1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2013 Jay Freeman (saurik)
5 /* GNU General Public License, Version 3 {{{ */
7 * Cydia is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
12 * Cydia is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Cydia. If not, see <http://www.gnu.org/licenses/>.
22 // XXX: wtf/FastMalloc.h... wtf?
23 #define USE_SYSTEM_MALLOC 1
25 /* #include Directives {{{ */
26 #include "CyteKit/UCPlatform.h"
27 #include "CyteKit/Localize.h"
29 #include <unicode/ustring.h>
30 #include <unicode/utrans.h>
32 #include <objc/objc.h>
33 #include <objc/runtime.h>
35 #include <CoreGraphics/CoreGraphics.h>
36 #include <Foundation/Foundation.h>
39 #define DEPLOYMENT_TARGET_MACOSX 1
40 #define CF_BUILDING_CF 1
41 #include <CoreFoundation/CFInternal.h>
44 #include <CoreFoundation/CFUniChar.h>
46 #include <SystemConfiguration/SystemConfiguration.h>
48 #include <UIKit/UIKit.h>
49 #include "iPhonePrivate.h"
51 #include <IOKit/IOKitLib.h>
53 #include <QuartzCore/CALayer.h>
55 #include <WebCore/WebCoreThread.h>
56 #include <WebKit/DOMHTMLIFrameElement.h>
64 #include <ext/stdio_filebuf.h>
68 #include <apt-pkg/acquire.h>
69 #include <apt-pkg/acquire-item.h>
70 #include <apt-pkg/algorithms.h>
71 #include <apt-pkg/cachefile.h>
72 #include <apt-pkg/clean.h>
73 #include <apt-pkg/configuration.h>
74 #include <apt-pkg/debindexfile.h>
75 #include <apt-pkg/debmetaindex.h>
76 #include <apt-pkg/error.h>
77 #include <apt-pkg/init.h>
78 #include <apt-pkg/mmap.h>
79 #include <apt-pkg/pkgrecords.h>
80 #include <apt-pkg/sha1.h>
81 #include <apt-pkg/sourcelist.h>
82 #include <apt-pkg/sptr.h>
83 #include <apt-pkg/strutl.h>
84 #include <apt-pkg/tagfile.h>
86 #include <apr-1/apr_pools.h>
88 #include <sys/types.h>
90 #include <sys/sysctl.h>
91 #include <sys/param.h>
92 #include <sys/mount.h>
93 #include <sys/reboot.h>
100 #include <mach-o/nlist.h>
109 #include <Cytore.hpp>
112 #include <CydiaSubstrate/CydiaSubstrate.h>
113 #include "Menes/Menes.h"
115 #include "CyteKit/IndirectDelegate.h"
116 #include "CyteKit/PerlCompatibleRegEx.hpp"
117 #include "CyteKit/TableViewCell.h"
118 #include "CyteKit/TabBarController.h"
119 #include "CyteKit/WebScriptObject-Cyte.h"
120 #include "CyteKit/WebViewController.h"
121 #include "CyteKit/WebViewTableViewCell.h"
122 #include "CyteKit/stringWithUTF8Bytes.h"
124 #include "Cydia/MIMEAddress.h"
125 #include "Cydia/LoadingViewController.h"
126 #include "Cydia/ProgressEvent.h"
128 #include "SDURLCache/SDURLCache.h"
135 #define _timestamp ({ \
137 gettimeofday(&tv, NULL); \
138 tv.tv_sec * 1000000 + tv.tv_usec; \
141 typedef std::vector<class ProfileTime *> TimeList;
151 ProfileTime(const char *name) :
155 times_.push_back(this);
158 void AddTime(uint64_t time) {
165 std::cerr << std::setw(7) << count_ << ", " << std::setw(8) << total_ << " : " << name_ << std::endl;
177 ProfileTimer(ProfileTime &time) :
184 time_.AddTime(_timestamp - start_);
189 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
191 std::cerr << "========" << std::endl;
194 #define _profile(name) { \
195 static ProfileTime name(#name); \
196 ProfileTimer _ ## name(name);
201 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
202 #define synchronized(lock) \
203 synchronized(static_cast<NSObject *>(lock))
205 extern NSString *Cydia_;
207 #define lprintf(args...) fprintf(stderr, args)
210 #define TraceLogging (1 && !ForRelease)
211 #define HistogramInsertionSort (0 && !ForRelease)
212 #define ProfileTimes (0 && !ForRelease)
213 #define ForSaurik (0 && !ForRelease)
214 #define LogBrowser (0 && !ForRelease)
215 #define TrackResize (0 && !ForRelease)
216 #define ManualRefresh (1 && !ForRelease)
217 #define ShowInternals (0 && !ForRelease)
218 #define AlwaysReload (0 && !ForRelease)
222 #define _trace(args...)
227 #define _profile(name) {
230 #define PrintTimes() do {} while (false)
233 // Hash Functions/Structures {{{
234 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
242 static NSString *Colon_;
244 static NSString *Error_;
245 static NSString *Warning_;
247 static NSString *Cache_;
249 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
251 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
253 static NSString *UniqueIdentifier(UIDevice *device = nil) {
254 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
255 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
257 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
260 static bool IsReachable(const char *name) {
261 SCNetworkReachabilityFlags flags; {
262 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
263 SCNetworkReachabilityGetFlags(reachability, &flags);
264 CFRelease(reachability);
267 // XXX: this elaborate mess is what Apple is using to determine this? :(
268 // XXX: do we care if the user has to intervene? maybe that's ok?
270 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
271 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
272 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
273 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
274 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
275 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
280 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
282 static _finline NSString *CydiaURL(NSString *path) {
284 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
285 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
286 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
287 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
288 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
290 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
293 static void ReapZombie(pid_t pid) {
296 if (waitpid(pid, &status, 0) == -1)
302 static _finline void UpdateExternalStatus(uint64_t newStatus) {
304 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
305 notify_set_state(notify_token, newStatus);
306 notify_cancel(notify_token);
308 notify_post("com.saurik.Cydia.status");
311 static CGFloat CYStatusBarHeight() {
312 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
313 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
316 /* NSForcedOrderingSearch doesn't work on the iPhone */
317 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
318 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
319 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
321 /* Insertion Sort {{{ */
323 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
324 const char *ptr = (const char *)list;
326 CFIndex half = count / 2;
327 const char *probe = ptr + elementSize * half;
328 CFComparisonResult cr = comparator(element, probe, context);
329 if (0 == cr) return (probe - (const char *)list) / elementSize;
330 ptr = (cr < 0) ? ptr : probe + elementSize;
331 count = (cr < 0) ? half : (half + (count & 1) - 1);
333 return (ptr - (const char *)list) / elementSize;
336 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
337 const char *ptr = (const char *)list;
339 CFIndex half = count / 2;
340 const char *probe = ptr + elementSize * half;
341 CFComparisonResult cr = comparator(element, probe, context);
342 if (0 == cr) return (probe - (const char *)list) / elementSize;
343 ptr = (cr < 0) ? ptr : probe + elementSize;
344 count = (cr < 0) ? half : (half + (count & 1) - 1);
346 return (ptr - (const char *)list) / elementSize;
349 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
350 if (range.length == 0)
352 const void **values(new const void *[range.length]);
353 CFArrayGetValues(array, range, values);
355 #if HistogramInsertionSort > 0
356 uint32_t total(0), *offsets(new uint32_t[range.length]);
359 for (CFIndex index(1); index != range.length; ++index) {
360 const void *value(values[index]);
361 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
362 CFIndex correct(index);
363 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
364 #if HistogramInsertionSort > 1
365 NSLog(@"%@ < %@", value, values[correct - 1]);
370 if (correct != index) {
371 size_t offset(index - correct);
372 #if HistogramInsertionSort
376 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
378 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
379 values[correct] = value;
383 CFArrayReplaceValues(array, range, values, range.length);
386 #if HistogramInsertionSort > 0
387 for (CFIndex index(0); index != range.length; ++index)
388 if (offsets[index] != 0)
389 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
390 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
397 /* Apple Bug Fixes {{{ */
398 @implementation UIWebDocumentView (Cydia)
400 - (void) _setScrollerOffset:(CGPoint)offset {
401 UIScroller *scroller([self _scroller]);
403 CGSize size([scroller contentSize]);
404 CGSize bounds([scroller bounds].size);
407 max.x = size.width - bounds.width;
408 max.y = size.height - bounds.height;
416 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
417 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
419 [scroller setOffset:offset];
425 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
426 size_t length([self length] - state->state);
429 else if (length > count)
431 for (size_t i(0); i != length; ++i)
432 objects[i] = [self item:state->state++];
433 state->itemsPtr = objects;
434 state->mutationsPtr = (unsigned long *) self;
438 /* Cydia NSString Additions {{{ */
439 @interface NSString (Cydia)
440 - (NSComparisonResult) compareByPath:(NSString *)other;
441 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
444 @implementation NSString (Cydia)
446 - (NSComparisonResult) compareByPath:(NSString *)other {
447 NSString *prefix = [self commonPrefixWithString:other options:0];
448 size_t length = [prefix length];
450 NSRange lrange = NSMakeRange(length, [self length] - length);
451 NSRange rrange = NSMakeRange(length, [other length] - length);
453 lrange = [self rangeOfString:@"/" options:0 range:lrange];
454 rrange = [other rangeOfString:@"/" options:0 range:rrange];
456 NSComparisonResult value;
458 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
459 value = NSOrderedSame;
460 else if (lrange.location == NSNotFound)
461 value = NSOrderedAscending;
462 else if (rrange.location == NSNotFound)
463 value = NSOrderedDescending;
465 value = NSOrderedSame;
467 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
468 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
469 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
470 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
472 NSComparisonResult result = [lpath compare:rpath];
473 return result == NSOrderedSame ? value : result;
476 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
477 return [(id)CFURLCreateStringByAddingPercentEscapes(
482 kCFStringEncodingUTF8
489 /* C++ NSString Wrapper Cache {{{ */
490 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
491 return size == 0 ? NULL :
492 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
493 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
496 static _finline CFStringRef CYStringCreate(const char *data) {
497 return CYStringCreate(data, strlen(data));
506 _finline void clear_() {
507 if (cache_ != NULL) {
514 _finline bool empty() const {
518 _finline size_t size() const {
522 _finline char *data() const {
526 _finline void clear() {
531 _finline CYString() :
538 _finline ~CYString() {
542 void operator =(const CYString &rhs) {
546 if (rhs.cache_ == nil)
549 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
552 void copy(apr_pool_t *pool) {
553 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
554 memcpy(temp, data_, size_);
559 void set(apr_pool_t *pool, const char *data, size_t size) {
565 data_ = const_cast<char *>(data);
573 _finline void set(apr_pool_t *pool, const char *data) {
574 set(pool, data, data == NULL ? 0 : strlen(data));
577 _finline void set(apr_pool_t *pool, const std::string &rhs) {
578 set(pool, rhs.data(), rhs.size());
581 bool operator ==(const CYString &rhs) const {
582 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
585 _finline operator CFStringRef() {
587 cache_ = CYStringCreate(data_, size_);
591 _finline operator id() {
592 return (NSString *) static_cast<CFStringRef>(*this);
595 _finline operator const char *() {
596 return reinterpret_cast<const char *>(data_);
600 /* C++ NSString Algorithm Adapters {{{ */
602 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
605 struct NSStringMapHash :
606 std::unary_function<NSString *, size_t>
608 _finline size_t operator ()(NSString *value) const {
609 return CFStringHashNSString((CFStringRef) value);
613 struct NSStringMapLess :
614 std::binary_function<NSString *, NSString *, bool>
616 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
617 return [lhs compare:rhs] == NSOrderedAscending;
621 struct NSStringMapEqual :
622 std::binary_function<NSString *, NSString *, bool>
624 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
625 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
626 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
627 //[lhs isEqualToString:rhs];
632 /* CoreGraphics Primitives {{{ */
637 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
638 CGFloat color[] = {red, green, blue, alpha};
639 return CGColorCreate(space, color);
648 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
649 color_(Create_(space, red, green, blue, alpha))
651 Set(space, red, green, blue, alpha);
656 CGColorRelease(color_);
663 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
665 color_ = Create_(space, red, green, blue, alpha);
668 operator CGColorRef() {
674 /* Random Global Variables {{{ */
675 static int PulseInterval_ = 500000;
677 static const NSString *UI_;
680 static bool RestartSubstrate_;
681 static NSArray *Finishes_;
683 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
684 #define NotifyConfig_ "/etc/notify.conf"
686 static bool Queuing_;
688 static CYColor Blue_;
689 static CYColor Blueish_;
690 static CYColor Black_;
691 static CYColor Folder_;
693 static CYColor White_;
694 static CYColor Gray_;
695 static CYColor Green_;
696 static CYColor Purple_;
697 static CYColor Purplish_;
699 static UIColor *InstallingColor_;
700 static UIColor *RemovingColor_;
702 static NSString *App_;
704 static BOOL Advanced_;
705 static BOOL Ignored_;
707 static _H<UIFont> Font12_;
708 static _H<UIFont> Font12Bold_;
709 static _H<UIFont> Font14_;
710 static _H<UIFont> Font18_;
711 static _H<UIFont> Font18Bold_;
712 static _H<UIFont> Font22Bold_;
714 static const char *Machine_ = NULL;
715 static _H<NSString> System_;
716 static NSString *SerialNumber_ = nil;
717 static NSString *ChipID_ = nil;
718 static NSString *BBSNum_ = nil;
719 static _H<NSString> Token_;
720 static _H<NSString> UniqueID_;
721 static _H<NSString> UserAgent_;
722 static _H<NSString> Product_;
723 static _H<NSString> Safari_;
725 static _H<NSLocale> CollationLocale_;
726 static _H<NSArray> CollationThumbs_;
727 static std::vector<NSInteger> CollationOffset_;
728 static _H<NSArray> CollationTitles_;
729 static _H<NSArray> CollationStarts_;
730 static UTransliterator *CollationTransl_;
731 //static Function<NSString *, NSString *> CollationModify_;
733 typedef std::basic_string<UChar> ustring;
734 static ustring CollationString_;
736 #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
737 #define UC ustring &str(*reinterpret_cast<ustring *>(rep))
738 static struct UReplaceableCallbacks CollationUCalls_ = {
739 .length = [](const UReplaceable *rep) -> int32_t { CUC;
743 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
744 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
745 if (offset >= str.size())
750 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
751 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
752 if (offset >= str.size())
755 U16_GET(str.data(), 0, offset, str.size(), c);
759 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
760 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
761 str.replace(start, limit - start, text, length);
764 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
765 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
766 str.copy(dst, limit - start, start);
769 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
770 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
771 str.replace(dest, 0, str, start, limit - start);
775 static CFLocaleRef Locale_;
776 static NSArray *Languages_;
777 static CGColorSpaceRef space_;
779 static NSDictionary *SectionMap_;
780 static NSMutableDictionary *Metadata_;
781 static _transient NSMutableDictionary *Settings_;
782 static _transient NSMutableDictionary *Packages_;
783 static _transient NSMutableDictionary *Values_;
784 static _transient NSMutableDictionary *Sections_;
785 _H<NSMutableDictionary> Sources_;
786 static _transient NSNumber *Version_;
791 static CGFloat ScreenScale_;
792 static NSString *Idiom_;
793 static _H<NSString> Firmware_;
794 static NSString *Major_;
796 static _H<NSMutableDictionary> SessionData_;
797 static _H<NSObject> HostConfig_;
798 static _H<NSMutableSet> BridgedHosts_;
799 static _H<NSMutableSet> TokenHosts_;
800 static _H<NSMutableSet> InsecureHosts_;
801 static _H<NSMutableSet> PipelinedHosts_;
802 static _H<NSMutableSet> CachedURLs_;
804 static NSString *kCydiaProgressEventTypeError = @"Error";
805 static NSString *kCydiaProgressEventTypeInformation = @"Information";
806 static NSString *kCydiaProgressEventTypeStatus = @"Status";
807 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
810 /* Display Helpers {{{ */
811 inline float Interpolate(float begin, float end, float fraction) {
812 return (end - begin) * fraction + begin;
815 static _finline const char *StripVersion_(const char *version) {
816 const char *colon(strchr(version, ':'));
817 return colon == NULL ? version : colon + 1;
820 NSString *LocalizeSection(NSString *section) {
821 static Pcre title_r("^(.*?) \\((.*)\\)$");
822 if (title_r(section)) {
823 NSString *parent(title_r[1]);
824 NSString *child(title_r[2]);
826 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
827 LocalizeSection(parent),
828 LocalizeSection(child)
832 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
835 NSString *Simplify(NSString *title) {
836 const char *data = [title UTF8String];
837 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
839 static Pcre square_r("^\\[(.*)\\]$");
840 if (square_r(data, size))
841 return Simplify(square_r[1]);
843 static Pcre paren_r("^\\((.*)\\)$");
844 if (paren_r(data, size))
845 return Simplify(paren_r[1]);
847 static Pcre title_r("^(.*?) \\((.*)\\)$");
848 if (title_r(data, size))
849 return Simplify(title_r[1]);
855 NSString *GetLastUpdate() {
856 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
859 return UCLocalize("NEVER_OR_UNKNOWN");
861 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
862 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
864 CFRelease(formatter);
866 return [(NSString *) formatted autorelease];
869 bool isSectionVisible(NSString *section) {
870 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
871 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
872 return hidden == nil || ![hidden boolValue];
875 static NSObject *CYIOGetValue(const char *path, NSString *property) {
876 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
877 if (entry == MACH_PORT_NULL)
880 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
881 IOObjectRelease(entry);
885 return [(id) value autorelease];
888 static NSString *CYHex(NSData *data, bool reverse = false) {
892 size_t length([data length]);
893 uint8_t bytes[length];
894 [data getBytes:bytes];
896 char string[length * 2 + 1];
897 for (size_t i(0); i != length; ++i)
898 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
900 return [NSString stringWithUTF8String:string];
905 /* Delegate Prototypes {{{ */
908 @class CydiaProgressEvent;
910 @protocol DatabaseDelegate
911 - (void) repairWithSelector:(SEL)selector;
912 - (void) setConfigurationData:(NSString *)data;
913 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
916 @class CYPackageController;
918 @protocol SourceDelegate
919 - (void) setFetch:(NSNumber *)fetch;
922 @protocol FetchDelegate
923 - (bool) isSourceCancelled;
924 - (void) startSourceFetch:(NSString *)uri;
925 - (void) stopSourceFetch:(NSString *)uri;
928 @protocol CydiaDelegate
929 - (void) returnToCydia;
931 - (void) retainNetworkActivityIndicator;
932 - (void) releaseNetworkActivityIndicator;
933 - (void) clearPackage:(Package *)package;
934 - (void) installPackage:(Package *)package;
935 - (void) installPackages:(NSArray *)packages;
936 - (void) removePackage:(Package *)package;
937 - (void) beginUpdate;
939 - (bool) requestUpdate;
940 - (void) distUpgrade;
943 - (void) _saveConfig;
945 - (void) addSource:(NSDictionary *)source;
946 - (void) addTrivialSource:(NSString *)href;
947 - (UIProgressHUD *) addProgressHUD;
948 - (void) removeProgressHUD:(UIProgressHUD *)hud;
949 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
950 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
954 /* CancelStatus {{{ */
956 public pkgAcquireStatus
967 virtual bool MediaChange(std::string media, std::string drive) {
971 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
975 virtual bool Pulse_(pkgAcquire *Owner) = 0;
977 virtual bool Pulse(pkgAcquire *Owner) {
978 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
986 _finline bool WasCancelled() const {
991 /* DelegateStatus {{{ */
996 _transient NSObject<ProgressDelegate> *delegate_;
1004 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1005 delegate_ = delegate;
1008 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1009 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1010 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
1011 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1014 virtual void Done(pkgAcquire::ItemDesc &item) {
1015 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1016 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
1017 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1020 virtual void Fail(pkgAcquire::ItemDesc &item) {
1022 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1023 item.Owner->Status == pkgAcquire::Item::StatDone
1027 std::string &error(item.Owner->ErrorText);
1031 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
1032 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1035 virtual bool Pulse_(pkgAcquire *Owner) {
1037 double(CurrentBytes + CurrentItems) /
1038 double(TotalBytes + TotalItems)
1041 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1042 [NSNumber numberWithDouble:percent], @"Percent",
1044 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1045 [NSNumber numberWithDouble:TotalBytes], @"Total",
1046 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1047 nil] waitUntilDone:YES];
1049 return ![delegate_ isProgressCancelled];
1052 virtual void Start() {
1053 pkgAcquireStatus::Start();
1054 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1057 virtual void Stop() {
1058 pkgAcquireStatus::Stop();
1059 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1060 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1064 /* Database Interface {{{ */
1065 typedef std::map< unsigned long, _H<Source> > SourceMap;
1067 @interface Database : NSObject {
1073 pkgCacheFile cache_;
1074 pkgDepCache::Policy *policy_;
1075 pkgRecords *records_;
1076 pkgProblemResolver *resolver_;
1077 pkgAcquire *fetcher_;
1079 SPtr<pkgPackageManager> manager_;
1080 pkgSourceList *list_;
1082 SourceMap sourceMap_;
1083 _H<NSMutableArray> sourceList_;
1085 CFMutableArrayRef packages_;
1087 _transient NSObject<DatabaseDelegate> *delegate_;
1088 _transient NSObject<ProgressDelegate> *progress_;
1090 CydiaStatus status_;
1096 std::map<const char *, _H<NSString> > sections_;
1099 + (Database *) sharedInstance;
1102 - (void) _readCydia:(NSNumber *)fd;
1103 - (void) _readStatus:(NSNumber *)fd;
1104 - (void) _readOutput:(NSNumber *)fd;
1108 - (Package *) packageWithName:(NSString *)name;
1110 - (pkgCacheFile &) cache;
1111 - (pkgDepCache::Policy *) policy;
1112 - (pkgRecords *) records;
1113 - (pkgProblemResolver *) resolver;
1114 - (pkgAcquire &) fetcher;
1115 - (pkgSourceList &) list;
1116 - (NSArray *) packages;
1117 - (NSArray *) sources;
1118 - (Source *) sourceWithKey:(NSString *)key;
1119 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1127 - (void) updateWithStatus:(CancelStatus &)status;
1129 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1131 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1132 - (NSObject<ProgressDelegate> *) progressDelegate;
1134 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1135 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1136 - (void) resetFetch;
1138 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1142 /* SourceStatus {{{ */
1143 class SourceStatus :
1147 _transient NSObject<FetchDelegate> *delegate_;
1148 _transient Database *database_;
1151 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1152 delegate_(delegate),
1157 void Set(bool fetch, pkgAcquire::ItemDesc &desc) {
1159 [database_ setFetch:fetch forURI:desc.Owner->DescURI().c_str()];
1162 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1166 virtual void Done(pkgAcquire::ItemDesc &desc) {
1170 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1174 virtual bool Pulse_(pkgAcquire *Owner) {
1175 for (pkgAcquire::ItemCIterator item = Owner->ItemsBegin(); item != Owner->ItemsEnd(); ++item)
1176 if ((*item)->ID != 0);
1177 else if ((*item)->Status == pkgAcquire::Item::StatIdle) {
1179 [database_ setFetch:true forURI:(*item)->DescURI().c_str()];
1180 } else (*item)->ID = 0;
1181 return ![delegate_ isSourceCancelled];
1184 virtual void Stop() {
1185 pkgAcquireStatus::Stop();
1186 [database_ resetFetch];
1190 /* ProgressEvent Implementation {{{ */
1191 @implementation CydiaProgressEvent
1193 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1194 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1197 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1198 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1199 [event setPackage:package];
1203 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1204 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1206 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1207 NSArray *fields([description componentsSeparatedByString:@" "]);
1208 [event setItem:fields];
1210 if ([fields count] > 3) {
1211 [event setPackage:[fields objectAtIndex:2]];
1212 [event setVersion:[fields objectAtIndex:3]];
1215 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1220 + (NSArray *) _attributeKeys {
1221 return [NSArray arrayWithObjects:
1231 - (NSArray *) attributeKeys {
1232 return [[self class] _attributeKeys];
1235 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1236 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1239 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1240 if ((self = [super init]) != nil) {
1246 - (NSString *) message {
1250 - (NSString *) type {
1254 - (NSArray *) item {
1255 return (id) item_ ?: [NSNull null];
1258 - (void) setItem:(NSArray *)item {
1262 - (NSString *) package {
1263 return (id) package_ ?: [NSNull null];
1266 - (void) setPackage:(NSString *)package {
1270 - (NSString *) url {
1271 return (id) url_ ?: [NSNull null];
1274 - (void) setURL:(NSString *)url {
1278 - (void) setVersion:(NSString *)version {
1282 - (NSString *) version {
1283 return (id) version_ ?: [NSNull null];
1286 - (NSString *) compound:(NSString *)value {
1288 NSString *mode(nil); {
1289 NSString *type([self type]);
1290 if ([type isEqualToString:kCydiaProgressEventTypeError])
1291 mode = UCLocalize("ERROR");
1292 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1293 mode = UCLocalize("WARNING");
1297 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1303 - (NSString *) compoundMessage {
1304 return [self compound:[self message]];
1307 - (NSString *) compoundTitle {
1310 if (package_ == nil)
1312 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1313 title = [package name];
1317 return [self compound:title];
1323 // Cytore Definitions {{{
1324 struct PackageValue :
1327 Cytore::Offset<PackageValue> next_;
1329 uint32_t index_ : 23;
1330 uint32_t subscribed_ : 1;
1347 Cytore::Offset<PackageValue> packages_[1 << 16];
1350 static Cytore::File<MetaValue> MetaFile_;
1352 // Cytore Helper Functions {{{
1353 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1354 SplitHash nhash = { hashlittle(name, length) };
1356 PackageValue *metadata;
1358 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1359 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1360 *offset = MetaFile_.New<PackageValue>(length + 1);
1361 metadata = &MetaFile_.Get(*offset);
1363 if (metadata == NULL) {
1367 metadata = new PackageValue();
1368 memset(metadata, 0, sizeof(*metadata));
1371 memcpy(metadata->name_, name, length);
1372 metadata->name_[length] = '\0';
1373 metadata->nhash_ = nhash.u16[1];
1375 metadata = &MetaFile_.Get(*offset);
1376 if (metadata->nhash_ != nhash.u16[1])
1378 if (strncmp(metadata->name_, name, length) != 0)
1380 if (metadata->name_[length] != '\0')
1387 static void PackageImport(const void *key, const void *value, void *context) {
1388 bool &fail(*reinterpret_cast<bool *>(context));
1391 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1392 NSLog(@"failed to import package %@", key);
1396 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1397 NSDictionary *package((NSDictionary *) value);
1399 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1400 if ([subscribed boolValue] && !metadata->subscribed_)
1401 metadata->subscribed_ = true;
1403 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1404 time_t time([date timeIntervalSince1970]);
1405 if (metadata->first_ > time || metadata->first_ == 0)
1406 metadata->first_ = time;
1409 NSDate *date([package objectForKey:@"LastSeen"]);
1410 NSString *version([package objectForKey:@"LastVersion"]);
1412 if (date != nil && version != nil) {
1413 time_t time([date timeIntervalSince1970]);
1414 if (metadata->last_ < time || metadata->last_ == 0)
1415 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1416 size_t length(strlen(buffer));
1417 uint16_t vhash(hashlittle(buffer, length));
1419 size_t capped(std::min<size_t>(8, length));
1420 char *latest(buffer + length - capped);
1422 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1423 metadata->vhash_ = vhash;
1425 metadata->last_ = time;
1431 /* Source Class {{{ */
1432 @interface Source : NSObject {
1434 Database *database_;
1437 CYString depiction_;
1438 CYString description_;
1444 CYString distribution_;
1450 _H<NSString> authority_;
1452 CYString defaultIcon_;
1454 _H<NSMutableDictionary> record_;
1457 std::set<std::string> fetches_;
1458 std::set<std::string> files_;
1459 _transient NSObject<SourceDelegate> *delegate_;
1462 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1464 - (NSComparisonResult) compareByName:(Source *)source;
1466 - (NSString *) depictionForPackage:(NSString *)package;
1467 - (NSString *) supportForPackage:(NSString *)package;
1469 - (metaIndex *) metaIndex;
1470 - (NSDictionary *) record;
1473 - (NSString *) rooturi;
1474 - (NSString *) distribution;
1475 - (NSString *) type;
1478 - (NSString *) host;
1480 - (NSString *) name;
1481 - (NSString *) shortDescription;
1482 - (NSString *) label;
1483 - (NSString *) origin;
1484 - (NSString *) version;
1486 - (NSString *) defaultIcon;
1487 - (NSURL *) iconURL;
1489 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1490 - (void) resetFetch;
1494 @implementation Source
1496 + (NSString *) webScriptNameForSelector:(SEL)selector {
1498 else if (selector == @selector(addSection:))
1499 return @"addSection";
1500 else if (selector == @selector(getField:))
1502 else if (selector == @selector(removeSection:))
1503 return @"removeSection";
1504 else if (selector == @selector(remove))
1510 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1511 return [self webScriptNameForSelector:selector] == nil;
1514 + (NSArray *) _attributeKeys {
1515 return [NSArray arrayWithObjects:
1526 @"shortDescription",
1533 - (NSArray *) attributeKeys {
1534 return [[self class] _attributeKeys];
1537 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1538 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1541 - (metaIndex *) metaIndex {
1545 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1546 trusted_ = index->IsTrusted();
1548 uri_.set(pool, index->GetURI());
1549 distribution_.set(pool, index->GetDist());
1550 type_.set(pool, index->GetType());
1552 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1553 if (dindex != NULL) {
1554 std::string file(dindex->MetaIndexURI(""));
1555 base_.set(pool, file);
1558 _profile(Source$setMetaIndex$GetIndexes)
1559 dindex->GetIndexes(&acquire, true);
1561 _profile(Source$setMetaIndex$DescURI)
1562 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1563 std::string file((*item)->DescURI());
1564 files_.insert(file);
1565 if (file.length() < sizeof("Packages.bz2") || file.substr(file.length() - sizeof("Packages.bz2")) != "/Packages.bz2")
1567 file = file.substr(0, file.length() - 4);
1568 files_.insert(file);
1569 files_.insert(file + ".gz");
1570 files_.insert(file + "Index");
1575 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1578 pkgTagFile tags(&fd);
1580 pkgTagSection section;
1587 {"default-icon", &defaultIcon_},
1588 {"depiction", &depiction_},
1589 {"description", &description_},
1591 {"origin", &origin_},
1592 {"support", &support_},
1593 {"version", &version_},
1596 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1597 const char *start, *end;
1599 if (section.Find(names[i].name_, start, end)) {
1600 CYString &value(*names[i].value_);
1601 value.set(pool, start, end - start);
1607 record_ = [Sources_ objectForKey:[self key]];
1609 NSURL *url([NSURL URLWithString:uri_]);
1613 host_ = [host_ lowercaseString];
1618 authority_ = [url path];
1621 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1622 if ((self = [super init]) != nil) {
1623 era_ = [database era];
1624 database_ = database;
1627 _profile(Source$initWithMetaIndex$setMetaIndex)
1628 [self setMetaIndex:index inPool:pool];
1633 - (NSString *) getField:(NSString *)name {
1634 @synchronized (database_) {
1635 if ([database_ era] != era_ || index_ == NULL)
1638 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1643 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1648 pkgTagFile tags(&fd);
1650 pkgTagSection section;
1653 const char *start, *end;
1654 if (!section.Find([name UTF8String], start, end))
1655 return (NSString *) [NSNull null];
1657 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1660 - (NSComparisonResult) compareByName:(Source *)source {
1661 NSString *lhs = [self name];
1662 NSString *rhs = [source name];
1664 if ([lhs length] != 0 && [rhs length] != 0) {
1665 unichar lhc = [lhs characterAtIndex:0];
1666 unichar rhc = [rhs characterAtIndex:0];
1668 if (isalpha(lhc) && !isalpha(rhc))
1669 return NSOrderedAscending;
1670 else if (!isalpha(lhc) && isalpha(rhc))
1671 return NSOrderedDescending;
1674 return [lhs compare:rhs options:LaxCompareOptions_];
1677 - (NSString *) depictionForPackage:(NSString *)package {
1678 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1681 - (NSString *) supportForPackage:(NSString *)package {
1682 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1685 - (NSArray *) sections {
1686 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1689 - (void) _addSection:(NSString *)section {
1692 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1693 if (![sections containsObject:section]) {
1694 [sections addObject:section];
1698 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1703 - (bool) addSection:(NSString *)section {
1707 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1711 - (void) _removeSection:(NSString *)section {
1715 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1716 if ([sections containsObject:section]) {
1717 [sections removeObject:section];
1722 - (bool) removeSection:(NSString *)section {
1726 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1731 [Sources_ removeObjectForKey:[self key]];
1736 bool value(record_ != nil);
1737 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1741 - (NSDictionary *) record {
1749 - (NSString *) rooturi {
1753 - (NSString *) distribution {
1754 return distribution_;
1757 - (NSString *) type {
1761 - (NSString *) baseuri {
1762 return base_.empty() ? nil : (id) base_;
1765 - (NSString *) iconuri {
1766 if (NSString *base = [self baseuri])
1767 return [base stringByAppendingString:@"CydiaIcon.png"];
1772 - (NSURL *) iconURL {
1773 if (NSString *uri = [self iconuri])
1774 return [NSURL URLWithString:uri];
1778 - (NSString *) key {
1779 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1782 - (NSString *) host {
1786 - (NSString *) name {
1787 return origin_.empty() ? (id) authority_ : origin_;
1790 - (NSString *) shortDescription {
1791 return description_;
1794 - (NSString *) label {
1795 return label_.empty() ? (id) authority_ : label_;
1798 - (NSString *) origin {
1802 - (NSString *) version {
1806 - (NSString *) defaultIcon {
1807 return defaultIcon_;
1810 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1811 delegate_ = delegate;
1815 return !fetches_.empty();
1818 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1820 if (fetches_.erase(uri) == 0)
1822 } else if (files_.find(uri) == files_.end())
1824 else if (!fetches_.insert(uri).second)
1827 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1830 - (void) resetFetch {
1832 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1837 /* CydiaOperation Class {{{ */
1838 @interface CydiaOperation : NSObject {
1839 _H<NSString> operator_;
1840 _H<NSString> value_;
1843 - (NSString *) operator;
1844 - (NSString *) value;
1848 @implementation CydiaOperation
1850 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1851 if ((self = [super init]) != nil) {
1852 operator_ = [NSString stringWithUTF8String:_operator];
1853 value_ = [NSString stringWithUTF8String:value];
1857 + (NSArray *) _attributeKeys {
1858 return [NSArray arrayWithObjects:
1864 - (NSArray *) attributeKeys {
1865 return [[self class] _attributeKeys];
1868 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1869 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1872 - (NSString *) operator {
1876 - (NSString *) value {
1882 /* CydiaClause Class {{{ */
1883 @interface CydiaClause : NSObject {
1884 _H<NSString> package_;
1885 _H<CydiaOperation> version_;
1888 - (NSString *) package;
1889 - (CydiaOperation *) version;
1893 @implementation CydiaClause
1895 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1896 if ((self = [super init]) != nil) {
1897 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1899 if (const char *version = dep.TargetVer())
1900 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1902 version_ = (id) [NSNull null];
1906 + (NSArray *) _attributeKeys {
1907 return [NSArray arrayWithObjects:
1913 - (NSArray *) attributeKeys {
1914 return [[self class] _attributeKeys];
1917 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1918 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1921 - (NSString *) package {
1925 - (CydiaOperation *) version {
1931 /* CydiaRelation Class {{{ */
1932 @interface CydiaRelation : NSObject {
1933 _H<NSString> relationship_;
1934 _H<NSMutableArray> clauses_;
1937 - (NSString *) relationship;
1938 - (NSArray *) clauses;
1942 @implementation CydiaRelation
1944 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1945 if ((self = [super init]) != nil) {
1946 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1947 clauses_ = [NSMutableArray arrayWithCapacity:8];
1949 pkgCache::DepIterator start;
1950 pkgCache::DepIterator end;
1951 dep.GlobOr(start, end); // ++dep
1954 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1956 // yes, seriously. (wtf?)
1964 + (NSArray *) _attributeKeys {
1965 return [NSArray arrayWithObjects:
1971 - (NSArray *) attributeKeys {
1972 return [[self class] _attributeKeys];
1975 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1976 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1979 - (NSString *) relationship {
1980 return relationship_;
1983 - (NSArray *) clauses {
1987 - (void) addClause:(CydiaClause *)clause {
1988 [clauses_ addObject:clause];
1993 /* Package Class {{{ */
1994 struct ParsedPackage {
1998 CYString architecture_;
2001 CYString depiction_;
2008 @interface Package : NSObject {
2010 @public uint32_t role_ : 3;
2011 uint32_t essential_ : 1;
2012 uint32_t obsolete_ : 1;
2013 uint32_t ignored_ : 1;
2014 uint32_t pooled_ : 1;
2020 _transient Database *database_;
2022 pkgCache::VerIterator version_;
2023 pkgCache::PkgIterator iterator_;
2024 pkgCache::VerFileIterator file_;
2028 CYString transform_;
2031 CYString installed_;
2034 const char *section_;
2035 _transient NSString *section$_;
2039 PackageValue *metadata_;
2040 ParsedPackage *parsed_;
2042 _H<NSMutableArray> tags_;
2045 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2046 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2048 - (pkgCache::PkgIterator) iterator;
2051 - (NSString *) section;
2052 - (NSString *) simpleSection;
2054 - (NSString *) longSection;
2055 - (NSString *) shortSection;
2059 - (MIMEAddress *) maintainer;
2061 - (NSString *) longDescription;
2062 - (NSString *) shortDescription;
2065 - (PackageValue *) metadata;
2068 - (bool) subscribed;
2069 - (bool) setSubscribed:(bool)subscribed;
2073 - (NSString *) latest;
2074 - (NSString *) installed;
2075 - (BOOL) uninstalled;
2078 - (BOOL) upgradableAndEssential:(BOOL)essential;
2081 - (BOOL) unfiltered;
2085 - (BOOL) halfConfigured;
2086 - (BOOL) halfInstalled;
2088 - (NSString *) mode;
2091 - (NSString *) name;
2093 - (NSString *) homepage;
2094 - (NSString *) depiction;
2095 - (MIMEAddress *) author;
2097 - (NSString *) support;
2099 - (NSArray *) files;
2100 - (NSArray *) warnings;
2101 - (NSArray *) applications;
2103 - (Source *) source;
2106 - (BOOL) matches:(NSArray *)query;
2108 - (BOOL) hasTag:(NSString *)tag;
2109 - (NSString *) primaryPurpose;
2110 - (NSArray *) purposes;
2111 - (bool) isCommercial;
2113 - (void) setIndex:(size_t)index;
2115 - (CYString &) cyname;
2117 - (uint32_t) compareBySection:(NSArray *)sections;
2124 uint32_t PackageChangesRadix(Package *self, void *) {
2129 uint32_t timestamp : 30;
2130 uint32_t ignored : 1;
2131 uint32_t upgradable : 1;
2135 bool upgradable([self upgradableAndEssential:YES]);
2136 value.bits.upgradable = upgradable ? 1 : 0;
2139 value.bits.timestamp = 0;
2140 value.bits.ignored = [self ignored] ? 0 : 1;
2141 value.bits.upgradable = 1;
2143 value.bits.timestamp = [self seen] >> 2;
2144 value.bits.ignored = 0;
2145 value.bits.upgradable = 0;
2148 return _not(uint32_t) - value.key;
2151 CYString &(*PackageName)(Package *self, SEL sel);
2153 uint32_t PackagePrefixRadix(Package *self, void *context) {
2154 size_t offset(reinterpret_cast<size_t>(context));
2155 CYString &name(PackageName(self, @selector(cyname)));
2157 size_t size(name.size());
2160 char *text(name.data());
2163 if (!isdigit(text[0]))
2167 while (size != digits && isdigit(text[digits]))
2175 if (offset == 0 && zeros != 0) {
2176 memset(data, '0', zeros);
2177 memcpy(data + zeros, text, 4 - zeros);
2179 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2180 if (size <= offset - zeros)
2183 text += offset - zeros;
2184 size -= offset - zeros;
2187 memcpy(data, text, 4);
2189 memcpy(data, text, size);
2190 memset(data + size, 0, 4 - size);
2193 for (size_t i(0); i != 4; ++i)
2194 if (isalpha(data[i]))
2202 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2204 /* XXX: ntohl may be more honest */
2205 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2208 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2209 _profile(PackageNameCompare)
2211 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2212 else if (rhn == NULL)
2213 return kCFCompareGreaterThan;
2215 CFIndex length(CFStringGetLength(lhn));
2217 _profile(PackageNameCompare$NumbersLast)
2218 if (length != 0 && CFStringGetLength(rhn) != 0) {
2219 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2220 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2221 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2222 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2223 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2227 _profile(PackageNameCompare$Compare)
2228 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2233 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2234 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2237 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2238 CYString &lhn(PackageName(lhs, @selector(cyname)));
2239 NSString *rhn(PackageName(rhs, @selector(cyname)));
2240 return StringNameCompare(lhn, rhn, lhn.size());
2243 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2244 return PackageNameCompare(*lhs, *rhs, arg);
2247 struct PackageNameOrdering :
2248 std::binary_function<Package *, Package *, bool>
2250 _finline bool operator ()(Package *lhs, Package *rhs) const {
2251 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2255 @implementation Package
2257 - (NSString *) description {
2258 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2263 apr_pool_destroy(pool_);
2264 if (parsed_ != NULL)
2269 + (NSString *) webScriptNameForSelector:(SEL)selector {
2271 else if (selector == @selector(clear))
2273 else if (selector == @selector(getField:))
2275 else if (selector == @selector(getRecord))
2276 return @"getRecord";
2277 else if (selector == @selector(hasTag:))
2279 else if (selector == @selector(install))
2281 else if (selector == @selector(remove))
2287 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2288 return [self webScriptNameForSelector:selector] == nil;
2291 + (NSArray *) _attributeKeys {
2292 return [NSArray arrayWithObjects:
2313 @"shortDescription",
2325 - (NSArray *) attributeKeys {
2326 return [[self class] _attributeKeys];
2329 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2330 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2333 - (NSArray *) relations {
2334 @synchronized (database_) {
2335 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2336 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2337 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2341 - (NSString *) architecture {
2343 @synchronized (database_) {
2344 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2347 - (NSString *) getField:(NSString *)name {
2348 @synchronized (database_) {
2349 if ([database_ era] != era_ || file_.end())
2352 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2354 const char *start, *end;
2355 if (!parser.Find([name UTF8String], start, end))
2356 return (NSString *) [NSNull null];
2358 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2361 - (NSString *) getRecord {
2362 @synchronized (database_) {
2363 if ([database_ era] != era_ || file_.end())
2366 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2368 const char *start, *end;
2369 parser.GetRec(start, end);
2371 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2375 if (parsed_ != NULL)
2377 @synchronized (database_) {
2378 if ([database_ era] != era_ || file_.end())
2381 ParsedPackage *parsed(new ParsedPackage);
2384 _profile(Package$parse)
2385 pkgRecords::Parser *parser;
2387 _profile(Package$parse$Lookup)
2388 parser = &[database_ records]->Lookup(file_);
2394 _profile(Package$parse$Find)
2399 {"architecture", &parsed->architecture_},
2400 {"icon", &parsed->icon_},
2401 {"depiction", &parsed->depiction_},
2402 {"homepage", &parsed->homepage_},
2403 {"website", &website},
2405 {"support", &parsed->support_},
2406 {"author", &parsed->author_},
2407 {"md5sum", &parsed->md5sum_},
2410 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2411 const char *start, *end;
2413 if (parser->Find(names[i].name_, start, end)) {
2414 CYString &value(*names[i].value_);
2415 _profile(Package$parse$Value)
2416 value.set(pool_, start, end - start);
2422 _profile(Package$parse$Tagline)
2423 const char *start, *end;
2424 if (parser->ShortDesc(start, end)) {
2425 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2428 while (stop != start && stop[-1] == '\r')
2430 parsed->tagline_.set(pool_, start, stop - start);
2434 _profile(Package$parse$Retain)
2435 if (parsed->homepage_.empty())
2436 parsed->homepage_ = website;
2437 if (parsed->homepage_ == parsed->depiction_)
2438 parsed->homepage_.clear();
2439 if (parsed->support_.empty())
2440 parsed->support_ = bugs;
2445 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2446 if ((self = [super init]) != nil) {
2447 _profile(Package$initWithVersion)
2449 apr_pool_create(&pool_, NULL);
2455 database_ = database;
2456 era_ = [database era];
2460 pkgCache::PkgIterator iterator(version.ParentPkg());
2461 iterator_ = iterator;
2463 _profile(Package$initWithVersion$Version)
2464 if (!version_.end())
2465 file_ = version_.FileList();
2467 pkgCache &cache([database_ cache]);
2468 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2472 _profile(Package$initWithVersion$Cache)
2473 name_.set(NULL, iterator.Display());
2475 latest_.set(NULL, StripVersion_(version_.VerStr()));
2477 pkgCache::VerIterator current(iterator.CurrentVer());
2479 installed_.set(NULL, StripVersion_(current.VerStr()));
2482 _profile(Package$initWithVersion$Transliterate) do {
2483 if (CollationTransl_ == NULL)
2488 _profile(Package$initWithVersion$Transliterate$utf8)
2489 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2490 for (size_t i(0), e(name_.size()); i != e; ++i)
2491 if (data[i] >= 0x80)
2496 UErrorCode code(U_ZERO_ERROR);
2499 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2500 CollationString_.resize(name_.size());
2501 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2502 if (!U_SUCCESS(code))
2504 CollationString_.resize(length);
2507 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2508 length = CollationString_.size();
2509 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2510 if (!U_SUCCESS(code))
2512 _assert(CollationString_.size() == length);
2515 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2516 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2517 if (code == U_BUFFER_OVERFLOW_ERROR)
2518 code = U_ZERO_ERROR;
2519 else if (!U_SUCCESS(code))
2524 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2525 transform = static_cast<char *>(apr_palloc(pool_, length));
2527 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2528 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2529 if (!U_SUCCESS(code))
2533 transform_.set(NULL, transform, length);
2534 } while (false); _end
2536 _profile(Package$initWithVersion$Tags)
2537 pkgCache::TagIterator tag(iterator.TagList());
2539 tags_ = [NSMutableArray arrayWithCapacity:8];
2541 goto tag; for (; !tag.end(); ++tag) tag: {
2542 const char *name(tag.Name());
2543 NSString *string((NSString *) CYStringCreate(name));
2547 [tags_ addObject:[string autorelease]];
2549 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2550 if (strcmp(name + 6, "enduser") == 0)
2552 else if (strcmp(name + 6, "hacker") == 0)
2554 else if (strcmp(name + 6, "developer") == 0)
2556 else if (strcmp(name + 6, "cydia") == 0)
2562 if (strncmp(name, "cydia::", 7) == 0) {
2563 if (strcmp(name + 7, "essential") == 0)
2565 else if (strcmp(name + 7, "obsolete") == 0)
2572 _profile(Package$initWithVersion$Metadata)
2573 const char *mixed(iterator.Name());
2574 size_t size(strlen(mixed));
2575 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2576 char lower[prefix + size + 5 + 1];
2578 for (size_t i(0); i != size; ++i)
2579 lower[prefix + i] = mixed[i] | 0x20;
2581 if (!installed_.empty()) {
2582 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2583 memcpy(lower + prefix + size, ".list", 6);
2585 if (stat(lower, &info) != -1)
2586 updated_ = info.st_birthtime;
2589 PackageValue *metadata(PackageFind(lower + prefix, size));
2590 metadata_ = metadata;
2592 id_.set(NULL, metadata->name_, size);
2594 const char *latest(version_.VerStr());
2595 size_t length(strlen(latest));
2597 uint16_t vhash(hashlittle(latest, length));
2599 size_t capped(std::min<size_t>(8, length));
2600 latest = latest + length - capped;
2602 if (metadata->first_ == 0)
2603 metadata->first_ = now_;
2605 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2606 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2607 metadata->vhash_ = vhash;
2608 metadata->last_ = now_;
2609 } else if (metadata->last_ == 0)
2610 metadata->last_ = metadata->first_;
2613 _profile(Package$initWithVersion$Section)
2614 section_ = version_.Section();
2617 _profile(Package$initWithVersion$Flags)
2618 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2619 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2624 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2625 pkgCache::VerIterator version;
2627 _profile(Package$packageWithIterator$GetCandidateVer)
2628 version = [database policy]->GetCandidateVer(iterator);
2636 _profile(Package$packageWithIterator$Allocate)
2637 package = [Package allocWithZone:zone];
2640 _profile(Package$packageWithIterator$Initialize)
2642 initWithVersion:version
2649 _profile(Package$packageWithIterator$Autorelease)
2650 package = [package autorelease];
2656 - (pkgCache::PkgIterator) iterator {
2660 - (NSString *) section {
2661 if (section$_ == nil) {
2662 if (section_ == NULL)
2665 _profile(Package$section$mappedSectionForPointer)
2666 section$_ = [database_ mappedSectionForPointer:section_];
2671 - (NSString *) simpleSection {
2672 if (NSString *section = [self section])
2673 return Simplify(section);
2678 - (NSString *) longSection {
2679 return LocalizeSection([self section]);
2682 - (NSString *) shortSection {
2683 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2686 - (NSString *) uri {
2689 pkgIndexFile *index;
2690 pkgCache::PkgFileIterator file(file_.File());
2691 if (![database_ list].FindIndex(file, index))
2693 return [NSString stringWithUTF8String:iterator_->Path];
2694 //return [NSString stringWithUTF8String:file.Site()];
2695 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2699 - (MIMEAddress *) maintainer {
2700 @synchronized (database_) {
2701 if ([database_ era] != era_ || file_.end())
2704 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2705 const std::string &maintainer(parser->Maintainer());
2706 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2709 - (NSString *) md5sum {
2710 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2714 @synchronized (database_) {
2715 if ([database_ era] != era_ || version_.end())
2718 return version_->InstalledSize;
2721 - (NSString *) longDescription {
2722 @synchronized (database_) {
2723 if ([database_ era] != era_ || file_.end())
2726 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2727 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2729 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2730 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2731 if ([lines count] < 2)
2734 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2735 for (size_t i(1), e([lines count]); i != e; ++i) {
2736 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2737 [trimmed addObject:trim];
2740 return [trimmed componentsJoinedByString:@"\n"];
2743 - (NSString *) shortDescription {
2744 if (parsed_ != NULL)
2745 return static_cast<NSString *>(parsed_->tagline_);
2747 @synchronized (database_) {
2748 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2750 const char *start, *end;
2751 if (!parser.ShortDesc(start, end))
2754 if (end - start > 200)
2758 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2761 while (end != start && end[-1] == '\r')
2765 return [(id) CYStringCreate(start, end - start) autorelease];
2769 _profile(Package$index)
2770 CFStringRef name((CFStringRef) [self name]);
2771 if (CFStringGetLength(name) == 0)
2773 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2774 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2776 return toupper(character);
2780 - (PackageValue *) metadata {
2785 PackageValue *metadata([self metadata]);
2786 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2789 - (bool) subscribed {
2790 return [self metadata]->subscribed_;
2793 - (bool) setSubscribed:(bool)subscribed {
2794 PackageValue *metadata([self metadata]);
2795 if (metadata->subscribed_ == subscribed)
2797 metadata->subscribed_ = subscribed;
2805 - (NSString *) latest {
2809 - (NSString *) installed {
2813 - (BOOL) uninstalled {
2814 return installed_.empty();
2818 return !version_.end();
2821 - (BOOL) upgradableAndEssential:(BOOL)essential {
2822 _profile(Package$upgradableAndEssential)
2823 pkgCache::VerIterator current(iterator_.CurrentVer());
2825 return essential && essential_;
2827 return !version_.end() && version_ != current;
2831 - (BOOL) essential {
2836 return [database_ cache][iterator_].InstBroken();
2839 - (BOOL) unfiltered {
2840 _profile(Package$unfiltered$obsolete)
2841 if (_unlikely(obsolete_))
2845 _profile(Package$unfiltered$role)
2846 if (_unlikely(role_ > 3))
2854 if (![self unfiltered])
2859 _profile(Package$visible$section)
2860 section = [self section];
2863 _profile(Package$visible$isSectionVisible)
2864 if (!isSectionVisible(section))
2872 unsigned char current(iterator_->CurrentState);
2873 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2876 - (BOOL) halfConfigured {
2877 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2880 - (BOOL) halfInstalled {
2881 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2885 @synchronized (database_) {
2886 if ([database_ era] != era_ || iterator_.end())
2889 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2890 return state.Mode != pkgDepCache::ModeKeep;
2893 - (NSString *) mode {
2894 @synchronized (database_) {
2895 if ([database_ era] != era_ || iterator_.end())
2898 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2900 switch (state.Mode) {
2901 case pkgDepCache::ModeDelete:
2902 if ((state.iFlags & pkgDepCache::Purge) != 0)
2906 case pkgDepCache::ModeKeep:
2907 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2908 return @"REINSTALL";
2909 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2913 case pkgDepCache::ModeInstall:
2914 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2915 return @"REINSTALL";
2916 else*/ switch (state.Status) {
2918 return @"DOWNGRADE";
2924 return @"NEW_INSTALL";
2935 - (NSString *) name {
2936 return name_.empty() ? id_ : name_;
2939 - (UIImage *) icon {
2940 NSString *section = [self simpleSection];
2943 if (parsed_ != NULL)
2944 if (NSString *href = parsed_->icon_)
2945 if ([href hasPrefix:@"file:///"])
2946 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2947 if (icon == nil) if (section != nil)
2948 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2949 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2950 if ([dicon hasPrefix:@"file:///"])
2951 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2953 icon = [UIImage applicationImageNamed:@"unknown.png"];
2957 - (NSString *) homepage {
2958 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2961 - (NSString *) depiction {
2962 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2965 - (MIMEAddress *) author {
2966 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2969 - (NSString *) support {
2970 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
2973 - (NSArray *) files {
2974 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2975 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2978 fin.open([path UTF8String]);
2983 while (std::getline(fin, line))
2984 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2989 - (NSString *) state {
2990 @synchronized (database_) {
2991 if ([database_ era] != era_ || file_.end())
2994 switch (iterator_->CurrentState) {
2995 case pkgCache::State::NotInstalled:
2996 return @"NotInstalled";
2997 case pkgCache::State::UnPacked:
2999 case pkgCache::State::HalfConfigured:
3000 return @"HalfConfigured";
3001 case pkgCache::State::HalfInstalled:
3002 return @"HalfInstalled";
3003 case pkgCache::State::ConfigFiles:
3004 return @"ConfigFiles";
3005 case pkgCache::State::Installed:
3006 return @"Installed";
3007 case pkgCache::State::TriggersAwaited:
3008 return @"TriggersAwaited";
3009 case pkgCache::State::TriggersPending:
3010 return @"TriggersPending";
3013 return (NSString *) [NSNull null];
3016 - (NSString *) selection {
3017 @synchronized (database_) {
3018 if ([database_ era] != era_ || file_.end())
3021 switch (iterator_->SelectedState) {
3022 case pkgCache::State::Unknown:
3024 case pkgCache::State::Install:
3026 case pkgCache::State::Hold:
3028 case pkgCache::State::DeInstall:
3029 return @"DeInstall";
3030 case pkgCache::State::Purge:
3034 return (NSString *) [NSNull null];
3037 - (NSArray *) warnings {
3038 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3039 const char *name(iterator_.Name());
3041 size_t length(strlen(name));
3042 if (length < 2) invalid:
3043 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3044 else for (size_t i(0); i != length; ++i)
3046 /* XXX: technically this is not allowed */
3047 (name[i] < 'A' || name[i] > 'Z') &&
3048 (name[i] < 'a' || name[i] > 'z') &&
3049 (name[i] < '0' || name[i] > '9') &&
3050 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3053 if (strcmp(name, "cydia") != 0) {
3056 bool _private = false;
3059 bool repository = [[self section] isEqualToString:@"Repositories"];
3061 if (NSArray *files = [self files])
3062 for (NSString *file in files)
3063 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3065 else if (!user && [file isEqualToString:@"/User"])
3067 else if (!_private && [file isEqualToString:@"/private"])
3069 else if (!stash && [file isEqualToString:@"/var/stash"])
3072 /* XXX: this is not sensitive enough. only some folders are valid. */
3073 if (cydia && !repository)
3074 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3076 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3078 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3080 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3083 return [warnings count] == 0 ? nil : warnings;
3086 - (NSArray *) applications {
3087 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3089 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3091 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
3092 if (NSArray *files = [self files])
3093 for (NSString *file in files)
3094 if (application_r(file)) {
3095 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3096 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3097 if ([id isEqualToString:me])
3100 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3102 display = application_r[1];
3104 NSString *bundle([file stringByDeletingLastPathComponent]);
3105 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3106 // XXX: maybe this should check if this is really a string, not just for length
3107 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3109 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3111 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3112 [applications addObject:application];
3114 [application addObject:id];
3115 [application addObject:display];
3116 [application addObject:url];
3119 return [applications count] == 0 ? nil : applications;
3122 - (Source *) source {
3123 if (source_ == nil) {
3124 @synchronized (database_) {
3125 if ([database_ era] != era_ || file_.end())
3126 source_ = (Source *) [NSNull null];
3128 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3132 return source_ == (Source *) [NSNull null] ? nil : source_;
3135 - (uint32_t) updated {
3136 return std::numeric_limits<uint32_t>::max() - updated_;
3143 - (BOOL) matches:(NSArray *)query {
3144 if (query == nil || [query count] == 0)
3153 string = [self name];
3154 length = [string length];
3157 for (NSString *term in query) {
3158 range = [string rangeOfString:term options:MatchCompareOptions_];
3159 if (range.location != NSNotFound)
3160 rank_ -= 6 * 1000000 / length;
3165 length = [string length];
3168 for (NSString *term in query) {
3169 range = [string rangeOfString:term options:MatchCompareOptions_];
3170 if (range.location != NSNotFound)
3171 rank_ -= 6 * 1000000 / length;
3175 string = [self shortDescription];
3176 length = [string length];
3177 NSUInteger stop(std::min<NSUInteger>(length, 200));
3180 for (NSString *term in query) {
3181 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3182 if (range.location != NSNotFound)
3183 rank_ -= 2 * 100000;
3189 - (NSArray *) tags {
3193 - (BOOL) hasTag:(NSString *)tag {
3194 return tags_ == nil ? NO : [tags_ containsObject:tag];
3197 - (NSString *) primaryPurpose {
3198 for (NSString *tag in (NSArray *) tags_)
3199 if ([tag hasPrefix:@"purpose::"])
3200 return [tag substringFromIndex:9];
3204 - (NSArray *) purposes {
3205 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3206 for (NSString *tag in (NSArray *) tags_)
3207 if ([tag hasPrefix:@"purpose::"])
3208 [purposes addObject:[tag substringFromIndex:9]];
3209 return [purposes count] == 0 ? nil : purposes;
3212 - (bool) isCommercial {
3213 return [self hasTag:@"cydia::commercial"];
3216 - (void) setIndex:(size_t)index {
3217 if (metadata_->index_ != index)
3218 metadata_->index_ = index;
3221 - (CYString &) cyname {
3222 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3225 - (uint32_t) compareBySection:(NSArray *)sections {
3226 NSString *section([self section]);
3227 for (size_t i(0), e([sections count]); i != e; ++i) {
3228 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3232 return _not(uint32_t);
3236 @synchronized (database_) {
3237 pkgProblemResolver *resolver = [database_ resolver];
3238 resolver->Clear(iterator_);
3240 pkgCacheFile &cache([database_ cache]);
3241 cache->SetReInstall(iterator_, false);
3242 cache->MarkKeep(iterator_, false);
3246 @synchronized (database_) {
3247 pkgProblemResolver *resolver = [database_ resolver];
3248 resolver->Clear(iterator_);
3249 resolver->Protect(iterator_);
3251 pkgCacheFile &cache([database_ cache]);
3252 cache->SetReInstall(iterator_, false);
3253 cache->MarkInstall(iterator_, false);
3255 pkgDepCache::StateCache &state((*cache)[iterator_]);
3256 if (!state.Install())
3257 cache->SetReInstall(iterator_, true);
3261 @synchronized (database_) {
3262 pkgProblemResolver *resolver = [database_ resolver];
3263 resolver->Clear(iterator_);
3264 resolver->Remove(iterator_);
3265 resolver->Protect(iterator_);
3267 pkgCacheFile &cache([database_ cache]);
3268 cache->SetReInstall(iterator_, false);
3269 cache->MarkDelete(iterator_, true);
3274 /* Section Class {{{ */
3275 @interface Section : NSObject {
3279 _H<NSString> localized_;
3282 - (NSComparisonResult) compareByLocalized:(Section *)section;
3283 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3284 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3285 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3287 - (NSString *) name;
3288 - (void) setName:(NSString *)name;
3294 - (void) addToCount;
3296 - (void) setCount:(size_t)count;
3297 - (NSString *) localized;
3301 @implementation Section
3303 - (NSComparisonResult) compareByLocalized:(Section *)section {
3304 NSString *lhs(localized_);
3305 NSString *rhs([section localized]);
3307 /*if ([lhs length] != 0 && [rhs length] != 0) {
3308 unichar lhc = [lhs characterAtIndex:0];
3309 unichar rhc = [rhs characterAtIndex:0];
3311 if (isalpha(lhc) && !isalpha(rhc))
3312 return NSOrderedAscending;
3313 else if (!isalpha(lhc) && isalpha(rhc))
3314 return NSOrderedDescending;
3317 return [lhs compare:rhs options:LaxCompareOptions_];
3320 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3321 if ((self = [self initWithName:name localize:NO]) != nil) {
3322 if (localized != nil)
3323 localized_ = localized;
3327 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3328 return [self initWithName:name row:0 localize:localize];
3331 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3332 if ((self = [super init]) != nil) {
3336 localized_ = LocalizeSection(name_);
3340 - (NSString *) name {
3344 - (void) setName:(NSString *)name {
3360 - (void) addToCount {
3364 - (void) setCount:(size_t)count {
3368 - (NSString *) localized {
3375 class CydiaLogCleaner :
3376 public pkgArchiveCleaner
3379 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3384 /* Database Implementation {{{ */
3385 @implementation Database
3387 + (Database *) sharedInstance {
3388 static _H<Database> instance;
3389 if (instance == nil)
3390 instance = [[[Database alloc] init] autorelease];
3398 - (void) releasePackages {
3399 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3400 CFArrayRemoveAllValues(packages_);
3404 // XXX: actually implement this thing
3406 [self releasePackages];
3407 apr_pool_destroy(pool_);
3408 NSRecycleZone(zone_);
3412 - (void) _readCydia:(NSNumber *)fd {
3413 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3414 std::istream is(&ib);
3417 static Pcre finish_r("^finish:([^:]*)$");
3419 while (std::getline(is, line)) {
3420 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3422 const char *data(line.c_str());
3423 size_t size = line.size();
3424 lprintf("C:%s\n", data);
3426 if (finish_r(data, size)) {
3427 NSString *finish = finish_r[1];
3428 int index = [Finishes_ indexOfObject:finish];
3429 if (index != INT_MAX && index > Finish_)
3439 - (void) _readStatus:(NSNumber *)fd {
3440 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3441 std::istream is(&ib);
3444 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3445 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3447 while (std::getline(is, line)) {
3448 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3450 const char *data(line.c_str());
3451 size_t size(line.size());
3452 lprintf("S:%s\n", data);
3454 if (conffile_r(data, size)) {
3455 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3456 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3457 } else if (strncmp(data, "status: ", 8) == 0) {
3458 // status: <package>: {unpacked,half-configured,installed}
3459 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3460 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3461 } else if (strncmp(data, "processing: ", 12) == 0) {
3462 // processing: configure: config-test
3463 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3464 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3465 } else if (pmstatus_r(data, size)) {
3466 std::string type([pmstatus_r[1] UTF8String]);
3468 NSString *package = pmstatus_r[2];
3469 if ([package isEqualToString:@"dpkg-exec"])
3472 float percent([pmstatus_r[3] floatValue]);
3473 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3475 NSString *string = pmstatus_r[4];
3477 if (type == "pmerror") {
3478 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3479 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3480 } else if (type == "pmstatus") {
3481 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3482 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3483 } else if (type == "pmconffile")
3484 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3486 lprintf("E:unknown pmstatus\n");
3488 lprintf("E:unknown status\n");
3496 - (void) _readOutput:(NSNumber *)fd {
3497 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3498 std::istream is(&ib);
3501 while (std::getline(is, line)) {
3502 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3504 lprintf("O:%s\n", line.c_str());
3506 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3507 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3519 - (Package *) packageWithName:(NSString *)name {
3522 @synchronized (self) {
3523 if (static_cast<pkgDepCache *>(cache_) == NULL)
3525 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3526 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3530 if ((self = [super init]) != nil) {
3537 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3538 apr_pool_create(&pool_, NULL);
3540 size_t capacity(MetaFile_->active_);
3546 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3547 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3551 _assert(pipe(fds) != -1);
3554 _config->Set("APT::Keep-Fds::", cydiafd_);
3555 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3558 detachNewThreadSelector:@selector(_readCydia:)
3560 withObject:[NSNumber numberWithInt:fds[0]]
3563 _assert(pipe(fds) != -1);
3567 detachNewThreadSelector:@selector(_readStatus:)
3569 withObject:[NSNumber numberWithInt:fds[0]]
3572 _assert(pipe(fds) != -1);
3573 _assert(dup2(fds[0], 0) != -1);
3574 _assert(close(fds[0]) != -1);
3576 input_ = fdopen(fds[1], "a");
3578 _assert(pipe(fds) != -1);
3579 _assert(dup2(fds[1], 1) != -1);
3580 _assert(close(fds[1]) != -1);
3583 detachNewThreadSelector:@selector(_readOutput:)
3585 withObject:[NSNumber numberWithInt:fds[0]]
3590 - (pkgCacheFile &) cache {
3594 - (pkgDepCache::Policy *) policy {
3598 - (pkgRecords *) records {
3602 - (pkgProblemResolver *) resolver {
3606 - (pkgAcquire &) fetcher {
3610 - (pkgSourceList &) list {
3614 - (NSArray *) packages {
3615 return (NSArray *) packages_;
3618 - (NSArray *) sources {
3622 - (Source *) sourceWithKey:(NSString *)key {
3623 for (Source *source in [self sources]) {
3624 if ([[source key] isEqualToString:key])
3629 - (bool) popErrorWithTitle:(NSString *)title {
3632 while (!_error->empty()) {
3634 bool warning(!_error->PopMessage(error));
3639 size_t size(error.size());
3640 if (size == 0 || error[size - 1] != '\n')
3642 error.resize(size - 1);
3645 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3647 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3648 if (warning && no_pubkey(error.c_str()))
3651 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3657 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3658 return [self popErrorWithTitle:title] || !success;
3661 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3662 @synchronized (self) {
3665 [self releasePackages];
3668 [sourceList_ removeAllObjects];
3688 apr_pool_clear(pool_);
3690 NSRecycleZone(zone_);
3691 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3693 int chk(creat("/tmp/cydia.chk", 0644));
3697 if (invocation != nil)
3698 [invocation invoke];
3700 NSString *title(UCLocalize("DATABASE"));
3702 list_ = new pkgSourceList();
3703 _profile(reloadDataWithInvocation$ReadMainList)
3704 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3708 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3709 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3710 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3711 [sourceList_ addObject:object];
3716 OpProgress progress;
3719 _profile(reloadDataWithInvocation$pkgCacheFile)
3720 opened = cache_.Open(progress, true);
3723 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3724 while (!_error->empty()) {
3726 bool warning(!_error->PopMessage(error));
3728 lprintf("cache_.Open():[%s]\n", error.c_str());
3730 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3734 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3735 repair = @selector(configure);
3736 //else if (error == "The package lists or status file could not be parsed or opened.")
3737 // repair = @selector(update);
3738 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3739 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3740 // else if (error == "Malformed Status line")
3741 // else if (error == "The list of sources could not be read.")
3743 if (repair != NULL) {
3745 [delegate_ repairWithSelector:repair];
3754 unlink("/tmp/cydia.chk");
3756 now_ = [[NSDate date] timeIntervalSince1970];
3758 policy_ = new pkgDepCache::Policy();
3759 records_ = new pkgRecords(cache_);
3760 resolver_ = new pkgProblemResolver(cache_);
3761 fetcher_ = new pkgAcquire(&status_);
3764 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3765 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3769 _profile(reloadDataWithInvocation$pkgApplyStatus)
3770 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3774 if (cache_->BrokenCount() != 0) {
3775 _profile(pkgApplyStatus$pkgFixBroken)
3776 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3780 if (cache_->BrokenCount() != 0) {
3781 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3785 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3786 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3791 for (Source *object in (id) sourceList_) {
3792 metaIndex *source([object metaIndex]);
3793 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3794 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3795 // XXX: this could be more intelligent
3796 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3797 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3799 sourceMap_[cached->ID] = object;
3804 /*std::vector<Package *> packages;
3805 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3808 _profile(reloadDataWithInvocation$packageWithIterator)
3809 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3810 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3811 //packages.push_back(package);
3812 CFArrayAppendValue(packages_, CFRetain(package));
3816 /*if (packages.empty())
3817 packages_ = [[NSArray alloc] init];
3819 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3822 _profile(reloadDataWithInvocation$radix$8)
3823 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3826 _profile(reloadDataWithInvocation$radix$4)
3827 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3830 _profile(reloadDataWithInvocation$radix$0)
3831 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3834 _profile(reloadDataWithInvocation$insertion)
3835 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3838 /*_profile(reloadDataWithInvocation$CFQSortArray)
3839 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3842 /*_profile(reloadDataWithInvocation$stdsort)
3843 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3846 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3847 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3850 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3851 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3855 size_t count(CFArrayGetCount(packages_));
3856 MetaFile_->active_ = count;
3857 for (size_t index(0); index != count; ++index)
3858 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3863 @synchronized (self) {
3865 resolver_ = new pkgProblemResolver(cache_);
3867 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3868 if (!cache_[iterator].Keep())
3869 cache_->MarkKeep(iterator, false);
3870 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3871 cache_->SetReInstall(iterator, false);
3874 - (void) configure {
3875 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3877 system([dpkg UTF8String]);
3882 @synchronized (self) {
3883 // XXX: I don't remember this condition
3888 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3890 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3892 if ([self popErrorWithTitle:title])
3896 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3898 CydiaLogCleaner cleaner;
3899 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3906 fetcher_->Shutdown();
3908 pkgRecords records(cache_);
3910 lock_ = new FileFd();
3911 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3913 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3915 if ([self popErrorWithTitle:title])
3919 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3922 manager_ = (_system->CreatePM(cache_));
3923 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3930 bool substrate(RestartSubstrate_);
3931 RestartSubstrate_ = false;
3933 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3935 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3937 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3939 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3940 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3943 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3945 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3947 [self popErrorWithTitle:title];
3951 bool failed = false;
3952 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3953 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3955 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3958 std::string uri = (*item)->DescURI();
3959 std::string error = (*item)->ErrorText;
3961 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3964 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3965 [delegate_ addProgressEventOnMainThread:event forTask:title];
3968 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3976 RestartSubstrate_ = true;
3979 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3980 if ([self popErrorWithTitle:title])
3983 if (result == pkgPackageManager::Failed) {
3988 if (result != pkgPackageManager::Completed) {
3993 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3995 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3997 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3998 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4001 if (![before isEqualToArray:after])
4006 NSString *title(UCLocalize("UPGRADE"));
4007 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4013 [self updateWithStatus:status_];
4016 - (void) updateWithStatus:(CancelStatus &)status {
4017 NSString *title(UCLocalize("REFRESHING_DATA"));
4020 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4024 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4025 if ([self popErrorWithTitle:title])
4028 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4030 bool success(ListUpdate(status, list, PulseInterval_));
4031 if (status.WasCancelled())
4034 [self popErrorWithTitle:title forOperation:success];
4035 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
4039 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4042 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4043 delegate_ = delegate;
4046 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4047 progress_ = delegate;
4048 status_.setDelegate(delegate);
4051 - (NSObject<ProgressDelegate> *) progressDelegate {
4055 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4056 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4057 return i == sourceMap_.end() ? nil : i->second;
4060 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4061 for (Source *source in (id) sourceList_)
4062 [source setFetch:fetch forURI:uri];
4065 - (void) resetFetch {
4066 for (Source *source in (id) sourceList_)
4067 [source resetFetch];
4070 - (NSString *) mappedSectionForPointer:(const char *)section {
4071 _H<NSString> *mapped;
4073 _profile(Database$mappedSectionForPointer$Cache)
4074 mapped = §ions_[section];
4077 if (*mapped == NULL) {
4078 size_t length(strlen(section));
4079 char spaced[length + 1];
4081 _profile(Database$mappedSectionForPointer$Replace)
4082 for (size_t index(0); index != length; ++index)
4083 spaced[index] = section[index] == '_' ? ' ' : section[index];
4084 spaced[length] = '\0';
4089 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4090 string = [NSString stringWithUTF8String:spaced];
4093 _profile(Database$mappedSectionForPointer$Map)
4094 string = [SectionMap_ objectForKey:string] ?: string;
4104 static _H<NSMutableSet> Diversions_;
4106 @interface Diversion : NSObject {
4109 _H<NSString> format_;
4114 @implementation Diversion
4116 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4117 if ((self = [super init]) != nil) {
4118 pattern_ = [from UTF8String];
4124 - (NSString *) divert:(NSString *)url {
4125 return !pattern_(url) ? nil : pattern_->*format_;
4128 + (NSURL *) divertURL:(NSURL *)url {
4130 NSString *href([url absoluteString]);
4132 for (Diversion *diversion in (id) Diversions_)
4133 if (NSString *diverted = [diversion divert:href]) {
4135 NSLog(@"div: %@", diverted);
4137 url = [NSURL URLWithString:diverted];
4144 - (NSString *) key {
4148 - (NSUInteger) hash {
4152 - (BOOL) isEqual:(Diversion *)object {
4153 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4158 @interface CydiaObject : NSObject {
4159 _H<CyteWebViewController> indirect_;
4160 _transient id delegate_;
4163 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4169 @interface CydiaWebViewController : CyteWebViewController {
4170 _H<CydiaObject> cydia_;
4173 + (void) addDiversion:(Diversion *)diversion;
4174 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4175 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4176 - (void) setDelegate:(id)delegate;
4180 /* Web Scripting {{{ */
4181 @implementation CydiaObject
4183 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4184 if ((self = [super init]) != nil) {
4185 indirect_ = (CyteWebViewController *) indirect;
4189 - (void) setDelegate:(id)delegate {
4190 delegate_ = delegate;
4193 + (NSArray *) _attributeKeys {
4194 return [NSArray arrayWithObjects:
4197 @"coreFoundationVersionNumber",
4214 - (NSArray *) attributeKeys {
4215 return [[self class] _attributeKeys];
4218 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4219 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4222 - (NSString *) version {
4226 - (NSString *) build {
4230 - (NSString *) coreFoundationVersionNumber {
4231 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4234 - (NSString *) device {
4235 return UniqueIdentifier();
4238 - (NSString *) firmware {
4239 return [[UIDevice currentDevice] systemVersion];
4242 - (NSString *) hostname {
4243 return [[UIDevice currentDevice] name];
4246 - (NSString *) idiom {
4247 return (id) Idiom_ ?: [NSNull null];
4250 - (NSString *) mcc {
4251 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4252 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4256 - (NSString *) mnc {
4257 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4258 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4262 - (NSString *) operator {
4263 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4264 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4268 - (NSString *) bbsnum {
4269 return (id) BBSNum_ ?: [NSNull null];
4272 - (NSString *) ecid {
4273 return (id) ChipID_ ?: [NSNull null];
4276 - (NSString *) serial {
4277 return SerialNumber_;
4280 - (NSString *) role {
4281 return (id) [NSNull null];
4284 - (NSString *) model {
4285 return [NSString stringWithUTF8String:Machine_];
4288 - (NSString *) token {
4289 return (id) Token_ ?: [NSNull null];
4292 + (NSString *) webScriptNameForSelector:(SEL)selector {
4294 else if (selector == @selector(addBridgedHost:))
4295 return @"addBridgedHost";
4296 else if (selector == @selector(addInsecureHost:))
4297 return @"addInsecureHost";
4298 else if (selector == @selector(addInternalRedirect::))
4299 return @"addInternalRedirect";
4300 else if (selector == @selector(addPipelinedHost:scheme:))
4301 return @"addPipelinedHost";
4302 else if (selector == @selector(addSource:::))
4303 return @"addSource";
4304 else if (selector == @selector(addTokenHost:))
4305 return @"addTokenHost";
4306 else if (selector == @selector(addTrivialSource:))
4307 return @"addTrivialSource";
4308 else if (selector == @selector(close))
4310 else if (selector == @selector(du:))
4312 else if (selector == @selector(stringWithFormat:arguments:))
4314 else if (selector == @selector(getAllSources))
4315 return @"getAllSources";
4316 else if (selector == @selector(getApplicationInfo:value:))
4317 return @"getApplicationInfoValue";
4318 else if (selector == @selector(getKernelNumber:))
4319 return @"getKernelNumber";
4320 else if (selector == @selector(getKernelString:))
4321 return @"getKernelString";
4322 else if (selector == @selector(getInstalledPackages))
4323 return @"getInstalledPackages";
4324 else if (selector == @selector(getIORegistryEntry::))
4325 return @"getIORegistryEntry";
4326 else if (selector == @selector(getLocaleIdentifier))
4327 return @"getLocaleIdentifier";
4328 else if (selector == @selector(getPreferredLanguages))
4329 return @"getPreferredLanguages";
4330 else if (selector == @selector(getPackageById:))
4331 return @"getPackageById";
4332 else if (selector == @selector(getMetadataKeys))
4333 return @"getMetadataKeys";
4334 else if (selector == @selector(getMetadataValue:))
4335 return @"getMetadataValue";
4336 else if (selector == @selector(getSessionValue:))
4337 return @"getSessionValue";
4338 else if (selector == @selector(installPackages:))
4339 return @"installPackages";
4340 else if (selector == @selector(isReachable:))
4341 return @"isReachable";
4342 else if (selector == @selector(localizedStringForKey:value:table:))
4344 else if (selector == @selector(popViewController:))
4345 return @"popViewController";
4346 else if (selector == @selector(refreshSources))
4347 return @"refreshSources";
4348 else if (selector == @selector(registerFrame:))
4349 return @"registerFrame";
4350 else if (selector == @selector(removeButton))
4351 return @"removeButton";
4352 else if (selector == @selector(saveConfig))
4353 return @"saveConfig";
4354 else if (selector == @selector(setMetadataValue::))
4355 return @"setMetadataValue";
4356 else if (selector == @selector(setSessionValue::))
4357 return @"setSessionValue";
4358 else if (selector == @selector(substitutePackageNames:))
4359 return @"substitutePackageNames";
4360 else if (selector == @selector(scrollToBottom:))
4361 return @"scrollToBottom";
4362 else if (selector == @selector(setAllowsNavigationAction:))
4363 return @"setAllowsNavigationAction";
4364 else if (selector == @selector(setBadgeValue:))
4365 return @"setBadgeValue";
4366 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4367 return @"setButtonImage";
4368 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4369 return @"setButtonTitle";
4370 else if (selector == @selector(setHidesBackButton:))
4371 return @"setHidesBackButton";
4372 else if (selector == @selector(setHidesNavigationBar:))
4373 return @"setHidesNavigationBar";
4374 else if (selector == @selector(setNavigationBarStyle:))
4375 return @"setNavigationBarStyle";
4376 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4377 return @"setNavigationBarTintColor";
4378 else if (selector == @selector(setPasteboardString:))
4379 return @"setPasteboardString";
4380 else if (selector == @selector(setPasteboardURL:))
4381 return @"setPasteboardURL";
4382 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4383 return @"setScrollAlwaysBounceVertical";
4384 else if (selector == @selector(setScrollIndicatorStyle:))
4385 return @"setScrollIndicatorStyle";
4386 else if (selector == @selector(setToken:))
4388 else if (selector == @selector(setViewportWidth:))
4389 return @"setViewportWidth";
4390 else if (selector == @selector(statfs:))
4392 else if (selector == @selector(supports:))
4394 else if (selector == @selector(unload))
4400 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4401 return [self webScriptNameForSelector:selector] == nil;
4404 - (BOOL) supports:(NSString *)feature {
4405 return [feature isEqualToString:@"window.open"];
4409 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4412 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4413 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4416 - (void) setScrollIndicatorStyle:(NSString *)style {
4417 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4420 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4421 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4424 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4426 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4427 return (id) [NSNull null];
4428 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4430 return (id) [NSNull null];
4431 return [info objectForKey:key];
4434 - (NSNumber *) getKernelNumber:(NSString *)name {
4435 const char *string([name UTF8String]);
4438 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4439 return (id) [NSNull null];
4441 if (size != sizeof(int))
4442 return (id) [NSNull null];
4445 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4446 return (id) [NSNull null];
4448 return [NSNumber numberWithInt:value];
4451 - (NSString *) getKernelString:(NSString *)name {
4452 const char *string([name UTF8String]);
4455 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4456 return (id) [NSNull null];
4458 char value[size + 1];
4459 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4460 return (id) [NSNull null];
4462 // XXX: just in case you request something ludicrous
4465 return [NSString stringWithCString:value];
4468 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4469 NSObject *value(CYIOGetValue([path UTF8String], entry));
4472 if ([value isKindOfClass:[NSData class]])
4473 value = CYHex((NSData *) value);
4478 - (NSArray *) getMetadataKeys {
4479 @synchronized (Values_) {
4480 return [Values_ allKeys];
4483 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4484 WebFrame *frame([iframe contentFrame]);
4485 [indirect_ registerFrame:frame];
4488 - (id) getMetadataValue:(NSString *)key {
4489 @synchronized (Values_) {
4490 return [Values_ objectForKey:key];
4493 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4494 @synchronized (Values_) {
4495 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4496 [Values_ removeObjectForKey:key];
4498 [Values_ setObject:value forKey:key];
4500 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4503 - (id) getSessionValue:(NSString *)key {
4504 @synchronized (SessionData_) {
4505 return [SessionData_ objectForKey:key];
4508 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4509 @synchronized (SessionData_) {
4510 if (value == (id) [WebUndefined undefined])
4511 [SessionData_ removeObjectForKey:key];
4513 [SessionData_ setObject:value forKey:key];
4516 - (void) addBridgedHost:(NSString *)host {
4517 @synchronized (HostConfig_) {
4518 [BridgedHosts_ addObject:host];
4521 - (void) addInsecureHost:(NSString *)host {
4522 @synchronized (HostConfig_) {
4523 [InsecureHosts_ addObject:host];
4526 - (void) addTokenHost:(NSString *)host {
4527 @synchronized (HostConfig_) {
4528 [TokenHosts_ addObject:host];
4531 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4532 @synchronized (HostConfig_) {
4533 if (scheme != (id) [WebUndefined undefined])
4534 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4536 [PipelinedHosts_ addObject:host];
4539 - (void) popViewController:(NSNumber *)value {
4540 if (value == (id) [WebUndefined undefined])
4541 value = [NSNumber numberWithBool:YES];
4542 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4545 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4546 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4548 for (NSString *section in sections)
4549 [array addObject:section];
4551 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4554 distribution, @"Distribution",
4556 nil] waitUntilDone:NO];
4559 - (void) addTrivialSource:(NSString *)href {
4560 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4563 - (void) refreshSources {
4564 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4567 - (void) saveConfig {
4568 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4571 - (NSArray *) getAllSources {
4572 return [[Database sharedInstance] sources];
4575 - (NSArray *) getInstalledPackages {
4576 Database *database([Database sharedInstance]);
4577 @synchronized (database) {
4578 NSArray *packages([database packages]);
4579 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4580 for (Package *package in packages)
4581 if (![package uninstalled])
4582 [installed addObject:package];
4586 - (Package *) getPackageById:(NSString *)id {
4587 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4591 return (Package *) [NSNull null];
4594 - (NSString *) getLocaleIdentifier {
4595 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4598 - (NSArray *) getPreferredLanguages {
4602 - (NSArray *) statfs:(NSString *)path {
4605 if (path == nil || statfs([path UTF8String], &stat) == -1)
4608 return [NSArray arrayWithObjects:
4609 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4610 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4611 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4615 - (NSNumber *) du:(NSString *)path {
4616 NSNumber *value(nil);
4619 _assert(pipe(fds) != -1);
4621 pid_t pid(ExecFork());
4623 _assert(dup2(fds[1], 1) != -1);
4624 _assert(close(fds[0]) != -1);
4625 _assert(close(fds[1]) != -1);
4626 /* XXX: this should probably not use du */
4627 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4630 _assert(close(fds[1]) != -1);
4632 if (FILE *du = fdopen(fds[0], "r")) {
4634 while (fgets(line, sizeof(line), du) != NULL) {
4635 size_t length(strlen(line));
4636 while (length != 0 && line[length - 1] == '\n')
4637 line[--length] = '\0';
4638 if (char *tab = strchr(line, '\t')) {
4640 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4646 _assert(close(fds[0]) != -1);
4653 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4656 - (NSNumber *) isReachable:(NSString *)name {
4657 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4660 - (void) installPackages:(NSArray *)packages {
4661 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4664 - (NSString *) substitutePackageNames:(NSString *)message {
4665 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4666 for (size_t i(0), e([words count]); i != e; ++i) {
4667 NSString *word([words objectAtIndex:i]);
4668 if (Package *package = [[Database sharedInstance] packageWithName:word])
4669 [words replaceObjectAtIndex:i withObject:[package name]];
4672 return [words componentsJoinedByString:@" "];
4675 - (void) removeButton {
4676 [indirect_ removeButton];
4679 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4680 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4683 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4684 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4687 - (void) setBadgeValue:(id)value {
4688 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4691 - (void) setAllowsNavigationAction:(NSString *)value {
4692 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4695 - (void) setHidesBackButton:(NSString *)value {
4696 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4699 - (void) setHidesNavigationBar:(NSString *)value {
4700 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4703 - (void) setNavigationBarStyle:(NSString *)value {
4704 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4707 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4708 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4709 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4710 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4713 - (void) setPasteboardString:(NSString *)value {
4714 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4717 - (void) setPasteboardURL:(NSString *)value {
4718 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4721 - (void) _setToken:(NSString *)token {
4725 [Metadata_ removeObjectForKey:@"Token"];
4727 [Metadata_ setObject:Token_ forKey:@"Token"];
4732 - (void) setToken:(NSString *)token {
4733 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4736 - (void) scrollToBottom:(NSNumber *)animated {
4737 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4740 - (void) setViewportWidth:(float)width {
4741 [indirect_ setViewportWidthOnMainThread:width];
4744 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4745 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4746 unsigned count([arguments count]);
4748 for (unsigned i(0); i != count; ++i)
4749 values[i] = [arguments objectAtIndex:i];
4750 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4753 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4754 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4756 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4758 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4764 @interface NSURL (CydiaSecure)
4767 @implementation NSURL (CydiaSecure)
4769 - (bool) isCydiaSecure {
4770 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4773 @synchronized (HostConfig_) {
4774 if ([InsecureHosts_ containsObject:[self host]])
4783 /* Cydia Browser Controller {{{ */
4784 @implementation CydiaWebViewController
4786 - (NSURL *) navigationURL {
4787 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4790 + (void) _initialize {
4791 [super _initialize];
4793 Diversions_ = [NSMutableSet setWithCapacity:0];
4796 + (void) addDiversion:(Diversion *)diversion {
4797 [Diversions_ addObject:diversion];
4800 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4801 [super webView:view didClearWindowObject:window forFrame:frame];
4802 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4805 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4806 WebDataSource *source([frame dataSource]);
4807 NSURLResponse *response([source response]);
4808 NSURL *url([response URL]);
4809 NSString *scheme([[url scheme] lowercaseString]);
4811 bool bridged(false);
4813 @synchronized (HostConfig_) {
4814 if ([scheme isEqualToString:@"file"])
4816 else if ([scheme isEqualToString:@"https"])
4817 if ([BridgedHosts_ containsObject:[url host]])
4822 [window setValue:cydia forKey:@"cydia"];
4825 - (void) _setupMail:(MFMailComposeViewController *)controller {
4826 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4828 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4829 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4832 - (NSURL *) URLWithURL:(NSURL *)url {
4833 return [Diversion divertURL:url];
4836 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4837 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4840 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4841 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4843 NSURL *url([copy URL]);
4844 NSString *href([url absoluteString]);
4845 NSString *host([url host]);
4847 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4848 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4849 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4850 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4853 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4854 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4856 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4860 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4861 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4862 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4863 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4868 @synchronized (HostConfig_) {
4869 bridged = [BridgedHosts_ containsObject:host];
4870 token = [TokenHosts_ containsObject:host];
4873 if ([url isCydiaSecure]) {
4875 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4876 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4878 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4879 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4886 - (void) setDelegate:(id)delegate {
4887 [super setDelegate:delegate];
4888 [cydia_ setDelegate:delegate];
4891 - (NSString *) applicationNameForUserAgent {
4896 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4897 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4903 @interface AppCacheController : CydiaWebViewController {
4908 @implementation AppCacheController
4910 - (void) didReceiveMemoryWarning {
4911 // XXX: this doesn't work
4914 - (bool) retainsNetworkActivityIndicator {
4922 @interface NSObject (CydiaScript)
4923 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4926 @implementation NSObject (CydiaScript)
4928 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4934 @implementation NSArray (CydiaScript)
4936 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4937 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4938 for (size_t i(0), e([self count]); i != e; ++i)
4939 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4945 @implementation NSDictionary (CydiaScript)
4947 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4948 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4950 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4957 /* Confirmation Controller {{{ */
4958 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4959 if (!iterator.end())
4960 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4961 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4963 pkgCache::PkgIterator package(dep.TargetPkg());
4966 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4973 @protocol ConfirmationControllerDelegate
4974 - (void) cancelAndClear:(bool)clear;
4975 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4979 @interface ConfirmationController : CydiaWebViewController {
4980 _transient Database *database_;
4982 _H<UIAlertView> essential_;
4984 _H<NSDictionary> changes_;
4985 _H<NSMutableArray> issues_;
4986 _H<NSDictionary> sizes_;
4991 - (id) initWithDatabase:(Database *)database;
4995 @implementation ConfirmationController
4999 RestartSubstrate_ = true;
5000 [delegate_ confirmWithNavigationController:[self navigationController]];
5003 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5004 NSString *context([alert context]);
5006 if ([context isEqualToString:@"remove"]) {
5007 if (button == [alert cancelButtonIndex])
5008 [self dismissModalViewControllerAnimated:YES];
5009 else if (button == [alert firstOtherButtonIndex]) {
5010 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5013 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5014 } else if ([context isEqualToString:@"unable"]) {
5015 [self dismissModalViewControllerAnimated:YES];
5016 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5018 [super alertView:alert clickedButtonAtIndex:button];
5022 - (void) _doContinue {
5023 [delegate_ cancelAndClear:NO];
5024 [self dismissModalViewControllerAnimated:YES];
5027 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5028 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5032 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5033 [super webView:view didClearWindowObject:window forFrame:frame];
5035 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5036 (id) changes_, @"changes",
5037 (id) issues_, @"issues",
5038 (id) sizes_, @"sizes",
5040 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5043 - (id) initWithDatabase:(Database *)database {
5044 if ((self = [super init]) != nil) {
5045 database_ = database;
5047 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5048 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5049 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5050 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5051 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5055 pkgCacheFile &cache([database_ cache]);
5056 NSArray *packages([database_ packages]);
5057 pkgDepCache::Policy *policy([database_ policy]);
5059 issues_ = [NSMutableArray arrayWithCapacity:4];
5061 for (Package *package in packages) {
5062 pkgCache::PkgIterator iterator([package iterator]);
5063 NSString *name([package id]);
5065 if ([package broken]) {
5066 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5068 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5070 reasons, @"reasons",
5073 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5077 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5078 pkgCache::DepIterator start;
5079 pkgCache::DepIterator end;
5080 dep.GlobOr(start, end); // ++dep
5082 if (!cache->IsImportantDep(end))
5084 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5087 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5089 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5090 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5091 clauses, @"clauses",
5095 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5097 pkgCache::PkgIterator target(start.TargetPkg());
5098 if (target->ProvidesList != 0)
5099 reason = @"missing";
5101 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5103 reason = @"installed";
5104 installed = [NSString stringWithUTF8String:ver.VerStr()];
5105 } else if (!cache[target].CandidateVerIter(cache).end())
5106 reason = @"uninstalled";
5107 else if (target->ProvidesList == 0)
5108 reason = @"uninstallable";
5110 reason = @"virtual";
5113 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5114 [NSString stringWithUTF8String:start.CompType()], @"operator",
5115 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5118 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5119 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5120 version, @"version",
5122 installed, @"installed",
5125 // yes, seriously. (wtf?)
5133 pkgDepCache::StateCache &state(cache[iterator]);
5135 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
5137 if (state.NewInstall())
5138 [installs addObject:name];
5139 // XXX: else if (state.Install())
5140 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5141 [reinstalls addObject:name];
5142 // XXX: move before previous if
5143 else if (state.Upgrade())
5144 [upgrades addObject:name];
5145 else if (state.Downgrade())
5146 [downgrades addObject:name];
5147 else if (!state.Delete())
5148 // XXX: _assert(state.Keep());
5150 else if (special_r(name))
5151 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5152 [NSNull null], @"package",
5153 [NSArray arrayWithObjects:
5154 [NSDictionary dictionaryWithObjectsAndKeys:
5155 @"Conflicts", @"relationship",
5156 [NSArray arrayWithObjects:
5157 [NSDictionary dictionaryWithObjectsAndKeys:
5159 [NSNull null], @"version",
5160 @"installed", @"reason",
5167 if ([package essential])
5169 [removes addObject:name];
5172 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5173 substrate_ |= DepSubstrate(iterator.CurrentVer());
5178 else if (Advanced_) {
5179 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5181 essential_ = [[[UIAlertView alloc]
5182 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5183 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5185 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5187 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5191 [essential_ setContext:@"remove"];
5192 [essential_ setNumberOfRows:2];
5194 essential_ = [[[UIAlertView alloc]
5195 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5196 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5198 cancelButtonTitle:UCLocalize("OKAY")
5199 otherButtonTitles:nil
5202 [essential_ setContext:@"unable"];
5205 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5206 installs, @"installs",
5207 reinstalls, @"reinstalls",
5208 upgrades, @"upgrades",
5209 downgrades, @"downgrades",
5210 removes, @"removes",
5213 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5214 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5215 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5218 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5222 - (UIBarButtonItem *) leftButton {
5223 return [[[UIBarButtonItem alloc]
5224 initWithTitle:UCLocalize("CANCEL")
5225 style:UIBarButtonItemStylePlain
5227 action:@selector(cancelButtonClicked)
5232 - (void) applyRightButton {
5233 if ([issues_ count] == 0 && ![self isLoading])
5234 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5235 initWithTitle:UCLocalize("CONFIRM")
5236 style:UIBarButtonItemStyleDone
5238 action:@selector(confirmButtonClicked)
5241 [[self navigationItem] setRightBarButtonItem:nil];
5245 - (void) cancelButtonClicked {
5246 [delegate_ cancelAndClear:YES];
5247 [self dismissModalViewControllerAnimated:YES];
5251 - (void) confirmButtonClicked {
5252 if (essential_ != nil)
5262 /* Progress Data {{{ */
5263 @interface CydiaProgressData : NSObject {
5264 _transient id delegate_;
5273 _H<NSMutableArray> events_;
5274 _H<NSString> title_;
5276 _H<NSString> status_;
5277 _H<NSString> finish_;
5282 @implementation CydiaProgressData
5284 + (NSArray *) _attributeKeys {
5285 return [NSArray arrayWithObjects:
5297 - (NSArray *) attributeKeys {
5298 return [[self class] _attributeKeys];
5301 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5302 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5306 if ((self = [super init]) != nil) {
5307 events_ = [NSMutableArray arrayWithCapacity:32];
5315 - (void) setDelegate:(id)delegate {
5316 delegate_ = delegate;
5319 - (void) setPercent:(float)value {
5323 - (NSNumber *) percent {
5324 return [NSNumber numberWithFloat:percent_];
5327 - (void) setCurrent:(float)value {
5331 - (NSNumber *) current {
5332 return [NSNumber numberWithFloat:current_];
5335 - (void) setTotal:(float)value {
5339 - (NSNumber *) total {
5340 return [NSNumber numberWithFloat:total_];
5343 - (void) setSpeed:(float)value {
5347 - (NSNumber *) speed {
5348 return [NSNumber numberWithFloat:speed_];
5351 - (NSArray *) events {
5355 - (void) removeAllEvents {
5356 [events_ removeAllObjects];
5359 - (void) addEvent:(CydiaProgressEvent *)event {
5360 [events_ addObject:event];
5363 - (void) setTitle:(NSString *)text {
5367 - (NSString *) title {
5371 - (void) setFinish:(NSString *)text {
5375 - (NSString *) finish {
5376 return (id) finish_ ?: [NSNull null];
5379 - (void) setRunning:(bool)running {
5383 - (NSNumber *) running {
5384 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5389 /* Progress Controller {{{ */
5390 @interface ProgressController : CydiaWebViewController <
5393 _transient Database *database_;
5394 _H<CydiaProgressData, 1> progress_;
5398 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5400 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5402 - (void) setTitle:(NSString *)title;
5403 - (void) setCancellable:(bool)cancellable;
5407 @implementation ProgressController
5410 [database_ setProgressDelegate:nil];
5414 - (UIBarButtonItem *) leftButton {
5415 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5416 initWithTitle:UCLocalize("CANCEL")
5417 style:UIBarButtonItemStylePlain
5419 action:@selector(cancel)
5420 ] autorelease] : nil;
5423 - (void) updateCancel {
5424 [super applyLeftButton];
5427 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5428 if ((self = [super init]) != nil) {
5429 database_ = database;
5430 delegate_ = delegate;
5432 [database_ setProgressDelegate:self];
5434 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5435 [progress_ setDelegate:self];
5437 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5439 [scroller_ setBackgroundColor:[UIColor blackColor]];
5441 [[self navigationItem] setHidesBackButton:YES];
5443 [self updateCancel];
5447 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5448 [super webView:view didClearWindowObject:window forFrame:frame];
5449 [window setValue:progress_ forKey:@"cydiaProgress"];
5452 - (void) updateProgress {
5453 [self dispatchEvent:@"CydiaProgressUpdate"];
5456 - (void) viewWillAppear:(BOOL)animated {
5457 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5458 [super viewWillAppear:animated];
5461 - (void) reloadSpringBoard {
5462 if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
5463 system("/bin/launchctl stop com.apple.backboardd");
5465 system("/usr/bin/killall backboardd SpringBoard sbreload");
5469 pid_t pid(ExecFork());
5474 pid_t pid(ExecFork());
5476 execl("/usr/bin/sbreload", "sbreload", NULL);
5486 system("/usr/bin/killall backboardd SpringBoard sbreload");
5490 UpdateExternalStatus(0);
5493 [delegate_ saveState];
5497 [delegate_ returnToCydia];
5501 [delegate_ terminateWithSuccess];
5502 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5503 [delegate_ suspendWithAnimation:YES];
5505 [delegate_ suspend];*/
5517 UIProgressHUD *hud([delegate_ addProgressHUD]);
5518 [hud setText:UCLocalize("LOADING")];
5519 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5525 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5526 SBReboot(SBSSpringBoardServerPort());
5528 reboot2(RB_AUTOBOOT);
5535 - (void) setTitle:(NSString *)title {
5536 [progress_ setTitle:title];
5537 [self updateProgress];
5540 - (UIBarButtonItem *) rightButton {
5541 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5542 initWithTitle:UCLocalize("CLOSE")
5543 style:UIBarButtonItemStylePlain
5545 action:@selector(close)
5549 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5550 UpdateExternalStatus(1);
5552 [progress_ setRunning:true];
5553 [self setTitle:title];
5554 // implicit updateProgress
5556 SHA1SumValue notifyconf; {
5558 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5561 MMap mmap(file, MMap::ReadOnly);
5563 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5564 notifyconf = sha1.Result();
5568 SHA1SumValue springlist; {
5570 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5573 MMap mmap(file, MMap::ReadOnly);
5575 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5576 springlist = sha1.Result();
5580 if (invocation != nil) {
5581 [invocation yieldToSelector:@selector(invoke)];
5582 [self setTitle:@"COMPLETE"];
5587 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5590 MMap mmap(file, MMap::ReadOnly);
5592 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5593 if (!(notifyconf == sha1.Result()))
5600 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5603 MMap mmap(file, MMap::ReadOnly);
5605 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5606 if (!(springlist == sha1.Result()))
5612 if (RestartSubstrate_)
5616 RestartSubstrate_ = false;
5619 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5620 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5621 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5622 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5623 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5626 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5628 [progress_ setRunning:false];
5629 [self updateProgress];
5631 [self applyRightButton];
5634 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5635 [progress_ addEvent:event];
5636 [self updateProgress];
5639 - (bool) isProgressCancelled {
5640 return cancel_ == 2;
5645 [self updateCancel];
5648 - (void) setCancellable:(bool)cancellable {
5649 unsigned cancel(cancel_);
5653 else if (cancel_ == 0)
5656 if (cancel != cancel_)
5657 [self updateCancel];
5660 - (void) setProgressCancellable:(NSNumber *)cancellable {
5661 [self setCancellable:[cancellable boolValue]];
5664 - (void) setProgressPercent:(NSNumber *)percent {
5665 [progress_ setPercent:[percent floatValue]];
5666 [self updateProgress];
5669 - (void) setProgressStatus:(NSDictionary *)status {
5670 if (status == nil) {
5671 [progress_ setCurrent:0];
5672 [progress_ setTotal:0];
5673 [progress_ setSpeed:0];
5675 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5677 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5678 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5679 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5682 [self updateProgress];
5688 /* Package Cell {{{ */
5689 @interface PackageCell : CyteTableViewCell <
5690 CyteTableViewCellDelegate
5694 _H<NSString> description_;
5696 _H<NSString> source_;
5698 _H<UIImage> placard_;
5702 - (PackageCell *) init;
5703 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5705 - (void) drawContentRect:(CGRect)rect;
5709 @implementation PackageCell
5711 - (PackageCell *) init {
5712 CGRect frame(CGRectMake(0, 0, 320, 74));
5713 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5714 UIView *content([self contentView]);
5715 CGRect bounds([content bounds]);
5717 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5718 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5719 [content addSubview:content_];
5721 [content_ setDelegate:self];
5722 [content_ setOpaque:YES];
5726 - (NSString *) accessibilityLabel {
5730 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5731 summarized_ = summary;
5741 [content_ setBackgroundColor:[UIColor whiteColor]];
5745 Source *source = [package source];
5747 icon_ = [package icon];
5749 if (NSString *name = [package name])
5750 name_ = [NSString stringWithString:name];
5752 if (NSString *description = [package shortDescription])
5753 description_ = [NSString stringWithString:description];
5755 commercial_ = [package isCommercial];
5757 NSString *label = nil;
5758 bool trusted = false;
5760 if (source != nil) {
5761 label = [source label];
5762 trusted = [source trusted];
5763 } else if ([[package id] isEqualToString:@"firmware"])
5764 label = UCLocalize("APPLE");
5766 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5768 NSString *from(label);
5770 NSString *section = [package simpleSection];
5771 if (section != nil && ![section isEqualToString:label]) {
5772 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5773 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5776 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5778 if (NSString *purpose = [package primaryPurpose])
5779 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5784 if (NSString *mode = [package mode]) {
5785 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5786 color = RemovingColor_;
5787 placard = @"removing";
5789 color = InstallingColor_;
5790 placard = @"installing";
5793 color = [UIColor whiteColor];
5795 if ([package installed] != nil)
5796 placard = @"installed";
5801 [content_ setBackgroundColor:color];
5804 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5807 [self setNeedsDisplay];
5808 [content_ setNeedsDisplay];
5811 - (void) drawSummaryContentRect:(CGRect)rect {
5812 bool highlighted(highlighted_);
5813 float width([self bounds].size.width);
5817 rect.size = [(UIImage *) icon_ size];
5819 while (rect.size.width > 16 || rect.size.height > 16) {
5820 rect.size.width /= 2;
5821 rect.size.height /= 2;
5824 rect.origin.x = 19 - rect.size.width / 2;
5825 rect.origin.y = 19 - rect.size.height / 2;
5827 [icon_ drawInRect:rect];
5830 if (badge_ != nil) {
5832 rect.size = [(UIImage *) badge_ size];
5834 rect.size.width /= 4;
5835 rect.size.height /= 4;
5837 rect.origin.x = 25 - rect.size.width / 2;
5838 rect.origin.y = 25 - rect.size.height / 2;
5840 [badge_ drawInRect:rect];
5843 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5847 UISetColor(commercial_ ? Purple_ : Black_);
5848 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5850 if (placard_ != nil)
5851 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5854 - (void) drawNormalContentRect:(CGRect)rect {
5855 bool highlighted(highlighted_);
5856 float width([self bounds].size.width);
5860 rect.size = [(UIImage *) icon_ size];
5862 while (rect.size.width > 32 || rect.size.height > 32) {
5863 rect.size.width /= 2;
5864 rect.size.height /= 2;
5867 rect.origin.x = 25 - rect.size.width / 2;
5868 rect.origin.y = 25 - rect.size.height / 2;
5870 [icon_ drawInRect:rect];
5873 if (badge_ != nil) {
5875 rect.size = [(UIImage *) badge_ size];
5877 rect.size.width /= 2;
5878 rect.size.height /= 2;
5880 rect.origin.x = 36 - rect.size.width / 2;
5881 rect.origin.y = 36 - rect.size.height / 2;
5883 [badge_ drawInRect:rect];
5886 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5890 UISetColor(commercial_ ? Purple_ : Black_);
5891 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5892 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5895 UISetColor(commercial_ ? Purplish_ : Gray_);
5896 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
5898 if (placard_ != nil)
5899 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5902 - (void) drawContentRect:(CGRect)rect {
5904 [self drawSummaryContentRect:rect];
5906 [self drawNormalContentRect:rect];
5911 /* Section Cell {{{ */
5912 @interface SectionCell : CyteTableViewCell <
5913 CyteTableViewCellDelegate
5915 _H<NSString> basic_;
5916 _H<NSString> section_;
5918 _H<NSString> count_;
5920 _H<UISwitch> switch_;
5924 - (void) setSection:(Section *)section editing:(BOOL)editing;
5928 @implementation SectionCell
5930 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5931 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5932 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5933 // XXX: this initial frame is wrong, but is fixed later
5934 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5935 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5937 UIView *content([self contentView]);
5938 CGRect bounds([content bounds]);
5940 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5941 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5942 [content addSubview:content_];
5943 [content_ setBackgroundColor:[UIColor whiteColor]];
5945 [content_ setDelegate:self];
5949 - (void) onSwitch:(id)sender {
5950 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5951 if (metadata == nil) {
5952 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5953 [Sections_ setObject:metadata forKey:basic_];
5956 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5960 - (void) setSection:(Section *)section editing:(BOOL)editing {
5961 if (editing != editing_) {
5963 [switch_ removeFromSuperview];
5965 [self addSubview:switch_];
5974 if (section == nil) {
5975 name_ = UCLocalize("ALL_PACKAGES");
5978 basic_ = [section name];
5979 section_ = [section localized];
5981 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5982 count_ = [NSString stringWithFormat:@"%zd", [section count]];
5985 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5988 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5989 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5991 [content_ setNeedsDisplay];
5994 - (void) setFrame:(CGRect)frame {
5995 [super setFrame:frame];
5997 CGRect rect([switch_ frame]);
5998 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6001 - (NSString *) accessibilityLabel {
6005 - (void) drawContentRect:(CGRect)rect {
6006 bool highlighted(highlighted_ && !editing_);
6008 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6010 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6013 float width(rect.size.width);
6015 width -= 9 + [switch_ frame].size.width;
6019 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6021 CGSize size = [count_ sizeWithFont:Font14_];
6023 UISetColor(Folder_);
6025 [count_ drawAtPoint:CGPointMake(10 + (30 - size.width) / 2, 18) withFont:Font12Bold_];
6031 /* File Table {{{ */
6032 @interface FileTable : CyteViewController <
6033 UITableViewDataSource,
6036 _transient Database *database_;
6037 _H<Package> package_;
6039 _H<NSMutableArray> files_;
6040 _H<UITableView, 2> list_;
6043 - (id) initWithDatabase:(Database *)database;
6044 - (void) setPackage:(Package *)package;
6048 @implementation FileTable
6050 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6051 return files_ == nil ? 0 : [files_ count];
6054 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6058 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6059 static NSString *reuseIdentifier = @"Cell";
6061 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6063 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6064 [cell setFont:[UIFont systemFontOfSize:16]];
6066 [cell setText:[files_ objectAtIndex:indexPath.row]];
6067 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6072 - (NSURL *) navigationURL {
6073 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6077 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6078 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6079 [list_ setRowHeight:24.0f];
6080 [(UITableView *) list_ setDataSource:self];
6081 [list_ setDelegate:self];
6082 [self setView:list_];
6085 - (void) viewDidLoad {
6086 [super viewDidLoad];
6088 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6091 - (void) releaseSubviews {
6097 [super releaseSubviews];
6100 - (id) initWithDatabase:(Database *)database {
6101 if ((self = [super init]) != nil) {
6102 database_ = database;
6106 - (void) setPackage:(Package *)package {
6110 files_ = [NSMutableArray arrayWithCapacity:32];
6112 if (package != nil) {
6114 name_ = [package id];
6116 if (NSArray *files = [package files])
6117 [files_ addObjectsFromArray:files];
6119 if ([files_ count] != 0) {
6120 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6121 [files_ removeObjectAtIndex:0];
6122 [files_ sortUsingSelector:@selector(compareByPath:)];
6124 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6125 [stack addObject:@"/"];
6127 for (int i(0), e([files_ count]); i != e; ++i) {
6128 NSString *file = [files_ objectAtIndex:i];
6129 while (![file hasPrefix:[stack lastObject]])
6130 [stack removeLastObject];
6131 NSString *directory = [stack lastObject];
6132 [stack addObject:[file stringByAppendingString:@"/"]];
6133 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6134 ([stack count] - 2) * 3, "",
6135 [file substringFromIndex:[directory length]]
6144 - (void) reloadData {
6147 [self setPackage:[database_ packageWithName:name_]];
6152 /* Package Controller {{{ */
6153 @interface CYPackageController : CydiaWebViewController <
6154 UIActionSheetDelegate
6156 _transient Database *database_;
6157 _H<Package> package_;
6160 _H<NSMutableArray> buttons_;
6161 _H<UIBarButtonItem> button_;
6164 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6168 @implementation CYPackageController
6170 - (NSURL *) navigationURL {
6171 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6174 /* XXX: this is not safe at all... localization of /fail/ */
6175 - (void) _clickButtonWithName:(NSString *)name {
6176 if ([name isEqualToString:UCLocalize("CLEAR")])
6177 [delegate_ clearPackage:package_];
6178 else if ([name isEqualToString:UCLocalize("INSTALL")])
6179 [delegate_ installPackage:package_];
6180 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6181 [delegate_ installPackage:package_];
6182 else if ([name isEqualToString:UCLocalize("REMOVE")])
6183 [delegate_ removePackage:package_];
6184 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6185 [delegate_ installPackage:package_];
6186 else _assert(false);
6189 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6190 NSString *context([sheet context]);
6192 if ([context isEqualToString:@"modify"]) {
6193 if (button != [sheet cancelButtonIndex]) {
6194 NSString *buttonName = [buttons_ objectAtIndex:button];
6195 [self _clickButtonWithName:buttonName];
6198 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6202 - (bool) _allowJavaScriptPanel {
6207 - (void) _customButtonClicked {
6208 int count([buttons_ count]);
6213 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6215 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6216 [buttons addObjectsFromArray:buttons_];
6218 UIActionSheet *sheet = [[[UIActionSheet alloc]
6221 cancelButtonTitle:nil
6222 destructiveButtonTitle:nil
6223 otherButtonTitles:nil
6226 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6228 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6229 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6231 [sheet setContext:@"modify"];
6233 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6237 - (void) reloadButtonClicked {
6238 if (commercial_ && function_ == nil && [package_ uninstalled])
6240 [self customButtonClicked];
6243 - (void) applyLoadingTitle {
6244 // Don't show "Loading" as the title. Ever.
6247 - (UIBarButtonItem *) rightButton {
6252 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6253 if ((self = [super init]) != nil) {
6254 database_ = database;
6255 buttons_ = [NSMutableArray arrayWithCapacity:4];
6256 name_ = name == nil ? @"" : [NSString stringWithString:name];
6257 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6261 - (void) reloadData {
6264 package_ = [database_ packageWithName:name_];
6266 [buttons_ removeAllObjects];
6268 if (package_ != nil) {
6269 [(Package *) package_ parse];
6271 commercial_ = [package_ isCommercial];
6273 if ([package_ mode] != nil)
6274 [buttons_ addObject:UCLocalize("CLEAR")];
6275 if ([package_ source] == nil);
6276 else if ([package_ upgradableAndEssential:NO])
6277 [buttons_ addObject:UCLocalize("UPGRADE")];
6278 else if ([package_ uninstalled])
6279 [buttons_ addObject:UCLocalize("INSTALL")];
6281 [buttons_ addObject:UCLocalize("REINSTALL")];
6282 if (![package_ uninstalled])
6283 [buttons_ addObject:UCLocalize("REMOVE")];
6287 switch ([buttons_ count]) {
6288 case 0: title = nil; break;
6289 case 1: title = [buttons_ objectAtIndex:0]; break;
6290 default: title = UCLocalize("MODIFY"); break;
6293 button_ = [[[UIBarButtonItem alloc]
6295 style:UIBarButtonItemStylePlain
6297 action:@selector(customButtonClicked)
6301 - (bool) isLoading {
6302 return commercial_ ? [super isLoading] : false;
6308 /* Package List Controller {{{ */
6309 @interface PackageListController : CyteViewController <
6310 UITableViewDataSource,
6313 _transient Database *database_;
6315 _H<NSArray> packages_;
6316 _H<NSArray> sections_;
6317 _H<UITableView, 2> list_;
6319 _H<NSArray> thumbs_;
6320 std::vector<NSInteger> offset_;
6322 _H<NSString> title_;
6323 unsigned reloading_;
6326 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6327 - (void) setDelegate:(id)delegate;
6328 - (void) resetCursor;
6331 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6335 @implementation PackageListController
6337 - (NSURL *) referrerURL {
6338 return [self navigationURL];
6341 - (bool) isSummarized {
6345 - (bool) showsSections {
6349 - (void) deselectWithAnimation:(BOOL)animated {
6350 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6353 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6354 CGRect base = [[self view] bounds];
6355 base.size.height -= bounds.size.height;
6356 base.origin = [list_ frame].origin;
6358 [UIView beginAnimations:nil context:NULL];
6359 [UIView setAnimationBeginsFromCurrentState:YES];
6360 [UIView setAnimationCurve:curve];
6361 [UIView setAnimationDuration:duration];
6362 [list_ setFrame:base];
6363 [UIView commitAnimations];
6366 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6367 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6370 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6371 [self resizeForKeyboardBounds:bounds duration:0];
6374 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6375 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6376 *curve = UIViewAnimationCurveEaseInOut;
6378 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6380 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6383 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6386 - (void) keyboardWillShow:(NSNotification *)notification {
6389 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6390 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6392 NSTimeInterval duration;
6393 UIViewAnimationCurve curve;
6394 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6396 CGRect kbframe = CGRectMake(round(center.x - bounds.size.width / 2.0), round(center.y - bounds.size.height / 2.0), bounds.size.width, bounds.size.height);
6397 UIViewController *base = self;
6398 while ([base parentOrPresentingViewController] != nil)
6399 base = [base parentOrPresentingViewController];
6400 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6401 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6403 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6404 intersection.size.height += CYStatusBarHeight();
6406 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6409 - (void) keyboardWillHide:(NSNotification *)notification {
6410 NSTimeInterval duration;
6411 UIViewAnimationCurve curve;
6412 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6414 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6417 - (void) viewWillAppear:(BOOL)animated {
6418 [super viewWillAppear:animated];
6420 [self resizeForKeyboardBounds:CGRectZero];
6421 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6422 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6425 - (void) viewWillDisappear:(BOOL)animated {
6426 [super viewWillDisappear:animated];
6428 [self resizeForKeyboardBounds:CGRectZero];
6429 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6430 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6433 - (void) viewDidAppear:(BOOL)animated {
6434 [super viewDidAppear:animated];
6435 [self deselectWithAnimation:animated];
6438 - (void) didSelectPackage:(Package *)package {
6439 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6440 [view setDelegate:delegate_];
6441 [[self navigationController] pushViewController:view animated:YES];
6444 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6445 NSInteger count([sections_ count]);
6446 return count == 0 ? 1 : count;
6449 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6450 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6452 return [[sections_ objectAtIndex:section] name];
6455 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6456 if ([sections_ count] == 0)
6458 return [[sections_ objectAtIndex:section] count];
6461 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6462 @synchronized (database_) {
6463 if ([database_ era] != era_)
6466 Section *section([sections_ objectAtIndex:[path section]]);
6467 NSInteger row([path row]);
6468 Package *package([packages_ objectAtIndex:([section row] + row)]);
6469 return [[package retain] autorelease];
6472 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6473 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6475 cell = [[[PackageCell alloc] init] autorelease];
6477 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6478 [cell setPackage:package asSummary:[self isSummarized]];
6482 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6483 Package *package([self packageAtIndexPath:path]);
6484 package = [database_ packageWithName:[package id]];
6485 [self didSelectPackage:package];
6488 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6492 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6493 return offset_[index];
6496 - (void) updateHeight {
6497 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6500 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6501 if ((self = [super init]) != nil) {
6502 database_ = database;
6503 title_ = [title copy];
6504 [[self navigationItem] setTitle:title_];
6509 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6510 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6511 [self setView:view];
6513 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6514 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6515 [view addSubview:list_];
6517 // XXX: is 20 the most optimal number here?
6518 [list_ setSectionIndexMinimumDisplayRowCount:20];
6520 [(UITableView *) list_ setDataSource:self];
6521 [list_ setDelegate:self];
6523 [self updateHeight];
6526 - (void) releaseSubviews {
6535 [super releaseSubviews];
6538 - (void) setDelegate:(id)delegate {
6539 delegate_ = delegate;
6542 - (bool) shouldYield {
6546 - (bool) shouldBlock {
6550 - (NSMutableArray *) _reloadPackages {
6551 @synchronized (database_) {
6552 era_ = [database_ era];
6553 NSArray *packages([database_ packages]);
6555 return [NSMutableArray arrayWithArray:packages];
6558 - (void) _reloadData {
6559 if (reloading_ != 0) {
6564 NSMutableArray *packages;
6567 if ([self shouldYield]) {
6571 if (![self shouldBlock])
6574 hud = [delegate_ addProgressHUD];
6575 [hud setText:UCLocalize("LOADING")];
6579 packages = [self yieldToSelector:@selector(_reloadPackages)];
6582 [delegate_ removeProgressHUD:hud];
6583 } while (reloading_ == 2);
6585 packages = [self _reloadPackages];
6588 @synchronized (database_) {
6589 if (era_ != [database_ era])
6596 packages_ = packages;
6598 if ([self showsSections])
6599 sections_ = [self sectionsForPackages:packages];
6601 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6602 [section setCount:[packages_ count]];
6603 sections_ = [NSArray arrayWithObject:section];
6606 [self updateHeight];
6608 _profile(PackageTable$reloadData$List)
6609 [(UITableView *) list_ setDataSource:self];
6617 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6618 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6619 size_t end([packages count]);
6621 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6622 Section *section(prefix);
6624 thumbs_ = CollationThumbs_;
6625 offset_ = CollationOffset_;
6628 size_t offsets([CollationStarts_ count]);
6630 NSString *start([CollationStarts_ objectAtIndex:offset]);
6631 size_t length([start length]);
6633 for (size_t index(0); index != end; ++index) {
6635 Package *package([packages objectAtIndex:index]);
6636 NSString *name(PackageName(package, @selector(cyname)));
6638 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6639 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6640 NSString *title([CollationTitles_ objectAtIndex:offset]);
6641 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6642 [sections addObject:section];
6644 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6647 length = [start length];
6651 [section addToCount];
6654 for (; offset != offsets; ++offset) {
6655 NSString *title([CollationTitles_ objectAtIndex:offset]);
6656 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6657 [sections addObject:section];
6660 if ([prefix count] != 0) {
6661 Section *suffix([sections lastObject]);
6662 [prefix setName:[suffix name]];
6663 [suffix setName:nil];
6664 [sections insertObject:prefix atIndex:(offsets - 1)];
6670 - (void) reloadData {
6673 if ([self shouldYield])
6674 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6679 - (void) resetCursor {
6680 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6683 - (void) clearData {
6684 [self updateHeight];
6686 [list_ setDataSource:nil];
6694 /* Filtered Package List Controller {{{ */
6695 typedef Function<bool, Package *> PackageFilter;
6696 typedef Function<void, NSMutableArray *> PackageSorter;
6697 @interface FilteredPackageListController : PackageListController {
6698 PackageFilter filter_;
6699 PackageSorter sorter_;
6702 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6704 - (void) setFilter:(PackageFilter)filter;
6705 - (void) setSorter:(PackageSorter)sorter;
6709 @implementation FilteredPackageListController
6711 - (void) setFilter:(PackageFilter)filter {
6712 @synchronized (self) {
6716 - (void) setSorter:(PackageSorter)sorter {
6717 @synchronized (self) {
6721 - (NSMutableArray *) _reloadPackages {
6722 @synchronized (database_) {
6723 era_ = [database_ era];
6725 NSArray *packages([database_ packages]);
6726 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6728 PackageFilter filter;
6729 PackageSorter sorter;
6731 @synchronized (self) {
6736 _profile(PackageTable$reloadData$Filter)
6737 for (Package *package in packages)
6738 if ([package valid] && filter(package))
6739 [filtered addObject:package];
6747 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6748 if ((self = [super initWithDatabase:database title:title]) != nil) {
6749 [self setFilter:filter];
6756 /* Home Controller {{{ */
6757 @interface HomeController : CydiaWebViewController {
6758 CFRunLoopRef runloop_;
6759 SCNetworkReachabilityRef reachability_;
6764 @implementation HomeController
6766 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6767 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6771 if ((self = [super init]) != nil) {
6772 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6775 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6776 if (reachability_ != NULL) {
6777 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6778 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6780 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6781 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6788 if (reachability_ != NULL && runloop_ != NULL)
6789 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6793 - (NSURL *) navigationURL {
6794 return [NSURL URLWithString:@"cydia://home"];
6797 - (void) aboutButtonClicked {
6798 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6800 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6801 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6802 [alert setCancelButtonIndex:0];
6805 @"Copyright \u00a9 2008-2013\n"
6808 "Jay Freeman (saurik)\n"
6809 "saurik@saurik.com\n"
6810 "http://www.saurik.com/"
6816 - (UIBarButtonItem *) leftButton {
6817 return [[[UIBarButtonItem alloc]
6818 initWithTitle:UCLocalize("ABOUT")
6819 style:UIBarButtonItemStylePlain
6821 action:@selector(aboutButtonClicked)
6828 /* Cydia Navigation Controller Interface {{{ */
6829 @interface UINavigationController (Cydia)
6831 - (NSArray *) navigationURLCollection;
6832 - (void) unloadData;
6837 /* Cydia Tab Bar Controller {{{ */
6838 @interface CydiaTabBarController : CyteTabBarController <
6839 UITabBarControllerDelegate,
6842 _transient Database *database_;
6844 _H<UIActivityIndicatorView> indicator_;
6847 // XXX: ok, "updatedelegate_"?...
6848 _transient NSObject<CydiaDelegate> *updatedelegate_;
6851 - (NSArray *) navigationURLCollection;
6852 - (void) beginUpdate;
6857 @implementation CydiaTabBarController
6859 - (NSArray *) navigationURLCollection {
6860 NSMutableArray *items([NSMutableArray array]);
6862 // XXX: Should this deal with transient view controllers?
6863 for (id navigation in [self viewControllers]) {
6864 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6866 [items addObject:stack];
6872 - (id) initWithDatabase:(Database *)database {
6873 if ((self = [super init]) != nil) {
6874 database_ = database;
6875 [self setDelegate:self];
6877 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6878 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6880 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6884 - (void) setUpdate:(NSDate *)date {
6888 - (void) beginUpdate {
6892 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6893 UITabBarItem *item([controller tabBarItem]);
6895 [item setBadgeValue:@""];
6896 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6898 [indicator_ startAnimating];
6899 [badge addSubview:indicator_];
6901 [updatedelegate_ retainNetworkActivityIndicator];
6905 detachNewThreadSelector:@selector(performUpdate)
6911 - (void) performUpdate {
6912 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6914 SourceStatus status(self, database_);
6915 [database_ updateWithStatus:status];
6918 performSelectorOnMainThread:@selector(completeUpdate)
6926 - (void) stopUpdateWithSelector:(SEL)selector {
6928 [updatedelegate_ releaseNetworkActivityIndicator];
6930 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6931 [[controller tabBarItem] setBadgeValue:nil];
6933 [indicator_ removeFromSuperview];
6934 [indicator_ stopAnimating];
6936 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6939 - (void) completeUpdate {
6942 [self stopUpdateWithSelector:@selector(reloadData)];
6945 - (void) cancelUpdate {
6946 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
6949 - (void) cancelPressed {
6950 [self cancelUpdate];
6957 - (bool) isSourceCancelled {
6961 - (void) startSourceFetch:(NSString *)uri {
6964 - (void) stopSourceFetch:(NSString *)uri {
6967 - (void) setUpdateDelegate:(id)delegate {
6968 updatedelegate_ = delegate;
6971 - (UIView *) transitionView {
6972 if (![self respondsToSelector:@selector(_transitionView)])
6973 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6974 else if (kCFCoreFoundationVersionNumber < 800)
6975 return [self _transitionView];
6977 return [[[self _transitionView] superview] superview];
6983 /* Cydia Navigation Controller Implementation {{{ */
6984 @implementation UINavigationController (Cydia)
6986 - (NSArray *) navigationURLCollection {
6987 NSMutableArray *stack([NSMutableArray array]);
6989 for (CyteViewController *controller in [self viewControllers]) {
6990 NSString *url = [[controller navigationURL] absoluteString];
6992 [stack addObject:url];
6998 - (void) reloadData {
7001 UIViewController *visible([self visibleViewController]);
7003 [visible reloadData];
7005 // on the iPad, this view controller is ALSO visible. :(
7007 if (UIViewController *top = [self topViewController])
7012 - (void) unloadData {
7013 for (CyteViewController *page in [self viewControllers])
7022 /* Cydia:// Protocol {{{ */
7023 @interface CydiaURLProtocol : NSURLProtocol {
7028 @implementation CydiaURLProtocol
7030 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7031 NSURL *url([request URL]);
7035 NSString *scheme([[url scheme] lowercaseString]);
7036 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7038 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7044 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7048 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7049 id<NSURLProtocolClient> client([self client]);
7051 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7053 NSData *data(UIImagePNGRepresentation(icon));
7055 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7056 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7057 [client URLProtocol:self didLoadData:data];
7058 [client URLProtocolDidFinishLoading:self];
7062 - (void) startLoading {
7063 id<NSURLProtocolClient> client([self client]);
7064 NSURLRequest *request([self request]);
7066 NSURL *url([request URL]);
7067 NSString *href([url absoluteString]);
7068 NSString *scheme([[url scheme] lowercaseString]);
7072 if ([scheme isEqualToString:@"cydia"])
7073 path = [href substringFromIndex:8];
7074 else if ([scheme isEqualToString:@"about"])
7075 path = [href substringFromIndex:12];
7076 else _assert(false);
7078 NSRange slash([path rangeOfString:@"/"]);
7081 if (slash.location == NSNotFound) {
7085 command = [path substringToIndex:slash.location];
7086 path = [path substringFromIndex:(slash.location + 1)];
7089 Database *database([Database sharedInstance]);
7091 if ([command isEqualToString:@"package-icon"]) {
7094 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7095 Package *package([database packageWithName:path]);
7099 UIImage *icon([package icon]);
7100 [self _returnPNGWithImage:icon forRequest:request];
7101 } else if ([command isEqualToString:@"uikit-image"]) {
7104 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7105 UIImage *icon(_UIImageWithName(path));
7106 [self _returnPNGWithImage:icon forRequest:request];
7107 } else if ([command isEqualToString:@"section-icon"]) {
7110 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7111 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7113 icon = [UIImage applicationImageNamed:@"unknown.png"];
7114 [self _returnPNGWithImage:icon forRequest:request];
7116 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7120 - (void) stopLoading {
7126 /* Section Controller {{{ */
7127 @interface SectionController : FilteredPackageListController {
7129 _H<NSString> section_;
7132 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7136 @implementation SectionController
7138 - (NSURL *) referrerURL {
7139 NSString *name(section_);
7140 name = name ?: @"*";
7141 NSString *key(key_);
7143 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7146 - (NSURL *) navigationURL {
7147 NSString *name(section_);
7148 name = name ?: @"*";
7149 NSString *key(key_);
7151 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7154 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7157 title = UCLocalize("ALL_PACKAGES");
7158 else if (![section isEqual:@""])
7159 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7161 title = UCLocalize("NO_SECTION");
7163 if ((self = [super initWithDatabase:database title:title]) != nil) {
7164 key_ = [source key];
7169 - (void) reloadData {
7170 Source *source([database_ sourceWithKey:key_]);
7171 _H<NSString> name(section_);
7173 [self setFilter:[=](Package *package) {
7174 NSString *section([package section]);
7178 section == nil && [name length] == 0 ||
7179 [name isEqualToString:section]
7182 [package source] == source
7183 ) && [package visible];
7191 /* Sections Controller {{{ */
7192 @interface SectionsController : CyteViewController <
7193 UITableViewDataSource,
7196 _transient Database *database_;
7198 _H<NSMutableArray> sections_;
7199 _H<NSMutableArray> filtered_;
7200 _H<UITableView, 2> list_;
7203 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7204 - (void) editButtonClicked;
7208 @implementation SectionsController
7210 - (NSURL *) navigationURL {
7211 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7214 - (Source *) source {
7217 return [database_ sourceWithKey:key_];
7220 - (void) updateNavigationItem {
7221 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7222 if ([sections_ count] == 0) {
7223 [[self navigationItem] setRightBarButtonItem:nil];
7225 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7226 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7228 action:@selector(editButtonClicked)
7229 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7233 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7234 [super setEditing:editing animated:animated];
7239 [delegate_ updateData];
7241 [self updateNavigationItem];
7244 - (void) viewDidAppear:(BOOL)animated {
7245 [super viewDidAppear:animated];
7246 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7249 - (void) viewWillDisappear:(BOOL)animated {
7250 [super viewWillDisappear:animated];
7251 [self setEditing:NO];
7254 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7255 Section *section = nil;
7256 int index = [indexPath row];
7257 if (![self isEditing]) {
7260 section = [filtered_ objectAtIndex:index];
7262 section = [sections_ objectAtIndex:index];
7267 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7268 if ([self isEditing])
7269 return [sections_ count];
7271 return [filtered_ count] + 1;
7274 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7278 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7279 static NSString *reuseIdentifier = @"SectionCell";
7281 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7283 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7285 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7290 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7291 if ([self isEditing])
7294 Section *section = [self sectionAtIndexPath:indexPath];
7296 SectionController *controller = [[[SectionController alloc]
7297 initWithDatabase:database_
7298 source:[self source]
7299 section:[section name]
7301 [controller setDelegate:delegate_];
7303 [[self navigationController] pushViewController:controller animated:YES];
7307 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7308 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7309 [list_ setRowHeight:46];
7310 [(UITableView *) list_ setDataSource:self];
7311 [list_ setDelegate:self];
7312 [self setView:list_];
7315 - (void) viewDidLoad {
7316 [super viewDidLoad];
7318 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7321 - (void) releaseSubviews {
7327 [super releaseSubviews];
7330 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7331 if ((self = [super init]) != nil) {
7332 database_ = database;
7333 key_ = [source key];
7337 - (void) reloadData {
7340 NSArray *packages = [database_ packages];
7342 sections_ = [NSMutableArray arrayWithCapacity:16];
7343 filtered_ = [NSMutableArray arrayWithCapacity:16];
7345 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7347 Source *source([self source]);
7350 for (Package *package in packages) {
7351 if (source != nil && [package source] != source)
7354 NSString *name([package section]);
7355 NSString *key(name == nil ? @"" : name);
7359 _profile(SectionsView$reloadData$Section)
7360 section = [sections objectForKey:key];
7361 if (section == nil) {
7362 _profile(SectionsView$reloadData$Section$Allocate)
7363 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7364 [sections setObject:section forKey:key];
7369 [section addToCount];
7371 _profile(SectionsView$reloadData$Filter)
7372 if (![package valid] || ![package visible])
7380 [sections_ addObjectsFromArray:[sections allValues]];
7382 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7384 for (Section *section in (id) sections_) {
7385 size_t count([section row]);
7389 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7390 [section setCount:count];
7391 [filtered_ addObject:section];
7394 [self updateNavigationItem];
7399 - (void) editButtonClicked {
7400 [self setEditing:![self isEditing] animated:YES];
7406 /* Changes Controller {{{ */
7407 @interface ChangesController : FilteredPackageListController {
7411 - (id) initWithDatabase:(Database *)database;
7415 @implementation ChangesController
7417 - (NSURL *) referrerURL {
7418 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7421 - (NSURL *) navigationURL {
7422 return [NSURL URLWithString:@"cydia://changes"];
7425 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7426 @synchronized (database_) {
7427 if ([database_ era] != era_)
7430 NSUInteger sectionIndex([path section]);
7431 if (sectionIndex >= [sections_ count])
7433 Section *section([sections_ objectAtIndex:sectionIndex]);
7434 NSInteger row([path row]);
7435 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7438 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7439 NSString *context([alert context]);
7441 if ([context isEqualToString:@"norefresh"])
7442 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7445 - (void) setLeftBarButtonItem {
7446 if ([delegate_ updating])
7447 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7448 initWithTitle:UCLocalize("CANCEL")
7449 style:UIBarButtonItemStyleDone
7451 action:@selector(cancelButtonClicked)
7452 ] autorelease] animated:YES];
7454 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7455 initWithTitle:UCLocalize("REFRESH")
7456 style:UIBarButtonItemStylePlain
7458 action:@selector(refreshButtonClicked)
7459 ] autorelease] animated:YES];
7462 - (void) refreshButtonClicked {
7463 if ([delegate_ requestUpdate])
7464 [self setLeftBarButtonItem];
7467 - (void) cancelButtonClicked {
7468 [delegate_ cancelUpdate];
7471 - (void) upgradeButtonClicked {
7472 [delegate_ distUpgrade];
7473 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7476 - (bool) shouldYield {
7480 - (bool) shouldBlock {
7484 - (void) useFilter {
7485 @synchronized (self) {
7486 [self setFilter:[](Package *package) {
7487 return [package upgradableAndEssential:YES] || [package visible];
7490 [self setSorter:[](NSMutableArray *packages) {
7491 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7495 - (id) initWithDatabase:(Database *)database {
7496 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7501 - (void) viewDidLoad {
7502 [super viewDidLoad];
7503 [self setLeftBarButtonItem];
7506 - (void) viewWillAppear:(BOOL)animated {
7507 [super viewWillAppear:animated];
7508 [self setLeftBarButtonItem];
7511 - (void) reloadData {
7512 [self setLeftBarButtonItem];
7516 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7517 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7519 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7520 Section *ignored = nil;
7521 Section *section = nil;
7525 bool unseens = false;
7527 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7529 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7530 Package *package = [packages objectAtIndex:offset];
7532 BOOL uae = [package upgradableAndEssential:YES];
7536 time_t seen([package seen]);
7538 if (section == nil || last != seen) {
7542 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7545 _profile(ChangesController$reloadData$Allocate)
7546 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7547 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7548 [sections addObject:section];
7552 [section addToCount];
7553 } else if ([package ignored]) {
7554 if (ignored == nil) {
7555 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7557 [ignored addToCount];
7560 [upgradable addToCount];
7565 CFRelease(formatter);
7568 Section *last = [sections lastObject];
7569 size_t count = [last count];
7570 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7571 [sections removeLastObject];
7574 if ([ignored count] != 0)
7575 [sections insertObject:ignored atIndex:0];
7577 [sections insertObject:upgradable atIndex:0];
7581 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7582 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7583 style:UIBarButtonItemStylePlain
7585 action:@selector(upgradeButtonClicked)
7586 ] autorelease]) animated:YES];
7593 /* Search Controller {{{ */
7594 @interface SearchController : FilteredPackageListController <
7597 _H<UISearchBar, 1> search_;
7602 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7603 - (void) reloadData;
7607 @implementation SearchController
7609 - (NSURL *) referrerURL {
7610 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7613 - (NSURL *) navigationURL {
7614 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7615 return [NSURL URLWithString:@"cydia://search"];
7617 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7620 - (NSArray *) termsForQuery:(NSString *)query {
7621 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7622 for (NSString *component in [query componentsSeparatedByString:@" "])
7623 if ([component length] != 0)
7624 [terms addObject:component];
7629 - (void) useSearch {
7630 _H<NSArray> query([self termsForQuery:[search_ text]]);
7633 @synchronized (self) {
7634 [self setFilter:[=](Package *package) {
7635 if (![package unfiltered])
7637 if (![package matches:query])
7642 [self setSorter:[](NSMutableArray *packages) {
7643 [packages radixSortUsingSelector:@selector(rank)];
7651 - (void) usePrefix:(NSString *)prefix {
7652 _H<NSString> query(prefix);
7655 @synchronized (self) {
7656 [self setFilter:[=](Package *package) {
7657 if ([query length] == 0)
7659 if (![package unfiltered])
7661 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7666 [self setSorter:nullptr];
7672 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7674 [self usePrefix:[search_ text]];
7677 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7678 [search_ resignFirstResponder];
7682 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7683 [search_ setText:@""];
7684 [self searchBarButtonClicked:searchBar];
7687 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7688 [self searchBarButtonClicked:searchBar];
7691 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7692 [self usePrefix:text];
7695 - (bool) shouldYield {
7699 - (bool) shouldBlock {
7703 - (bool) isSummarized {
7707 - (bool) showsSections {
7711 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7712 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7713 search_ = [[[UISearchBar alloc] init] autorelease];
7714 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7715 [search_ setDelegate:self];
7717 UITextField *textField;
7718 if ([search_ respondsToSelector:@selector(searchField)])
7719 textField = [search_ searchField];
7721 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7723 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7724 [textField setEnablesReturnKeyAutomatically:NO];
7725 [[self navigationItem] setTitleView:textField];
7728 [search_ setText:query];
7733 - (void) viewDidAppear:(BOOL)animated {
7734 [super viewDidAppear:animated];
7736 if (!searchloaded_) {
7737 searchloaded_ = YES;
7738 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7739 [search_ layoutSubviews];
7742 if ([self isSummarized])
7743 [search_ becomeFirstResponder];
7746 - (void) reloadData {
7751 - (void) didSelectPackage:(Package *)package {
7752 [search_ resignFirstResponder];
7753 [super didSelectPackage:package];
7758 /* Package Settings Controller {{{ */
7759 @interface PackageSettingsController : CyteViewController <
7760 UITableViewDataSource,
7763 _transient Database *database_;
7765 _H<Package> package_;
7766 _H<UITableView, 2> table_;
7767 _H<UISwitch> subscribedSwitch_;
7768 _H<UISwitch> ignoredSwitch_;
7769 _H<UITableViewCell> subscribedCell_;
7770 _H<UITableViewCell> ignoredCell_;
7773 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7777 @implementation PackageSettingsController
7779 - (NSURL *) navigationURL {
7780 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7783 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7784 if (package_ == nil)
7787 if ([package_ installed] == nil)
7793 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7794 if (package_ == nil)
7797 // both sections contain just one item right now.
7801 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7805 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7807 return UCLocalize("SHOW_ALL_CHANGES_EX");
7809 return UCLocalize("IGNORE_UPGRADES_EX");
7812 - (void) onSubscribed:(id)control {
7813 bool value([control isOn]);
7814 if (package_ == nil)
7816 if ([package_ setSubscribed:value])
7817 [delegate_ updateData];
7820 - (void) _updateIgnored {
7821 const char *package([name_ UTF8String]);
7822 bool on([ignoredSwitch_ isOn]);
7824 pid_t pid(ExecFork());
7826 FILE *dpkg(popen("dpkg --set-selections", "w"));
7827 fwrite(package, strlen(package), 1, dpkg);
7830 fwrite(" hold\n", 6, 1, dpkg);
7832 fwrite(" install\n", 9, 1, dpkg);
7840 - (void) onIgnored:(id)control {
7841 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7842 [invocation setTarget:self];
7843 [invocation setSelector:@selector(_updateIgnored)];
7845 [delegate_ reloadDataWithInvocation:invocation];
7848 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7849 if (package_ == nil)
7852 switch ([indexPath section]) {
7853 case 0: return subscribedCell_;
7854 case 1: return ignoredCell_;
7863 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7864 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7865 [self setView:view];
7867 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7868 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7869 [(UITableView *) table_ setDataSource:self];
7870 [table_ setDelegate:self];
7871 [view addSubview:table_];
7873 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7874 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7875 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7877 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7878 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7879 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7881 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7882 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7883 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7884 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7886 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7887 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7888 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7889 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7892 - (void) viewDidLoad {
7893 [super viewDidLoad];
7895 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7898 - (void) releaseSubviews {
7900 subscribedCell_ = nil;
7902 ignoredSwitch_ = nil;
7903 subscribedSwitch_ = nil;
7905 [super releaseSubviews];
7908 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7909 if ((self = [super init]) != nil) {
7910 database_ = database;
7915 - (void) reloadData {
7918 package_ = [database_ packageWithName:name_];
7920 if (package_ != nil) {
7921 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7922 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7923 } // XXX: what now, G?
7925 [table_ reloadData];
7931 /* Installed Controller {{{ */
7932 @interface InstalledController : FilteredPackageListController {
7936 - (id) initWithDatabase:(Database *)database;
7937 - (void) queueStatusDidChange;
7941 @implementation InstalledController
7943 - (NSURL *) referrerURL {
7944 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
7947 - (NSURL *) navigationURL {
7948 return [NSURL URLWithString:@"cydia://installed"];
7951 - (bool) showsSections {
7955 - (void) useUpdated {
7958 @synchronized (self) {
7959 [self setFilter:[](Package *package) {
7960 return ![package uninstalled] && package->role_ < 7;
7963 [self setSorter:[](NSMutableArray *packages) {
7964 [packages radixSortUsingSelector:@selector(updated)];
7968 - (void) useFilter:(UISegmentedControl *)segmented {
7969 NSInteger selected([segmented selectedSegmentIndex]);
7971 return [self useUpdated];
7972 bool simple(selected == 0);
7975 @synchronized (self) {
7976 [self setFilter:[=](Package *package) {
7977 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
7980 [self setSorter:nullptr];
7983 - (id) initWithDatabase:(Database *)database {
7984 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
7985 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
7986 [segmented setSelectedSegmentIndex:0];
7987 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
7988 [[self navigationItem] setTitleView:segmented];
7990 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
7991 [self useFilter:segmented];
7993 [self queueStatusDidChange];
7998 - (void) queueButtonClicked {
8003 - (void) queueStatusDidChange {
8006 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8007 initWithTitle:UCLocalize("QUEUE")
8008 style:UIBarButtonItemStyleDone
8010 action:@selector(queueButtonClicked)
8013 [[self navigationItem] setLeftBarButtonItem:nil];
8018 - (void) modeChanged:(UISegmentedControl *)segmented {
8019 [self useFilter:segmented];
8026 /* Source Cell {{{ */
8027 @interface SourceCell : CyteTableViewCell <
8028 CyteTableViewCellDelegate,
8031 _H<Source, 1> source_;
8034 _H<NSString> origin_;
8035 _H<NSString> label_;
8036 _H<UIActivityIndicatorView> indicator_;
8039 - (void) setSource:(Source *)source;
8040 - (void) setFetch:(NSNumber *)fetch;
8044 @implementation SourceCell
8046 - (void) _setImage:(NSArray *)data {
8047 if ([url_ isEqual:[data objectAtIndex:0]]) {
8048 icon_ = [data objectAtIndex:1];
8049 [content_ setNeedsDisplay];
8053 - (void) _setSource:(NSURL *) url {
8054 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8056 if (NSData *data = [NSURLConnection
8057 sendSynchronousRequest:[NSURLRequest
8059 cachePolicy:NSURLRequestUseProtocolCachePolicy
8063 returningResponse:NULL
8066 if (UIImage *image = [UIImage imageWithData:data])
8067 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8072 - (void) setSource:(Source *)source {
8074 [source_ setDelegate:self];
8076 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8078 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8080 origin_ = [source name];
8081 label_ = [source rooturi];
8083 [content_ setNeedsDisplay];
8085 url_ = [source iconURL];
8086 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8089 - (void) setAllSource {
8091 [indicator_ stopAnimating];
8093 icon_ = [UIImage applicationImageNamed:@"folder.png"];
8094 origin_ = UCLocalize("ALL_SOURCES");
8095 label_ = UCLocalize("ALL_SOURCES_EX");
8096 [content_ setNeedsDisplay];
8099 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8100 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8101 UIView *content([self contentView]);
8102 CGRect bounds([content bounds]);
8104 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8105 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8106 [content_ setBackgroundColor:[UIColor whiteColor]];
8107 [content addSubview:content_];
8109 [content_ setDelegate:self];
8110 [content_ setOpaque:YES];
8112 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8113 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8114 [content addSubview:indicator_];
8116 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8120 - (void) layoutSubviews {
8121 [super layoutSubviews];
8123 UIView *content([self contentView]);
8124 CGRect bounds([content bounds]);
8126 CGRect frame([indicator_ frame]);
8127 frame.origin.x = bounds.size.width - frame.size.width;
8128 frame.origin.y = (bounds.size.height - frame.size.height) / 2;
8130 if (kCFCoreFoundationVersionNumber < 800)
8131 frame.origin.x -= 8;
8132 [indicator_ setFrame:frame];
8135 - (NSString *) accessibilityLabel {
8139 - (void) drawContentRect:(CGRect)rect {
8140 bool highlighted(highlighted_);
8141 float width(rect.size.width);
8145 rect.size = [(UIImage *) icon_ size];
8147 while (rect.size.width > 32 || rect.size.height > 32) {
8148 rect.size.width /= 2;
8149 rect.size.height /= 2;
8152 rect.origin.x = 26 - rect.size.width / 2;
8153 rect.origin.y = 26 - rect.size.height / 2;
8155 [icon_ drawInRect:rect];
8158 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8163 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 61) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8167 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 61) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8170 - (void) setFetch:(NSNumber *)fetch {
8171 if ([fetch boolValue])
8172 [indicator_ startAnimating];
8174 [indicator_ stopAnimating];
8179 /* Sources Controller {{{ */
8180 @interface SourcesController : CyteViewController <
8181 UITableViewDataSource,
8184 _transient Database *database_;
8187 _H<UITableView, 2> list_;
8188 _H<NSMutableArray> sources_;
8192 _H<UIProgressHUD> hud_;
8195 NSURLConnection *trivial_bz2_;
8196 NSURLConnection *trivial_gz_;
8201 - (id) initWithDatabase:(Database *)database;
8202 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8206 @implementation SourcesController
8208 - (void) _releaseConnection:(NSURLConnection *)connection {
8209 if (connection != nil) {
8210 [connection cancel];
8211 //[connection setDelegate:nil];
8212 [connection release];
8217 [self _releaseConnection:trivial_gz_];
8218 [self _releaseConnection:trivial_bz2_];
8223 - (NSURL *) navigationURL {
8224 return [NSURL URLWithString:@"cydia://sources"];
8227 - (void) viewDidAppear:(BOOL)animated {
8228 [super viewDidAppear:animated];
8229 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8232 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8236 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8238 return UCLocalize("INDIVIDUAL_SOURCES");
8242 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8245 case 1: return [sources_ count];
8250 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8251 @synchronized (database_) {
8252 if ([database_ era] != era_)
8254 if ([indexPath section] != 1)
8256 NSUInteger index([indexPath row]);
8257 if (index >= [sources_ count])
8259 return [sources_ objectAtIndex:index];
8262 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8263 static NSString *cellIdentifier = @"SourceCell";
8265 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8266 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8267 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8269 Source *source([self sourceAtIndexPath:indexPath]);
8271 [cell setAllSource];
8273 [cell setSource:source];
8278 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8279 SectionsController *controller([[[SectionsController alloc]
8280 initWithDatabase:database_
8281 source:[self sourceAtIndexPath:indexPath]
8284 [controller setDelegate:delegate_];
8285 [[self navigationController] pushViewController:controller animated:YES];
8288 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8289 if ([indexPath section] != 1)
8291 Source *source = [self sourceAtIndexPath:indexPath];
8292 return [source record] != nil;
8295 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8296 _assert([indexPath section] == 1);
8297 if (editingStyle == UITableViewCellEditingStyleDelete) {
8298 Source *source = [self sourceAtIndexPath:indexPath];
8299 if (source == nil) return;
8301 [Sources_ removeObjectForKey:[source key]];
8304 [delegate_ _saveConfig];
8305 [delegate_ reloadDataWithInvocation:nil];
8309 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8310 [self updateButtonsForEditingStatusAnimated:YES];
8314 [delegate_ addTrivialSource:href_];
8317 [delegate_ syncData];
8320 - (NSString *) getWarning {
8321 NSString *href(href_);
8322 NSRange colon([href rangeOfString:@"://"]);
8323 if (colon.location != NSNotFound)
8324 href = [href substringFromIndex:(colon.location + 3)];
8325 href = [href stringByAddingPercentEscapes];
8326 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8328 NSURL *url([NSURL URLWithString:href]);
8330 NSStringEncoding encoding;
8331 NSError *error(nil);
8333 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8334 return [warning length] == 0 ? nil : warning;
8338 - (void) _endConnection:(NSURLConnection *)connection {
8339 // XXX: the memory management in this method is horribly awkward
8341 NSURLConnection **field = NULL;
8342 if (connection == trivial_bz2_)
8343 field = &trivial_bz2_;
8344 else if (connection == trivial_gz_)
8345 field = &trivial_gz_;
8346 _assert(field != NULL);
8347 [connection release];
8351 trivial_bz2_ == nil &&
8354 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8356 [delegate_ releaseNetworkActivityIndicator];
8358 [delegate_ removeProgressHUD:hud_];
8362 if (warning != nil) {
8363 UIAlertView *alert = [[[UIAlertView alloc]
8364 initWithTitle:UCLocalize("SOURCE_WARNING")
8367 cancelButtonTitle:UCLocalize("CANCEL")
8369 UCLocalize("ADD_ANYWAY"),
8373 [alert setContext:@"warning"];
8374 [alert setNumberOfRows:1];
8377 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8383 } else if (error_ != nil) {
8384 UIAlertView *alert = [[[UIAlertView alloc]
8385 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8386 message:[error_ localizedDescription]
8388 cancelButtonTitle:UCLocalize("OK")
8389 otherButtonTitles:nil
8392 [alert setContext:@"urlerror"];
8397 UIAlertView *alert = [[[UIAlertView alloc]
8398 initWithTitle:UCLocalize("NOT_REPOSITORY")
8399 message:UCLocalize("NOT_REPOSITORY_EX")
8401 cancelButtonTitle:UCLocalize("OK")
8402 otherButtonTitles:nil
8405 [alert setContext:@"trivial"];
8415 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8416 switch ([response statusCode]) {
8422 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8423 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8425 [self _endConnection:connection];
8428 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8429 [self _endConnection:connection];
8432 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8433 NSURL *url([NSURL URLWithString:href]);
8435 NSMutableURLRequest *request = [NSMutableURLRequest
8437 cachePolicy:NSURLRequestUseProtocolCachePolicy
8441 [request setHTTPMethod:method];
8443 if (Machine_ != NULL)
8444 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8446 if (UniqueID_ != nil)
8447 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8449 if ([url isCydiaSecure]) {
8450 if (UniqueID_ != nil)
8451 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8454 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8457 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8458 NSString *context([alert context]);
8460 if ([context isEqualToString:@"source"]) {
8463 NSString *href = [[alert textField] text];
8465 static Pcre href_r("^http(s?)://[^# ]*$");
8466 if (!href_r(href)) {
8467 UIAlertView *alert = [[[UIAlertView alloc]
8468 initWithTitle:Error_
8469 message:UCLocalize("INVALID_URL")
8471 cancelButtonTitle:UCLocalize("OK")
8472 otherButtonTitles:nil
8475 [alert setContext:@"badurl"];
8481 if (![href hasSuffix:@"/"])
8482 href_ = [href stringByAppendingString:@"/"];
8486 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8487 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8491 // XXX: this is stupid
8492 hud_ = [delegate_ addProgressHUD];
8493 [hud_ setText:UCLocalize("VERIFYING_URL")];
8494 [delegate_ retainNetworkActivityIndicator];
8503 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8504 } else if ([context isEqualToString:@"trivial"])
8505 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8506 else if ([context isEqualToString:@"urlerror"])
8507 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8508 else if ([context isEqualToString:@"warning"]) {
8511 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8520 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8524 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8525 BOOL editing([list_ isEditing]);
8528 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8529 initWithTitle:UCLocalize("ADD")
8530 style:UIBarButtonItemStylePlain
8532 action:@selector(addButtonClicked)
8533 ] autorelease] animated:animated];
8534 else if ([delegate_ updating])
8535 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8536 initWithTitle:UCLocalize("CANCEL")
8537 style:UIBarButtonItemStyleDone
8539 action:@selector(cancelButtonClicked)
8540 ] autorelease] animated:animated];
8542 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8543 initWithTitle:UCLocalize("REFRESH")
8544 style:UIBarButtonItemStylePlain
8546 action:@selector(refreshButtonClicked)
8547 ] autorelease] animated:animated];
8549 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8550 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8551 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8553 action:@selector(editButtonClicked)
8554 ] autorelease] animated:animated];
8558 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8559 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8560 [list_ setRowHeight:53];
8561 [(UITableView *) list_ setDataSource:self];
8562 [list_ setDelegate:self];
8563 [self setView:list_];
8566 - (void) viewDidLoad {
8567 [super viewDidLoad];
8569 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8570 [self updateButtonsForEditingStatusAnimated:NO];
8573 - (void) viewWillAppear:(BOOL)animated {
8574 [super viewWillAppear:animated];
8576 [list_ setEditing:NO];
8577 [self updateButtonsForEditingStatusAnimated:NO];
8580 - (void) releaseSubviews {
8585 [super releaseSubviews];
8588 - (id) initWithDatabase:(Database *)database {
8589 if ((self = [super init]) != nil) {
8590 database_ = database;
8594 - (void) reloadData {
8596 [self updateButtonsForEditingStatusAnimated:YES];
8598 @synchronized (database_) {
8599 era_ = [database_ era];
8601 sources_ = [NSMutableArray arrayWithCapacity:16];
8602 [sources_ addObjectsFromArray:[database_ sources]];
8604 [sources_ sortUsingSelector:@selector(compareByName:)];
8607 int count([sources_ count]);
8609 for (int i = 0; i != count; i++) {
8610 if ([[sources_ objectAtIndex:i] record] == nil)
8618 - (void) showAddSourcePrompt {
8619 UIAlertView *alert = [[[UIAlertView alloc]
8620 initWithTitle:UCLocalize("ENTER_APT_URL")
8623 cancelButtonTitle:UCLocalize("CANCEL")
8625 UCLocalize("ADD_SOURCE"),
8629 [alert setContext:@"source"];
8631 [alert setNumberOfRows:1];
8632 [alert addTextFieldWithValue:@"http://" label:@""];
8634 UITextInputTraits *traits = [[alert textField] textInputTraits];
8635 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8636 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8637 [traits setKeyboardType:UIKeyboardTypeURL];
8638 // XXX: UIReturnKeyDone
8639 [traits setReturnKeyType:UIReturnKeyNext];
8644 - (void) addButtonClicked {
8645 [self showAddSourcePrompt];
8648 - (void) refreshButtonClicked {
8649 if ([delegate_ requestUpdate])
8650 [self updateButtonsForEditingStatusAnimated:YES];
8653 - (void) cancelButtonClicked {
8654 [delegate_ cancelUpdate];
8657 - (void) editButtonClicked {
8658 [list_ setEditing:![list_ isEditing] animated:YES];
8659 [self updateButtonsForEditingStatusAnimated:YES];
8665 /* Stash Controller {{{ */
8666 @interface StashController : CyteViewController {
8667 _H<UIActivityIndicatorView> spinner_;
8668 _H<UILabel> status_;
8669 _H<UILabel> caption_;
8674 @implementation StashController
8677 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8678 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8679 [self setView:view];
8681 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8683 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8684 CGRect spinrect = [spinner_ frame];
8685 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8686 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8687 [spinner_ setFrame:spinrect];
8688 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8689 [view addSubview:spinner_];
8690 [spinner_ startAnimating];
8693 captrect.size.width = [[self view] frame].size.width;
8694 captrect.size.height = 40.0f;
8695 captrect.origin.x = 0;
8696 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8697 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8698 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8699 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8700 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8701 [caption_ setTextColor:[UIColor whiteColor]];
8702 [caption_ setBackgroundColor:[UIColor clearColor]];
8703 [caption_ setShadowColor:[UIColor blackColor]];
8704 [caption_ setTextAlignment:NSTextAlignmentCenter];
8705 [view addSubview:caption_];
8708 statusrect.size.width = [[self view] frame].size.width;
8709 statusrect.size.height = 30.0f;
8710 statusrect.origin.x = 0;
8711 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8712 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8713 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8714 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8715 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8716 [status_ setTextColor:[UIColor whiteColor]];
8717 [status_ setBackgroundColor:[UIColor clearColor]];
8718 [status_ setShadowColor:[UIColor blackColor]];
8719 [status_ setTextAlignment:NSTextAlignmentCenter];
8720 [view addSubview:status_];
8723 - (void) releaseSubviews {
8728 [super releaseSubviews];
8734 @interface CYURLCache : SDURLCache {
8739 @implementation CYURLCache
8741 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8744 else if ([event isEqualToString:@"no-cache"])
8746 else if ([event isEqualToString:@"store"])
8748 else if ([event isEqualToString:@"invalid"])
8750 else if ([event isEqualToString:@"memory"])
8752 else if ([event isEqualToString:@"disk"])
8754 else if ([event isEqualToString:@"miss"])
8757 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8761 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8762 if (NSURLResponse *response = [cached response])
8763 if (NSString *mime = [response MIMEType])
8764 if ([mime isEqualToString:@"text/cache-manifest"]) {
8765 NSURL *url([response URL]);
8768 NSLog(@"###: %@", [url absoluteString]);
8771 @synchronized (HostConfig_) {
8772 [CachedURLs_ addObject:url];
8776 [super storeCachedResponse:cached forRequest:request];
8781 @interface Cydia : UIApplication <
8782 ConfirmationControllerDelegate,
8785 UINavigationControllerDelegate,
8786 UITabBarControllerDelegate
8788 _H<UIWindow> window_;
8789 _H<CydiaTabBarController> tabbar_;
8790 _H<CydiaLoadingViewController> emulated_;
8792 _H<NSMutableArray> essential_;
8793 _H<NSMutableArray> broken_;
8795 Database *database_;
8797 _H<NSURL> starturl_;
8802 _H<StashController> stash_;
8811 @implementation Cydia
8813 - (void) lockSuspend {
8814 if (locked_++ == 0) {
8815 if ($SBSSetInterceptsMenuButtonForever != NULL)
8816 (*$SBSSetInterceptsMenuButtonForever)(true);
8818 [self setIdleTimerDisabled:YES];
8822 - (void) unlockSuspend {
8823 if (--locked_ == 0) {
8824 [self setIdleTimerDisabled:NO];
8826 if ($SBSSetInterceptsMenuButtonForever != NULL)
8827 (*$SBSSetInterceptsMenuButtonForever)(false);
8831 - (void) beginUpdate {
8832 [tabbar_ beginUpdate];
8835 - (void) cancelUpdate {
8836 [tabbar_ cancelUpdate];
8839 - (bool) requestUpdate {
8840 if (IsReachable("cydia.saurik.com")) {
8844 UIAlertView *alert = [[[UIAlertView alloc]
8845 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8846 message:@"Host Unreachable" // XXX: Localize
8848 cancelButtonTitle:UCLocalize("OK")
8849 otherButtonTitles:nil
8852 [alert setContext:@"norefresh"];
8860 return [tabbar_ updating];
8864 if ([broken_ count] != 0) {
8865 int count = [broken_ count];
8867 UIAlertView *alert = [[[UIAlertView alloc]
8868 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8869 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8871 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8873 UCLocalize("TEMPORARY_IGNORE"),
8877 [alert setContext:@"fixhalf"];
8878 [alert setNumberOfRows:2];
8880 } else if (!Ignored_ && [essential_ count] != 0) {
8881 int count = [essential_ count];
8883 UIAlertView *alert = [[[UIAlertView alloc]
8884 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8885 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8887 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8889 UCLocalize("UPGRADE_ESSENTIAL"),
8890 UCLocalize("COMPLETE_UPGRADE"),
8894 [alert setContext:@"upgrade"];
8899 - (void) returnToCydia {
8903 - (void) _saveConfig {
8904 @synchronized (database_) {
8911 NSString *error(nil);
8913 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8915 NSError *error(nil);
8916 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8917 NSLog(@"failure to save metadata data: %@", error);
8922 NSLog(@"failure to serialize metadata: %@", error);
8926 CydiaWriteSources();
8929 // Navigation controller for the queuing badge.
8930 - (UINavigationController *) queueNavigationController {
8931 NSArray *controllers = [tabbar_ viewControllers];
8932 return [controllers objectAtIndex:3];
8935 - (void) unloadData {
8936 [tabbar_ unloadData];
8939 - (void) _updateData {
8943 UINavigationController *navigation = [self queueNavigationController];
8945 id queuedelegate = nil;
8946 if ([[navigation viewControllers] count] > 0)
8947 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8949 [queuedelegate queueStatusDidChange];
8950 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8953 - (void) _refreshIfPossible:(NSDate *)update {
8954 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8956 bool recently = false;
8957 if (update != nil) {
8958 NSTimeInterval interval([update timeIntervalSinceNow]);
8959 if (interval <= 0 && interval > -(15*60))
8963 // Don't automatic refresh if:
8964 // - We already refreshed recently.
8965 // - We already auto-refreshed this launch.
8966 // - Auto-refresh is disabled.
8967 // - Cydia's server is not reachable
8968 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
8969 // If we are cancelling, we need to make sure it knows it's already loaded.
8972 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8974 // We are going to load, so remember that.
8977 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8983 - (void) refreshIfPossible {
8984 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8987 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8988 _profile(reloadDataWithInvocation)
8989 @synchronized (self) {
8990 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8992 [hud setText:UCLocalize("RELOADING_DATA")];
8994 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8998 [essential_ removeAllObjects];
8999 [broken_ removeAllObjects];
9001 _profile(reloadDataWithInvocation$Essential)
9002 NSArray *packages([database_ packages]);
9003 for (Package *package in packages) {
9005 [broken_ addObject:package];
9006 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9007 if ([package essential] && [package installed] != nil)
9008 [essential_ addObject:package];
9014 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9017 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9018 [changesItem setBadgeValue:badge];
9019 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9020 [self setApplicationIconBadgeNumber:changes];
9023 [changesItem setBadgeValue:nil];
9024 [changesItem setAnimatedBadge:NO];
9025 [self setApplicationIconBadgeNumber:0];
9031 [self removeProgressHUD:hud];
9038 - (void) updateData {
9042 - (void) updateDataAndLoad {
9044 if ([database_ progressDelegate] == nil)
9050 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9053 - (void) disemulate {
9054 if (emulated_ == nil)
9057 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9058 [window_ setRootViewController:tabbar_];
9060 [window_ addSubview:[tabbar_ view]];
9061 [[emulated_ view] removeFromSuperview];
9065 [window_ setUserInteractionEnabled:YES];
9068 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9069 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9071 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9073 UIViewController *parent;
9074 if (emulated_ == nil)
9083 [parent presentModalViewController:navigation animated:YES];
9086 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9087 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9089 if (navigation != nil)
9090 [navigation pushViewController:progress animated:YES];
9092 [self presentModalViewController:progress force:YES];
9094 [progress invoke:invocation withTitle:title];
9098 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9099 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9102 - (void) repairWithInvocation:(NSInvocation *)invocation {
9104 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9108 - (void) repairWithSelector:(SEL)selector {
9109 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9112 - (void) reloadData {
9113 [self reloadDataWithInvocation:nil];
9114 if ([database_ progressDelegate] == nil)
9120 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9123 - (void) addSource:(NSDictionary *) source {
9124 CydiaAddSource(source);
9127 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9128 CydiaAddSource(href, distribution, sections);
9131 - (void) addTrivialSource:(NSString *)href {
9132 CydiaAddSource(href, @"./");
9135 - (void) updateValues {
9140 pkgProblemResolver *resolver = [database_ resolver];
9142 resolver->InstallProtect();
9143 if (!resolver->Resolve(true))
9148 // XXX: this is a really crappy way of doing this.
9149 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9150 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9151 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9152 if ([tabbar_ updating])
9153 [tabbar_ cancelUpdate];
9155 if (![database_ prepare])
9158 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9159 [page setDelegate:self];
9160 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9163 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9164 [tabbar_ presentModalViewController:confirm_ animated:YES];
9170 @synchronized (self) {
9175 - (void) clearPackage:(Package *)package {
9176 @synchronized (self) {
9183 - (void) installPackages:(NSArray *)packages {
9184 @synchronized (self) {
9185 for (Package *package in packages)
9192 - (void) installPackage:(Package *)package {
9193 @synchronized (self) {
9200 - (void) removePackage:(Package *)package {
9201 @synchronized (self) {
9208 - (void) distUpgrade {
9209 @synchronized (self) {
9210 if (![database_ upgrade])
9218 system("su -c /usr/bin/uicache mobile");
9223 UIProgressHUD *hud([self addProgressHUD]);
9224 [hud setText:UCLocalize("LOADING")];
9225 [self yieldToSelector:@selector(_uicache)];
9226 [self removeProgressHUD:hud];
9230 [database_ perform];
9231 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9232 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9235 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9238 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9239 [self unlockSuspend];
9242 - (void) retainNetworkActivityIndicator {
9243 if (activity_++ == 0)
9244 [self setNetworkActivityIndicatorVisible:YES];
9247 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9251 - (void) releaseNetworkActivityIndicator {
9252 if (--activity_ == 0)
9253 [self setNetworkActivityIndicatorVisible:NO];
9256 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9261 - (void) cancelAndClear:(bool)clear {
9262 @synchronized (self) {
9274 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9275 NSString *context([alert context]);
9277 if ([context isEqualToString:@"conffile"]) {
9278 FILE *input = [database_ input];
9279 if (button == [alert cancelButtonIndex])
9280 fprintf(input, "N\n");
9281 else if (button == [alert firstOtherButtonIndex])
9282 fprintf(input, "Y\n");
9285 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9286 } else if ([context isEqualToString:@"fixhalf"]) {
9287 if (button == [alert cancelButtonIndex]) {
9288 @synchronized (self) {
9289 for (Package *broken in (id) broken_) {
9292 NSString *id = [broken id];
9293 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9294 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9295 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9296 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9302 } else if (button == [alert firstOtherButtonIndex]) {
9303 [broken_ removeAllObjects];
9307 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9308 } else if ([context isEqualToString:@"upgrade"]) {
9309 if (button == [alert firstOtherButtonIndex]) {
9310 @synchronized (self) {
9311 for (Package *essential in (id) essential_)
9312 [essential install];
9317 } else if (button == [alert firstOtherButtonIndex] + 1) {
9319 } else if (button == [alert cancelButtonIndex]) {
9323 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9327 - (void) system:(NSString *)command {
9328 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9331 system([command UTF8String]);
9337 - (void) applicationWillSuspend {
9339 [super applicationWillSuspend];
9342 - (BOOL) isSafeToSuspend {
9345 NSLog(@"isSafeToSuspend: locked_ != 0");
9350 if ([tabbar_ modalViewController] != nil)
9353 // Use external process status API internally.
9354 // This is probably a really bad idea.
9355 // XXX: what is the point of this? does this solve anything at all?
9356 uint64_t status = 0;
9358 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9359 notify_get_state(notify_token, &status);
9360 notify_cancel(notify_token);
9365 NSLog(@"isSafeToSuspend: status != 0");
9371 NSLog(@"isSafeToSuspend: -> true");
9376 - (void) applicationSuspend:(__GSEvent *)event {
9377 if ([self isSafeToSuspend])
9378 [super applicationSuspend:event];
9381 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9382 if ([self isSafeToSuspend])
9383 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9386 - (void) _setSuspended:(BOOL)value {
9387 if ([self isSafeToSuspend])
9388 [super _setSuspended:value];
9391 - (UIProgressHUD *) addProgressHUD {
9392 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9393 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9395 [window_ setUserInteractionEnabled:NO];
9397 UIViewController *target(tabbar_);
9398 if (UIViewController *modal = [target modalViewController])
9401 [hud showInView:[target view]];
9407 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9408 [self unlockSuspend];
9410 [hud removeFromSuperview];
9411 [window_ setUserInteractionEnabled:YES];
9414 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9415 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9418 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9419 NSString *scheme([[url scheme] lowercaseString]);
9420 if ([[url absoluteString] length] <= [scheme length] + 3)
9422 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9423 NSArray *components([path componentsSeparatedByString:@"/"]);
9425 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9426 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9427 if (controller != nil)
9428 [controller setDelegate:self];
9432 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9435 NSString *base([components objectAtIndex:0]);
9437 CyteViewController *controller = nil;
9439 if ([base isEqualToString:@"url"]) {
9440 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9441 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9442 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9443 } else if (!external && [components count] == 1) {
9444 if ([base isEqualToString:@"sources"]) {
9445 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9448 if ([base isEqualToString:@"home"]) {
9449 controller = [[[HomeController alloc] init] autorelease];
9452 if ([base isEqualToString:@"sections"]) {
9453 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9456 if ([base isEqualToString:@"search"]) {
9457 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9460 if ([base isEqualToString:@"changes"]) {
9461 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9464 if ([base isEqualToString:@"installed"]) {
9465 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9467 } else if ([components count] == 2) {
9468 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9470 if ([base isEqualToString:@"package"]) {
9471 controller = [self pageForPackage:argument withReferrer:referrer];
9474 if (!external && [base isEqualToString:@"search"]) {
9475 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9478 if (!external && [base isEqualToString:@"sections"]) {
9479 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9481 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9484 if (!external && [base isEqualToString:@"sources"]) {
9485 if ([argument isEqualToString:@"add"]) {
9486 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9487 [(SourcesController *)controller showAddSourcePrompt];
9489 Source *source([database_ sourceWithKey:argument]);
9490 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9494 if (!external && [base isEqualToString:@"launch"]) {
9495 [self launchApplicationWithIdentifier:argument suspended:NO];
9498 } else if (!external && [components count] == 3) {
9499 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9500 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9502 if ([base isEqualToString:@"package"]) {
9503 if ([arg2 isEqualToString:@"settings"]) {
9504 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9505 } else if ([arg2 isEqualToString:@"files"]) {
9506 if (Package *package = [database_ packageWithName:arg1]) {
9507 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9508 [(FileTable *)controller setPackage:package];
9513 if ([base isEqualToString:@"sections"]) {
9514 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9515 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9516 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9520 [controller setDelegate:self];
9524 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9525 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9528 [tabbar_ setUnselectedViewController:page];
9533 - (void) applicationOpenURL:(NSURL *)url {
9534 [super applicationOpenURL:url];
9539 [self openCydiaURL:url forExternal:YES];
9542 - (void) applicationWillResignActive:(UIApplication *)application {
9543 // Stop refreshing if you get a phone call or lock the device.
9544 if ([tabbar_ updating])
9545 [tabbar_ cancelUpdate];
9547 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9548 [super applicationWillResignActive:application];
9551 - (void) saveState {
9552 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9553 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9554 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9560 - (void) applicationWillTerminate:(UIApplication *)application {
9564 - (void) setConfigurationData:(NSString *)data {
9565 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9567 if (!conffile_r(data)) {
9568 lprintf("E:invalid conffile\n");
9572 NSString *ofile = conffile_r[1];
9573 //NSString *nfile = conffile_r[2];
9575 UIAlertView *alert = [[[UIAlertView alloc]
9576 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9577 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9579 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9581 UCLocalize("ACCEPT_NEW_COPY"),
9582 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9586 [alert setContext:@"conffile"];
9587 [alert setNumberOfRows:2];
9591 - (void) addStashController {
9593 stash_ = [[[StashController alloc] init] autorelease];
9594 [window_ addSubview:[stash_ view]];
9597 - (void) removeStashController {
9598 [[stash_ view] removeFromSuperview];
9600 [self unlockSuspend];
9604 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9605 UpdateExternalStatus(1);
9606 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9607 UpdateExternalStatus(0);
9609 [self removeStashController];
9611 pid_t pid(ExecFork());
9613 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9614 perror("launchctl stop");
9620 - (void) setupViewControllers {
9621 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9623 NSMutableArray *items;
9624 if (kCFCoreFoundationVersionNumber < 800) {
9625 items = [NSMutableArray arrayWithObjects:
9626 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9627 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9628 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9629 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease],
9630 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9633 items = [NSMutableArray arrayWithObjects:
9634 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home7.png"] selectedImage:[UIImage applicationImageNamed:@"home7s.png"]] autorelease],
9635 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install7.png"] selectedImage:[UIImage applicationImageNamed:@"install7s.png"]] autorelease],
9636 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes7.png"] selectedImage:[UIImage applicationImageNamed:@"changes7s.png"]] autorelease],
9637 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage7.png"] selectedImage:[UIImage applicationImageNamed:@"manage7s.png"]] autorelease],
9638 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search7.png"] selectedImage:[UIImage applicationImageNamed:@"search7s.png"]] autorelease],
9642 NSMutableArray *controllers([NSMutableArray array]);
9643 for (UITabBarItem *item in items) {
9644 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9645 [controller setTabBarItem:item];
9646 [controllers addObject:controller];
9648 [tabbar_ setViewControllers:controllers];
9650 [tabbar_ setUpdateDelegate:self];
9653 - (void) _sendMemoryWarningNotification {
9654 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9655 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9657 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9660 - (void) _sendMemoryWarningNotifications {
9662 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9668 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9670 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9673 - (void) applicationDidFinishLaunching:(id)unused {
9674 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9677 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9678 [self setApplicationSupportsShakeToEdit:NO];
9680 @synchronized (HostConfig_) {
9681 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9684 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9685 initWithMemoryCapacity:524288
9686 diskCapacity:10485760
9687 diskPath:[NSString stringWithFormat:@"%@/SDURLCache", Cache_]
9690 [CydiaWebViewController _initialize];
9692 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9694 // this would disallow http{,s} URLs from accessing this data
9695 //[WebView registerURLSchemeAsLocal:@"cydia"];
9697 Font12_ = [UIFont systemFontOfSize:12];
9698 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9699 Font14_ = [UIFont systemFontOfSize:14];
9700 Font18_ = [UIFont systemFontOfSize:18];
9701 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9702 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9704 essential_ = [NSMutableArray arrayWithCapacity:4];
9705 broken_ = [NSMutableArray arrayWithCapacity:4];
9707 // XXX: I really need this thing... like, seriously... I'm sorry
9708 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9710 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9711 [window_ orderFront:self];
9712 [window_ makeKey:self];
9713 [window_ setHidden:NO];
9716 [self addStashController];
9717 // XXX: this would be much cleaner as a yieldToSelector:
9718 // that way the removeStashController could happen right here inline
9719 // we also could no longer require the useless stash_ field anymore
9720 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9725 int error(stat("/", &root));
9726 _assert(error != -1);
9728 #define Stash_(path) do { \
9729 struct stat folder; \
9730 int error(lstat((path), &folder)); \
9731 if (error != -1 && ( \
9732 folder.st_dev == root.st_dev && \
9733 S_ISDIR(folder.st_mode) \
9734 ) || error == -1 && ( \
9735 errno == ENOENT || \
9740 Stash_("/Applications");
9741 Stash_("/Library/Ringtones");
9742 Stash_("/Library/Wallpaper");
9743 //Stash_("/usr/bin");
9744 Stash_("/usr/include");
9745 Stash_("/usr/lib/pam");
9746 Stash_("/usr/share");
9747 //Stash_("/var/lib");
9749 database_ = [Database sharedInstance];
9750 [database_ setDelegate:self];
9752 [window_ setUserInteractionEnabled:NO];
9753 [self setupViewControllers];
9755 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9756 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9757 [window_ setRootViewController:emulated_];
9759 [window_ addSubview:[emulated_ view]];
9761 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9765 - (NSArray *) defaultStartPages {
9766 NSMutableArray *standard = [NSMutableArray array];
9767 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9768 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9769 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9770 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9771 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9777 if ([emulated_ modalViewController] != nil)
9778 [emulated_ dismissModalViewControllerAnimated:YES];
9779 [window_ setUserInteractionEnabled:NO];
9781 [self reloadDataWithInvocation:nil];
9782 [self refreshIfPossible];
9785 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9786 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9787 int standardIndex = 0;
9788 NSArray *standard = [self defaultStartPages];
9795 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9796 if (valid && closed != nil) {
9797 NSTimeInterval interval([closed timeIntervalSinceNow]);
9798 // XXX: Is 30 minutes the optimal time here?
9799 if (interval <= -(30*60))
9803 if (valid && [saved count] != [standard count])
9807 for (unsigned int i = 0; i < [standard count]; i++) {
9808 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9809 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9810 // but it's good enough for now.
9811 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9818 NSArray *items = nil;
9820 [tabbar_ setSelectedIndex:savedIndex];
9823 [tabbar_ setSelectedIndex:standardIndex];
9827 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9828 NSArray *stack = [items objectAtIndex:tab];
9829 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9830 NSMutableArray *current = [NSMutableArray array];
9832 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9833 NSString *addr = [stack objectAtIndex:nav];
9834 NSURL *url = [NSURL URLWithString:addr];
9835 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9837 [current addObject:page];
9840 [navigation setViewControllers:current];
9843 // (Try to) show the startup URL.
9844 if (starturl_ != nil) {
9845 [self openCydiaURL:starturl_ forExternal:YES];
9850 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9851 if (item != nil && IsWildcat_) {
9852 [sheet showFromBarButtonItem:item animated:YES];
9854 [sheet showInView:window_];
9858 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9859 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9860 [progress setTitle:task];
9861 [progress addProgressEvent:event];
9864 - (void) addProgressEventForTask:(NSArray *)data {
9865 CydiaProgressEvent *event([data objectAtIndex:0]);
9866 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9867 [self addProgressEvent:event forTask:task];
9870 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9871 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9877 id Alloc_(id self, SEL selector) {
9878 id object = alloc_(self, selector);
9879 lprintf("[%s]A-%p\n", self->isa->name, object);
9884 id Dealloc_(id self, SEL selector) {
9885 id object = dealloc_(self, selector);
9886 lprintf("[%s]D-%p\n", self->isa->name, object);
9890 static NSSet *MobilizedFiles_;
9892 static NSURL *MobilizeURL(NSURL *url) {
9893 NSString *path([url path]);
9894 if ([path hasPrefix:@"/var/root/"]) {
9895 NSString *file([path substringFromIndex:10]);
9896 if ([MobilizedFiles_ containsObject:file])
9897 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9903 Class $CFXPreferencesPropertyListSource;
9904 @class CFXPreferencesPropertyListSource;
9906 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9907 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9908 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9910 url = MobilizeURL(url);
9912 value = _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd);
9913 //NSLog(@"CFX %@ %s", [url absoluteString], value ? "YES" : "NO");
9922 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9923 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9924 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9926 url = MobilizeURL(url);
9928 value = _CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd);
9929 //NSLog(@"CFX %@ %@", [url absoluteString], value);
9938 Class $NSURLConnection;
9940 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9941 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
9943 NSURL *url([copy URL]);
9945 NSString *host([url host]);
9946 NSString *scheme([[url scheme] lowercaseString]);
9948 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9950 @synchronized (HostConfig_) {
9951 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9952 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9953 [copy setHTTPShouldUsePipelining:YES];
9955 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9956 if ([control isEqualToString:@"max-age=0"])
9957 if ([CachedURLs_ containsObject:url]) {
9959 NSLog(@"~~~: %@", url);
9962 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9964 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9965 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9966 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9970 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9976 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
9977 CGSize size([[UIScreen mainScreen] bounds].size);
9978 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
9979 if ([$WAKWindow hasLandscapeOrientation])
9980 std::swap(size.width, size.height);*/
9984 Class $NSUserDefaults;
9986 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
9987 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
9988 return [NSString stringWithFormat:@"%@/LocalStorage", Cache_];
9989 return _NSUserDefaults$objectForKey$(self, _cmd, key);
9992 int main(int argc, char *argv[]) {
9993 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9997 UpdateExternalStatus(0);
9999 UIScreen *screen([UIScreen mainScreen]);
10000 if ([screen respondsToSelector:@selector(scale)])
10001 ScreenScale_ = [screen scale];
10005 UIDevice *device([UIDevice currentDevice]);
10006 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10007 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10008 if (idiom == UIUserInterfaceIdiomPad)
10012 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10014 Pcre pattern("^([0-9]+\\.[0-9]+)");
10016 if (pattern([device systemVersion]))
10017 Firmware_ = pattern[1];
10018 if (pattern(Cydia_))
10019 Major_ = pattern[1];
10021 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10023 HostConfig_ = [[[NSObject alloc] init] autorelease];
10024 @synchronized (HostConfig_) {
10025 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10026 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10027 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10028 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10029 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10032 NSString *ui(@"ui/ios");
10034 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10035 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10036 UI_ = CydiaURL(ui);
10038 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10040 MobilizedFiles_ = [NSMutableSet setWithObjects:
10041 @"Library/Preferences/.GlobalPreferences.plist",
10042 @"Library/Preferences/com.apple.Accessibility.plist",
10043 @"Library/Preferences/com.apple.preferences.sounds.plist",
10046 /* Library Hacks {{{ */
10047 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10049 $WAKWindow = objc_getClass("WAKWindow");
10050 if ($WAKWindow != NULL)
10051 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10052 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10054 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSourceSynchronizer");
10055 if ($CFXPreferencesPropertyListSource == Nil)
10056 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10058 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10059 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10060 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10061 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10064 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10065 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10066 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10067 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10070 $NSURLConnection = objc_getClass("NSURLConnection");
10071 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10072 if (NSURLConnection$init$ != NULL) {
10073 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10074 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10077 $NSUserDefaults = objc_getClass("NSUserDefaults");
10078 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10079 if (NSUserDefaults$objectForKey$ != NULL) {
10080 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10081 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10084 /* Set Locale {{{ */
10085 Locale_ = CFLocaleCopyCurrent();
10086 Languages_ = [NSLocale preferredLanguages];
10088 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10089 //NSLog(@"%@", [Languages_ description]);
10092 if (Locale_ != NULL)
10093 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10094 else if (Languages_ != nil && [Languages_ count] != 0)
10095 lang = [[Languages_ objectAtIndex:0] UTF8String];
10097 // XXX: consider just setting to C and then falling through?
10100 if (lang != NULL) {
10101 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10102 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10105 NSLog(@"Setting Language: %s", lang);
10107 if (lang != NULL) {
10108 setenv("LANG", lang, true);
10109 std::setlocale(LC_ALL, lang);
10112 /* Index Collation {{{ */
10113 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) {
10114 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10115 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10116 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10117 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10118 _H<UILocalizedIndexedCollation> collation([[[UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10120 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10122 CollationThumbs_ = [collation sectionIndexTitles];
10123 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10124 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10126 CollationTitles_ = [collation sectionTitles];
10127 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10129 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10130 if (&transform != NULL && transform != nil) {
10131 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10132 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10133 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10134 UErrorCode code(U_ZERO_ERROR);
10135 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10136 if (!U_SUCCESS(code))
10137 NSLog(@"%s", u_errorName(code));
10140 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10142 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];
10143 for (NSInteger offset(0); offset != 28; ++offset)
10144 CollationOffset_.push_back(offset);
10146 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];
10147 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];
10151 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10153 /* Parse Arguments {{{ */
10154 bool substrate(false);
10160 for (int argi(1); argi != argc; ++argi)
10161 if (strcmp(argv[argi], "--") == 0) {
10163 argv[argi] = argv[0];
10169 for (int argi(1); argi != arge; ++argi)
10170 if (strcmp(args[argi], "--substrate") == 0)
10173 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10177 App_ = [[NSBundle mainBundle] bundlePath];
10183 if (access("/var/mobile/Library/Keyboard/UserDictionary.sqlite", F_OK) == 0)
10184 system("mkdir -p /var/root/Library/Keyboard; cp -af /var/mobile/Library/Keyboard/UserDictionary.sqlite /var/root/Library/Keyboard/");
10186 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/root"] retain];
10188 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10189 alloc_ = alloc->method_imp;
10190 alloc->method_imp = (IMP) &Alloc_;*/
10192 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10193 dealloc_ = dealloc->method_imp;
10194 dealloc->method_imp = (IMP) &Dealloc_;*/
10196 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10197 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10199 /* System Information {{{ */
10203 size = sizeof(maxproc);
10204 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10205 perror("sysctlbyname(\"kern.maxproc\", ?)");
10206 else if (maxproc < 64) {
10208 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10209 perror("sysctlbyname(\"kern.maxproc\", #)");
10212 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10213 char *osversion = new char[size];
10214 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10215 perror("sysctlbyname(\"kern.osversion\", ?)");
10217 System_ = [NSString stringWithUTF8String:osversion];
10219 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10220 char *machine = new char[size];
10221 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10222 perror("sysctlbyname(\"hw.machine\", ?)");
10224 Machine_ = machine;
10226 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10227 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10228 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10230 UniqueID_ = UniqueIdentifier(device);
10232 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10233 Product_ = [info objectForKey:@"SafariProductVersion"];
10234 Safari_ = [info objectForKey:@"CFBundleVersion"];
10237 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10239 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10240 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10241 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10242 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10243 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10244 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10246 UserAgent_ = agent;
10248 /* Load Database {{{ */
10250 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10252 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10254 if (Metadata_ == NULL)
10255 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10257 Settings_ = [Metadata_ objectForKey:@"Settings"];
10259 Packages_ = [Metadata_ objectForKey:@"Packages"];
10261 Values_ = [Metadata_ objectForKey:@"Values"];
10262 Sections_ = [Metadata_ objectForKey:@"Sections"];
10263 Sources_ = [Metadata_ objectForKey:@"Sources"];
10265 Token_ = [Metadata_ objectForKey:@"Token"];
10267 Version_ = [Metadata_ objectForKey:@"Version"];
10270 if (Values_ == nil) {
10271 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10272 [Metadata_ setObject:Values_ forKey:@"Values"];
10275 if (Sections_ == nil) {
10276 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10277 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10280 if (Sources_ == nil) {
10281 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10282 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10285 if (Version_ == nil) {
10286 Version_ = [NSNumber numberWithUnsignedInt:0];
10287 [Metadata_ setObject:Version_ forKey:@"Version"];
10290 if ([Version_ unsignedIntValue] == 0) {
10291 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10292 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10293 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10294 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10296 Version_ = [NSNumber numberWithUnsignedInt:1];
10297 [Metadata_ setObject:Version_ forKey:@"Version"];
10299 [Metadata_ removeObjectForKey:@"LastUpdate"];
10304 _H<NSMutableArray> broken([NSMutableArray array]);
10305 for (NSString *key in (id) Sources_)
10306 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound)
10307 [broken addObject:key];
10308 if ([broken count] != 0) {
10309 for (NSString *key in (id) broken)
10310 [Sources_ removeObjectForKey:key];
10315 CydiaWriteSources();
10318 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10321 if (Packages_ != nil) {
10323 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10327 [Metadata_ removeObjectForKey:@"Packages"];
10333 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10335 #define MobileSubstrate_(name) \
10336 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10337 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10338 if (handle == NULL) \
10339 NSLog(@"%s", dlerror()); \
10342 MobileSubstrate_(Activator)
10343 MobileSubstrate_(libstatusbar)
10344 MobileSubstrate_(SimulatedKeyEvents)
10345 MobileSubstrate_(WinterBoard)
10347 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10348 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10350 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10352 if (access("/User", F_OK) != 0 || version != 6) {
10354 system("/usr/libexec/cydia/firmware.sh");
10358 _assert([[NSFileManager defaultManager]
10359 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10360 withIntermediateDirectories:YES
10365 if (access("/tmp/cydia.chk", F_OK) == 0) {
10366 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10367 _assert(errno == ENOENT);
10368 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10369 _assert(errno == ENOENT);
10372 /* APT Initialization {{{ */
10373 _assert(pkgInitConfig(*_config));
10374 _assert(pkgInitSystem(*_config, _system));
10377 _config->Set("APT::Acquire::Translation", lang);
10379 // XXX: this timeout might be important :(
10380 //_config->Set("Acquire::http::Timeout", 15);
10382 _config->Set("Acquire::http::MaxParallel", 3);
10384 /* Color Choices {{{ */
10385 space_ = CGColorSpaceCreateDeviceRGB();
10387 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10388 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10389 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10390 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10391 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10392 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10393 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10394 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10395 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10396 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10398 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10399 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10401 /* UIKit Configuration {{{ */
10402 // XXX: I have a feeling this was important
10403 //UIKeyboardDisableAutomaticAppearance();
10406 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10408 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10409 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10410 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10412 PulseInterval_ = fast ? 50000 : 500000;
10414 Colon_ = UCLocalize("COLON_DELIMITED");
10415 Elision_ = UCLocalize("ELISION");
10416 Error_ = UCLocalize("ERROR");
10417 Warning_ = UCLocalize("WARNING");
10420 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10422 CGColorSpaceRelease(space_);
10423 CFRelease(Locale_);