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];
3156 for (NSString *term in query) {
3157 range = [string rangeOfString:term options:MatchCompareOptions_];
3158 if (range.location != NSNotFound)
3159 rank_ -= 6 * 1000000 / length;
3164 length = [string length];
3166 for (NSString *term in query) {
3167 range = [string rangeOfString:term options:MatchCompareOptions_];
3168 if (range.location != NSNotFound)
3169 rank_ -= 6 * 1000000 / length;
3173 string = [self shortDescription];
3174 length = [string length];
3175 NSUInteger stop(std::min<NSUInteger>(length, 200));
3177 for (NSString *term in query) {
3178 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3179 if (range.location != NSNotFound)
3180 rank_ -= 2 * 100000;
3186 - (NSArray *) tags {
3190 - (BOOL) hasTag:(NSString *)tag {
3191 return tags_ == nil ? NO : [tags_ containsObject:tag];
3194 - (NSString *) primaryPurpose {
3195 for (NSString *tag in (NSArray *) tags_)
3196 if ([tag hasPrefix:@"purpose::"])
3197 return [tag substringFromIndex:9];
3201 - (NSArray *) purposes {
3202 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3203 for (NSString *tag in (NSArray *) tags_)
3204 if ([tag hasPrefix:@"purpose::"])
3205 [purposes addObject:[tag substringFromIndex:9]];
3206 return [purposes count] == 0 ? nil : purposes;
3209 - (bool) isCommercial {
3210 return [self hasTag:@"cydia::commercial"];
3213 - (void) setIndex:(size_t)index {
3214 if (metadata_->index_ != index)
3215 metadata_->index_ = index;
3218 - (CYString &) cyname {
3219 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3222 - (uint32_t) compareBySection:(NSArray *)sections {
3223 NSString *section([self section]);
3224 for (size_t i(0), e([sections count]); i != e; ++i) {
3225 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3229 return _not(uint32_t);
3233 @synchronized (database_) {
3234 pkgProblemResolver *resolver = [database_ resolver];
3235 resolver->Clear(iterator_);
3237 pkgCacheFile &cache([database_ cache]);
3238 cache->SetReInstall(iterator_, false);
3239 cache->MarkKeep(iterator_, false);
3243 @synchronized (database_) {
3244 pkgProblemResolver *resolver = [database_ resolver];
3245 resolver->Clear(iterator_);
3246 resolver->Protect(iterator_);
3248 pkgCacheFile &cache([database_ cache]);
3249 cache->SetReInstall(iterator_, false);
3250 cache->MarkInstall(iterator_, false);
3252 pkgDepCache::StateCache &state((*cache)[iterator_]);
3253 if (!state.Install())
3254 cache->SetReInstall(iterator_, true);
3258 @synchronized (database_) {
3259 pkgProblemResolver *resolver = [database_ resolver];
3260 resolver->Clear(iterator_);
3261 resolver->Remove(iterator_);
3262 resolver->Protect(iterator_);
3264 pkgCacheFile &cache([database_ cache]);
3265 cache->SetReInstall(iterator_, false);
3266 cache->MarkDelete(iterator_, true);
3271 /* Section Class {{{ */
3272 @interface Section : NSObject {
3276 _H<NSString> localized_;
3279 - (NSComparisonResult) compareByLocalized:(Section *)section;
3280 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3281 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3282 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3284 - (NSString *) name;
3285 - (void) setName:(NSString *)name;
3291 - (void) addToCount;
3293 - (void) setCount:(size_t)count;
3294 - (NSString *) localized;
3298 @implementation Section
3300 - (NSComparisonResult) compareByLocalized:(Section *)section {
3301 NSString *lhs(localized_);
3302 NSString *rhs([section localized]);
3304 /*if ([lhs length] != 0 && [rhs length] != 0) {
3305 unichar lhc = [lhs characterAtIndex:0];
3306 unichar rhc = [rhs characterAtIndex:0];
3308 if (isalpha(lhc) && !isalpha(rhc))
3309 return NSOrderedAscending;
3310 else if (!isalpha(lhc) && isalpha(rhc))
3311 return NSOrderedDescending;
3314 return [lhs compare:rhs options:LaxCompareOptions_];
3317 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3318 if ((self = [self initWithName:name localize:NO]) != nil) {
3319 if (localized != nil)
3320 localized_ = localized;
3324 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3325 return [self initWithName:name row:0 localize:localize];
3328 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3329 if ((self = [super init]) != nil) {
3333 localized_ = LocalizeSection(name_);
3337 - (NSString *) name {
3341 - (void) setName:(NSString *)name {
3357 - (void) addToCount {
3361 - (void) setCount:(size_t)count {
3365 - (NSString *) localized {
3372 class CydiaLogCleaner :
3373 public pkgArchiveCleaner
3376 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3381 /* Database Implementation {{{ */
3382 @implementation Database
3384 + (Database *) sharedInstance {
3385 static _H<Database> instance;
3386 if (instance == nil)
3387 instance = [[[Database alloc] init] autorelease];
3395 - (void) releasePackages {
3396 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3397 CFArrayRemoveAllValues(packages_);
3401 // XXX: actually implement this thing
3403 [self releasePackages];
3404 apr_pool_destroy(pool_);
3405 NSRecycleZone(zone_);
3409 - (void) _readCydia:(NSNumber *)fd {
3410 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3411 std::istream is(&ib);
3414 static Pcre finish_r("^finish:([^:]*)$");
3416 while (std::getline(is, line)) {
3417 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3419 const char *data(line.c_str());
3420 size_t size = line.size();
3421 lprintf("C:%s\n", data);
3423 if (finish_r(data, size)) {
3424 NSString *finish = finish_r[1];
3425 int index = [Finishes_ indexOfObject:finish];
3426 if (index != INT_MAX && index > Finish_)
3436 - (void) _readStatus:(NSNumber *)fd {
3437 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3438 std::istream is(&ib);
3441 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3442 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3444 while (std::getline(is, line)) {
3445 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3447 const char *data(line.c_str());
3448 size_t size(line.size());
3449 lprintf("S:%s\n", data);
3451 if (conffile_r(data, size)) {
3452 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3453 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3454 } else if (strncmp(data, "status: ", 8) == 0) {
3455 // status: <package>: {unpacked,half-configured,installed}
3456 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3457 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3458 } else if (strncmp(data, "processing: ", 12) == 0) {
3459 // processing: configure: config-test
3460 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3461 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3462 } else if (pmstatus_r(data, size)) {
3463 std::string type([pmstatus_r[1] UTF8String]);
3465 NSString *package = pmstatus_r[2];
3466 if ([package isEqualToString:@"dpkg-exec"])
3469 float percent([pmstatus_r[3] floatValue]);
3470 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3472 NSString *string = pmstatus_r[4];
3474 if (type == "pmerror") {
3475 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3476 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3477 } else if (type == "pmstatus") {
3478 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3479 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3480 } else if (type == "pmconffile")
3481 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3483 lprintf("E:unknown pmstatus\n");
3485 lprintf("E:unknown status\n");
3493 - (void) _readOutput:(NSNumber *)fd {
3494 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3495 std::istream is(&ib);
3498 while (std::getline(is, line)) {
3499 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3501 lprintf("O:%s\n", line.c_str());
3503 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3504 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3516 - (Package *) packageWithName:(NSString *)name {
3519 @synchronized (self) {
3520 if (static_cast<pkgDepCache *>(cache_) == NULL)
3522 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3523 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3527 if ((self = [super init]) != nil) {
3534 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3535 apr_pool_create(&pool_, NULL);
3537 size_t capacity(MetaFile_->active_);
3543 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3544 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3548 _assert(pipe(fds) != -1);
3551 _config->Set("APT::Keep-Fds::", cydiafd_);
3552 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3555 detachNewThreadSelector:@selector(_readCydia:)
3557 withObject:[NSNumber numberWithInt:fds[0]]
3560 _assert(pipe(fds) != -1);
3564 detachNewThreadSelector:@selector(_readStatus:)
3566 withObject:[NSNumber numberWithInt:fds[0]]
3569 _assert(pipe(fds) != -1);
3570 _assert(dup2(fds[0], 0) != -1);
3571 _assert(close(fds[0]) != -1);
3573 input_ = fdopen(fds[1], "a");
3575 _assert(pipe(fds) != -1);
3576 _assert(dup2(fds[1], 1) != -1);
3577 _assert(close(fds[1]) != -1);
3580 detachNewThreadSelector:@selector(_readOutput:)
3582 withObject:[NSNumber numberWithInt:fds[0]]
3587 - (pkgCacheFile &) cache {
3591 - (pkgDepCache::Policy *) policy {
3595 - (pkgRecords *) records {
3599 - (pkgProblemResolver *) resolver {
3603 - (pkgAcquire &) fetcher {
3607 - (pkgSourceList &) list {
3611 - (NSArray *) packages {
3612 return (NSArray *) packages_;
3615 - (NSArray *) sources {
3619 - (Source *) sourceWithKey:(NSString *)key {
3620 for (Source *source in [self sources]) {
3621 if ([[source key] isEqualToString:key])
3626 - (bool) popErrorWithTitle:(NSString *)title {
3629 while (!_error->empty()) {
3631 bool warning(!_error->PopMessage(error));
3636 size_t size(error.size());
3637 if (size == 0 || error[size - 1] != '\n')
3639 error.resize(size - 1);
3642 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3644 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3645 if (warning && no_pubkey(error.c_str()))
3648 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3654 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3655 return [self popErrorWithTitle:title] || !success;
3658 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3659 @synchronized (self) {
3662 [self releasePackages];
3665 [sourceList_ removeAllObjects];
3685 apr_pool_clear(pool_);
3687 NSRecycleZone(zone_);
3688 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3690 int chk(creat("/tmp/cydia.chk", 0644));
3694 if (invocation != nil)
3695 [invocation invoke];
3697 NSString *title(UCLocalize("DATABASE"));
3699 list_ = new pkgSourceList();
3700 _profile(reloadDataWithInvocation$ReadMainList)
3701 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3705 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3706 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3707 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3708 [sourceList_ addObject:object];
3713 OpProgress progress;
3716 _profile(reloadDataWithInvocation$pkgCacheFile)
3717 opened = cache_.Open(progress, true);
3720 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3721 while (!_error->empty()) {
3723 bool warning(!_error->PopMessage(error));
3725 lprintf("cache_.Open():[%s]\n", error.c_str());
3727 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3731 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3732 repair = @selector(configure);
3733 //else if (error == "The package lists or status file could not be parsed or opened.")
3734 // repair = @selector(update);
3735 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3736 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3737 // else if (error == "Malformed Status line")
3738 // else if (error == "The list of sources could not be read.")
3740 if (repair != NULL) {
3742 [delegate_ repairWithSelector:repair];
3751 unlink("/tmp/cydia.chk");
3753 now_ = [[NSDate date] timeIntervalSince1970];
3755 policy_ = new pkgDepCache::Policy();
3756 records_ = new pkgRecords(cache_);
3757 resolver_ = new pkgProblemResolver(cache_);
3758 fetcher_ = new pkgAcquire(&status_);
3761 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3762 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3766 _profile(reloadDataWithInvocation$pkgApplyStatus)
3767 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3771 if (cache_->BrokenCount() != 0) {
3772 _profile(pkgApplyStatus$pkgFixBroken)
3773 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3777 if (cache_->BrokenCount() != 0) {
3778 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3782 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3783 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3788 for (Source *object in (id) sourceList_) {
3789 metaIndex *source([object metaIndex]);
3790 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3791 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3792 // XXX: this could be more intelligent
3793 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3794 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3796 sourceMap_[cached->ID] = object;
3801 /*std::vector<Package *> packages;
3802 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3805 _profile(reloadDataWithInvocation$packageWithIterator)
3806 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3807 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3808 //packages.push_back(package);
3809 CFArrayAppendValue(packages_, CFRetain(package));
3813 /*if (packages.empty())
3814 packages_ = [[NSArray alloc] init];
3816 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3819 _profile(reloadDataWithInvocation$radix$8)
3820 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3823 _profile(reloadDataWithInvocation$radix$4)
3824 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3827 _profile(reloadDataWithInvocation$radix$0)
3828 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3831 _profile(reloadDataWithInvocation$insertion)
3832 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3835 /*_profile(reloadDataWithInvocation$CFQSortArray)
3836 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3839 /*_profile(reloadDataWithInvocation$stdsort)
3840 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3843 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3844 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3847 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3848 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3852 size_t count(CFArrayGetCount(packages_));
3853 MetaFile_->active_ = count;
3854 for (size_t index(0); index != count; ++index)
3855 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3860 @synchronized (self) {
3862 resolver_ = new pkgProblemResolver(cache_);
3864 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3865 if (!cache_[iterator].Keep())
3866 cache_->MarkKeep(iterator, false);
3867 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3868 cache_->SetReInstall(iterator, false);
3871 - (void) configure {
3872 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3874 system([dpkg UTF8String]);
3879 @synchronized (self) {
3880 // XXX: I don't remember this condition
3885 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3887 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3889 if ([self popErrorWithTitle:title])
3893 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3895 CydiaLogCleaner cleaner;
3896 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3903 fetcher_->Shutdown();
3905 pkgRecords records(cache_);
3907 lock_ = new FileFd();
3908 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3910 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3912 if ([self popErrorWithTitle:title])
3916 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3919 manager_ = (_system->CreatePM(cache_));
3920 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3927 bool substrate(RestartSubstrate_);
3928 RestartSubstrate_ = false;
3930 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3932 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3934 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3936 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3937 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3940 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3942 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3944 [self popErrorWithTitle:title];
3948 bool failed = false;
3949 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3950 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3952 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3955 std::string uri = (*item)->DescURI();
3956 std::string error = (*item)->ErrorText;
3958 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3961 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3962 [delegate_ addProgressEventOnMainThread:event forTask:title];
3965 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3973 RestartSubstrate_ = true;
3976 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3977 if ([self popErrorWithTitle:title])
3980 if (result == pkgPackageManager::Failed) {
3985 if (result != pkgPackageManager::Completed) {
3990 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3992 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3994 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3995 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3998 if (![before isEqualToArray:after])
4003 NSString *title(UCLocalize("UPGRADE"));
4004 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4010 [self updateWithStatus:status_];
4013 - (void) updateWithStatus:(CancelStatus &)status {
4014 NSString *title(UCLocalize("REFRESHING_DATA"));
4017 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4021 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4022 if ([self popErrorWithTitle:title])
4025 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4027 bool success(ListUpdate(status, list, PulseInterval_));
4028 if (status.WasCancelled())
4031 [self popErrorWithTitle:title forOperation:success];
4032 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
4036 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4039 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4040 delegate_ = delegate;
4043 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4044 progress_ = delegate;
4045 status_.setDelegate(delegate);
4048 - (NSObject<ProgressDelegate> *) progressDelegate {
4052 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4053 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4054 return i == sourceMap_.end() ? nil : i->second;
4057 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4058 for (Source *source in (id) sourceList_)
4059 [source setFetch:fetch forURI:uri];
4062 - (void) resetFetch {
4063 for (Source *source in (id) sourceList_)
4064 [source resetFetch];
4067 - (NSString *) mappedSectionForPointer:(const char *)section {
4068 _H<NSString> *mapped;
4070 _profile(Database$mappedSectionForPointer$Cache)
4071 mapped = §ions_[section];
4074 if (*mapped == NULL) {
4075 size_t length(strlen(section));
4076 char spaced[length + 1];
4078 _profile(Database$mappedSectionForPointer$Replace)
4079 for (size_t index(0); index != length; ++index)
4080 spaced[index] = section[index] == '_' ? ' ' : section[index];
4081 spaced[length] = '\0';
4086 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4087 string = [NSString stringWithUTF8String:spaced];
4090 _profile(Database$mappedSectionForPointer$Map)
4091 string = [SectionMap_ objectForKey:string] ?: string;
4101 static _H<NSMutableSet> Diversions_;
4103 @interface Diversion : NSObject {
4106 _H<NSString> format_;
4111 @implementation Diversion
4113 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4114 if ((self = [super init]) != nil) {
4115 pattern_ = [from UTF8String];
4121 - (NSString *) divert:(NSString *)url {
4122 return !pattern_(url) ? nil : pattern_->*format_;
4125 + (NSURL *) divertURL:(NSURL *)url {
4127 NSString *href([url absoluteString]);
4129 for (Diversion *diversion in (id) Diversions_)
4130 if (NSString *diverted = [diversion divert:href]) {
4132 NSLog(@"div: %@", diverted);
4134 url = [NSURL URLWithString:diverted];
4141 - (NSString *) key {
4145 - (NSUInteger) hash {
4149 - (BOOL) isEqual:(Diversion *)object {
4150 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4155 @interface CydiaObject : NSObject {
4156 _H<CyteWebViewController> indirect_;
4157 _transient id delegate_;
4160 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4166 @interface CydiaWebViewController : CyteWebViewController {
4167 _H<CydiaObject> cydia_;
4170 + (void) addDiversion:(Diversion *)diversion;
4171 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4172 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4173 - (void) setDelegate:(id)delegate;
4177 /* Web Scripting {{{ */
4178 @implementation CydiaObject
4180 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4181 if ((self = [super init]) != nil) {
4182 indirect_ = (CyteWebViewController *) indirect;
4186 - (void) setDelegate:(id)delegate {
4187 delegate_ = delegate;
4190 + (NSArray *) _attributeKeys {
4191 return [NSArray arrayWithObjects:
4194 @"coreFoundationVersionNumber",
4211 - (NSArray *) attributeKeys {
4212 return [[self class] _attributeKeys];
4215 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4216 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4219 - (NSString *) version {
4223 - (NSString *) build {
4227 - (NSString *) coreFoundationVersionNumber {
4228 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4231 - (NSString *) device {
4232 return UniqueIdentifier();
4235 - (NSString *) firmware {
4236 return [[UIDevice currentDevice] systemVersion];
4239 - (NSString *) hostname {
4240 return [[UIDevice currentDevice] name];
4243 - (NSString *) idiom {
4244 return (id) Idiom_ ?: [NSNull null];
4247 - (NSString *) mcc {
4248 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4249 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4253 - (NSString *) mnc {
4254 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4255 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4259 - (NSString *) operator {
4260 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4261 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4265 - (NSString *) bbsnum {
4266 return (id) BBSNum_ ?: [NSNull null];
4269 - (NSString *) ecid {
4270 return (id) ChipID_ ?: [NSNull null];
4273 - (NSString *) serial {
4274 return SerialNumber_;
4277 - (NSString *) role {
4278 return (id) [NSNull null];
4281 - (NSString *) model {
4282 return [NSString stringWithUTF8String:Machine_];
4285 - (NSString *) token {
4286 return (id) Token_ ?: [NSNull null];
4289 + (NSString *) webScriptNameForSelector:(SEL)selector {
4291 else if (selector == @selector(addBridgedHost:))
4292 return @"addBridgedHost";
4293 else if (selector == @selector(addInsecureHost:))
4294 return @"addInsecureHost";
4295 else if (selector == @selector(addInternalRedirect::))
4296 return @"addInternalRedirect";
4297 else if (selector == @selector(addPipelinedHost:scheme:))
4298 return @"addPipelinedHost";
4299 else if (selector == @selector(addSource:::))
4300 return @"addSource";
4301 else if (selector == @selector(addTokenHost:))
4302 return @"addTokenHost";
4303 else if (selector == @selector(addTrivialSource:))
4304 return @"addTrivialSource";
4305 else if (selector == @selector(close))
4307 else if (selector == @selector(du:))
4309 else if (selector == @selector(stringWithFormat:arguments:))
4311 else if (selector == @selector(getAllSources))
4312 return @"getAllSources";
4313 else if (selector == @selector(getApplicationInfo:value:))
4314 return @"getApplicationInfoValue";
4315 else if (selector == @selector(getKernelNumber:))
4316 return @"getKernelNumber";
4317 else if (selector == @selector(getKernelString:))
4318 return @"getKernelString";
4319 else if (selector == @selector(getInstalledPackages))
4320 return @"getInstalledPackages";
4321 else if (selector == @selector(getIORegistryEntry::))
4322 return @"getIORegistryEntry";
4323 else if (selector == @selector(getLocaleIdentifier))
4324 return @"getLocaleIdentifier";
4325 else if (selector == @selector(getPreferredLanguages))
4326 return @"getPreferredLanguages";
4327 else if (selector == @selector(getPackageById:))
4328 return @"getPackageById";
4329 else if (selector == @selector(getMetadataKeys))
4330 return @"getMetadataKeys";
4331 else if (selector == @selector(getMetadataValue:))
4332 return @"getMetadataValue";
4333 else if (selector == @selector(getSessionValue:))
4334 return @"getSessionValue";
4335 else if (selector == @selector(installPackages:))
4336 return @"installPackages";
4337 else if (selector == @selector(isReachable:))
4338 return @"isReachable";
4339 else if (selector == @selector(localizedStringForKey:value:table:))
4341 else if (selector == @selector(popViewController:))
4342 return @"popViewController";
4343 else if (selector == @selector(refreshSources))
4344 return @"refreshSources";
4345 else if (selector == @selector(registerFrame:))
4346 return @"registerFrame";
4347 else if (selector == @selector(removeButton))
4348 return @"removeButton";
4349 else if (selector == @selector(saveConfig))
4350 return @"saveConfig";
4351 else if (selector == @selector(setMetadataValue::))
4352 return @"setMetadataValue";
4353 else if (selector == @selector(setSessionValue::))
4354 return @"setSessionValue";
4355 else if (selector == @selector(substitutePackageNames:))
4356 return @"substitutePackageNames";
4357 else if (selector == @selector(scrollToBottom:))
4358 return @"scrollToBottom";
4359 else if (selector == @selector(setAllowsNavigationAction:))
4360 return @"setAllowsNavigationAction";
4361 else if (selector == @selector(setBadgeValue:))
4362 return @"setBadgeValue";
4363 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4364 return @"setButtonImage";
4365 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4366 return @"setButtonTitle";
4367 else if (selector == @selector(setHidesBackButton:))
4368 return @"setHidesBackButton";
4369 else if (selector == @selector(setHidesNavigationBar:))
4370 return @"setHidesNavigationBar";
4371 else if (selector == @selector(setNavigationBarStyle:))
4372 return @"setNavigationBarStyle";
4373 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4374 return @"setNavigationBarTintColor";
4375 else if (selector == @selector(setPasteboardString:))
4376 return @"setPasteboardString";
4377 else if (selector == @selector(setPasteboardURL:))
4378 return @"setPasteboardURL";
4379 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4380 return @"setScrollAlwaysBounceVertical";
4381 else if (selector == @selector(setScrollIndicatorStyle:))
4382 return @"setScrollIndicatorStyle";
4383 else if (selector == @selector(setToken:))
4385 else if (selector == @selector(setViewportWidth:))
4386 return @"setViewportWidth";
4387 else if (selector == @selector(statfs:))
4389 else if (selector == @selector(supports:))
4391 else if (selector == @selector(unload))
4397 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4398 return [self webScriptNameForSelector:selector] == nil;
4401 - (BOOL) supports:(NSString *)feature {
4402 return [feature isEqualToString:@"window.open"];
4406 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4409 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4410 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4413 - (void) setScrollIndicatorStyle:(NSString *)style {
4414 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4417 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4418 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4421 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4423 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4424 return (id) [NSNull null];
4425 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4427 return (id) [NSNull null];
4428 return [info objectForKey:key];
4431 - (NSNumber *) getKernelNumber:(NSString *)name {
4432 const char *string([name UTF8String]);
4435 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4436 return (id) [NSNull null];
4438 if (size != sizeof(int))
4439 return (id) [NSNull null];
4442 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4443 return (id) [NSNull null];
4445 return [NSNumber numberWithInt:value];
4448 - (NSString *) getKernelString:(NSString *)name {
4449 const char *string([name UTF8String]);
4452 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4453 return (id) [NSNull null];
4455 char value[size + 1];
4456 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4457 return (id) [NSNull null];
4459 // XXX: just in case you request something ludicrous
4462 return [NSString stringWithCString:value];
4465 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4466 NSObject *value(CYIOGetValue([path UTF8String], entry));
4469 if ([value isKindOfClass:[NSData class]])
4470 value = CYHex((NSData *) value);
4475 - (NSArray *) getMetadataKeys {
4476 @synchronized (Values_) {
4477 return [Values_ allKeys];
4480 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4481 WebFrame *frame([iframe contentFrame]);
4482 [indirect_ registerFrame:frame];
4485 - (id) getMetadataValue:(NSString *)key {
4486 @synchronized (Values_) {
4487 return [Values_ objectForKey:key];
4490 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4491 @synchronized (Values_) {
4492 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4493 [Values_ removeObjectForKey:key];
4495 [Values_ setObject:value forKey:key];
4497 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4500 - (id) getSessionValue:(NSString *)key {
4501 @synchronized (SessionData_) {
4502 return [SessionData_ objectForKey:key];
4505 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4506 @synchronized (SessionData_) {
4507 if (value == (id) [WebUndefined undefined])
4508 [SessionData_ removeObjectForKey:key];
4510 [SessionData_ setObject:value forKey:key];
4513 - (void) addBridgedHost:(NSString *)host {
4514 @synchronized (HostConfig_) {
4515 [BridgedHosts_ addObject:host];
4518 - (void) addInsecureHost:(NSString *)host {
4519 @synchronized (HostConfig_) {
4520 [InsecureHosts_ addObject:host];
4523 - (void) addTokenHost:(NSString *)host {
4524 @synchronized (HostConfig_) {
4525 [TokenHosts_ addObject:host];
4528 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4529 @synchronized (HostConfig_) {
4530 if (scheme != (id) [WebUndefined undefined])
4531 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4533 [PipelinedHosts_ addObject:host];
4536 - (void) popViewController:(NSNumber *)value {
4537 if (value == (id) [WebUndefined undefined])
4538 value = [NSNumber numberWithBool:YES];
4539 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4542 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4543 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4545 for (NSString *section in sections)
4546 [array addObject:section];
4548 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4551 distribution, @"Distribution",
4553 nil] waitUntilDone:NO];
4556 - (void) addTrivialSource:(NSString *)href {
4557 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4560 - (void) refreshSources {
4561 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4564 - (void) saveConfig {
4565 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4568 - (NSArray *) getAllSources {
4569 return [[Database sharedInstance] sources];
4572 - (NSArray *) getInstalledPackages {
4573 Database *database([Database sharedInstance]);
4574 @synchronized (database) {
4575 NSArray *packages([database packages]);
4576 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4577 for (Package *package in packages)
4578 if (![package uninstalled])
4579 [installed addObject:package];
4583 - (Package *) getPackageById:(NSString *)id {
4584 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4588 return (Package *) [NSNull null];
4591 - (NSString *) getLocaleIdentifier {
4592 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4595 - (NSArray *) getPreferredLanguages {
4599 - (NSArray *) statfs:(NSString *)path {
4602 if (path == nil || statfs([path UTF8String], &stat) == -1)
4605 return [NSArray arrayWithObjects:
4606 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4607 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4608 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4612 - (NSNumber *) du:(NSString *)path {
4613 NSNumber *value(nil);
4616 _assert(pipe(fds) != -1);
4618 pid_t pid(ExecFork());
4620 _assert(dup2(fds[1], 1) != -1);
4621 _assert(close(fds[0]) != -1);
4622 _assert(close(fds[1]) != -1);
4623 /* XXX: this should probably not use du */
4624 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4627 _assert(close(fds[1]) != -1);
4629 if (FILE *du = fdopen(fds[0], "r")) {
4631 while (fgets(line, sizeof(line), du) != NULL) {
4632 size_t length(strlen(line));
4633 while (length != 0 && line[length - 1] == '\n')
4634 line[--length] = '\0';
4635 if (char *tab = strchr(line, '\t')) {
4637 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4643 _assert(close(fds[0]) != -1);
4650 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4653 - (NSNumber *) isReachable:(NSString *)name {
4654 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4657 - (void) installPackages:(NSArray *)packages {
4658 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4661 - (NSString *) substitutePackageNames:(NSString *)message {
4662 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4663 for (size_t i(0), e([words count]); i != e; ++i) {
4664 NSString *word([words objectAtIndex:i]);
4665 if (Package *package = [[Database sharedInstance] packageWithName:word])
4666 [words replaceObjectAtIndex:i withObject:[package name]];
4669 return [words componentsJoinedByString:@" "];
4672 - (void) removeButton {
4673 [indirect_ removeButton];
4676 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4677 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4680 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4681 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4684 - (void) setBadgeValue:(id)value {
4685 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4688 - (void) setAllowsNavigationAction:(NSString *)value {
4689 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4692 - (void) setHidesBackButton:(NSString *)value {
4693 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4696 - (void) setHidesNavigationBar:(NSString *)value {
4697 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4700 - (void) setNavigationBarStyle:(NSString *)value {
4701 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4704 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4705 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4706 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4707 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4710 - (void) setPasteboardString:(NSString *)value {
4711 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4714 - (void) setPasteboardURL:(NSString *)value {
4715 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4718 - (void) _setToken:(NSString *)token {
4722 [Metadata_ removeObjectForKey:@"Token"];
4724 [Metadata_ setObject:Token_ forKey:@"Token"];
4729 - (void) setToken:(NSString *)token {
4730 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4733 - (void) scrollToBottom:(NSNumber *)animated {
4734 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4737 - (void) setViewportWidth:(float)width {
4738 [indirect_ setViewportWidthOnMainThread:width];
4741 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4742 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4743 unsigned count([arguments count]);
4745 for (unsigned i(0); i != count; ++i)
4746 values[i] = [arguments objectAtIndex:i];
4747 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4750 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4751 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4753 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4755 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4761 @interface NSURL (CydiaSecure)
4764 @implementation NSURL (CydiaSecure)
4766 - (bool) isCydiaSecure {
4767 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4770 @synchronized (HostConfig_) {
4771 if ([InsecureHosts_ containsObject:[self host]])
4780 /* Cydia Browser Controller {{{ */
4781 @implementation CydiaWebViewController
4783 - (NSURL *) navigationURL {
4784 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4787 + (void) _initialize {
4788 [super _initialize];
4790 Diversions_ = [NSMutableSet setWithCapacity:0];
4793 + (void) addDiversion:(Diversion *)diversion {
4794 [Diversions_ addObject:diversion];
4797 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4798 [super webView:view didClearWindowObject:window forFrame:frame];
4799 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4802 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4803 WebDataSource *source([frame dataSource]);
4804 NSURLResponse *response([source response]);
4805 NSURL *url([response URL]);
4806 NSString *scheme([[url scheme] lowercaseString]);
4808 bool bridged(false);
4810 @synchronized (HostConfig_) {
4811 if ([scheme isEqualToString:@"file"])
4813 else if ([scheme isEqualToString:@"https"])
4814 if ([BridgedHosts_ containsObject:[url host]])
4819 [window setValue:cydia forKey:@"cydia"];
4822 - (void) _setupMail:(MFMailComposeViewController *)controller {
4823 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4825 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4826 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4829 - (NSURL *) URLWithURL:(NSURL *)url {
4830 return [Diversion divertURL:url];
4833 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4834 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4837 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4838 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4840 NSURL *url([copy URL]);
4841 NSString *href([url absoluteString]);
4842 NSString *host([url host]);
4844 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4845 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4846 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4847 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4850 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4851 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4853 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4857 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4858 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4859 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4860 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4865 @synchronized (HostConfig_) {
4866 bridged = [BridgedHosts_ containsObject:host];
4867 token = [TokenHosts_ containsObject:host];
4870 if ([url isCydiaSecure]) {
4872 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4873 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4875 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4876 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4883 - (void) setDelegate:(id)delegate {
4884 [super setDelegate:delegate];
4885 [cydia_ setDelegate:delegate];
4888 - (NSString *) applicationNameForUserAgent {
4893 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4894 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4900 @interface AppCacheController : CydiaWebViewController {
4905 @implementation AppCacheController
4907 - (void) didReceiveMemoryWarning {
4908 // XXX: this doesn't work
4911 - (bool) retainsNetworkActivityIndicator {
4919 @interface NSObject (CydiaScript)
4920 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4923 @implementation NSObject (CydiaScript)
4925 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4931 @implementation NSArray (CydiaScript)
4933 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4934 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4935 for (size_t i(0), e([self count]); i != e; ++i)
4936 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4942 @implementation NSDictionary (CydiaScript)
4944 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4945 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4947 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4954 /* Confirmation Controller {{{ */
4955 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4956 if (!iterator.end())
4957 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4958 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4960 pkgCache::PkgIterator package(dep.TargetPkg());
4963 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4970 @protocol ConfirmationControllerDelegate
4971 - (void) cancelAndClear:(bool)clear;
4972 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4976 @interface ConfirmationController : CydiaWebViewController {
4977 _transient Database *database_;
4979 _H<UIAlertView> essential_;
4981 _H<NSDictionary> changes_;
4982 _H<NSMutableArray> issues_;
4983 _H<NSDictionary> sizes_;
4988 - (id) initWithDatabase:(Database *)database;
4992 @implementation ConfirmationController
4996 RestartSubstrate_ = true;
4997 [delegate_ confirmWithNavigationController:[self navigationController]];
5000 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5001 NSString *context([alert context]);
5003 if ([context isEqualToString:@"remove"]) {
5004 if (button == [alert cancelButtonIndex])
5005 [self dismissModalViewControllerAnimated:YES];
5006 else if (button == [alert firstOtherButtonIndex]) {
5007 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5010 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5011 } else if ([context isEqualToString:@"unable"]) {
5012 [self dismissModalViewControllerAnimated:YES];
5013 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5015 [super alertView:alert clickedButtonAtIndex:button];
5019 - (void) _doContinue {
5020 [delegate_ cancelAndClear:NO];
5021 [self dismissModalViewControllerAnimated:YES];
5024 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5025 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5029 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5030 [super webView:view didClearWindowObject:window forFrame:frame];
5032 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5033 (id) changes_, @"changes",
5034 (id) issues_, @"issues",
5035 (id) sizes_, @"sizes",
5037 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5040 - (id) initWithDatabase:(Database *)database {
5041 if ((self = [super init]) != nil) {
5042 database_ = database;
5044 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5045 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5046 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5047 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5048 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5052 pkgCacheFile &cache([database_ cache]);
5053 NSArray *packages([database_ packages]);
5054 pkgDepCache::Policy *policy([database_ policy]);
5056 issues_ = [NSMutableArray arrayWithCapacity:4];
5058 for (Package *package in packages) {
5059 pkgCache::PkgIterator iterator([package iterator]);
5060 NSString *name([package id]);
5062 if ([package broken]) {
5063 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5065 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5067 reasons, @"reasons",
5070 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5074 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5075 pkgCache::DepIterator start;
5076 pkgCache::DepIterator end;
5077 dep.GlobOr(start, end); // ++dep
5079 if (!cache->IsImportantDep(end))
5081 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5084 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5086 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5087 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5088 clauses, @"clauses",
5092 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5094 pkgCache::PkgIterator target(start.TargetPkg());
5095 if (target->ProvidesList != 0)
5096 reason = @"missing";
5098 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5100 reason = @"installed";
5101 installed = [NSString stringWithUTF8String:ver.VerStr()];
5102 } else if (!cache[target].CandidateVerIter(cache).end())
5103 reason = @"uninstalled";
5104 else if (target->ProvidesList == 0)
5105 reason = @"uninstallable";
5107 reason = @"virtual";
5110 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5111 [NSString stringWithUTF8String:start.CompType()], @"operator",
5112 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5115 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5116 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5117 version, @"version",
5119 installed, @"installed",
5122 // yes, seriously. (wtf?)
5130 pkgDepCache::StateCache &state(cache[iterator]);
5132 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
5134 if (state.NewInstall())
5135 [installs addObject:name];
5136 // XXX: else if (state.Install())
5137 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5138 [reinstalls addObject:name];
5139 // XXX: move before previous if
5140 else if (state.Upgrade())
5141 [upgrades addObject:name];
5142 else if (state.Downgrade())
5143 [downgrades addObject:name];
5144 else if (!state.Delete())
5145 // XXX: _assert(state.Keep());
5147 else if (special_r(name))
5148 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5149 [NSNull null], @"package",
5150 [NSArray arrayWithObjects:
5151 [NSDictionary dictionaryWithObjectsAndKeys:
5152 @"Conflicts", @"relationship",
5153 [NSArray arrayWithObjects:
5154 [NSDictionary dictionaryWithObjectsAndKeys:
5156 [NSNull null], @"version",
5157 @"installed", @"reason",
5164 if ([package essential])
5166 [removes addObject:name];
5169 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5170 substrate_ |= DepSubstrate(iterator.CurrentVer());
5175 else if (Advanced_) {
5176 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5178 essential_ = [[[UIAlertView alloc]
5179 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5180 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5182 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5184 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5188 [essential_ setContext:@"remove"];
5189 [essential_ setNumberOfRows:2];
5191 essential_ = [[[UIAlertView alloc]
5192 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5193 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5195 cancelButtonTitle:UCLocalize("OKAY")
5196 otherButtonTitles:nil
5199 [essential_ setContext:@"unable"];
5202 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5203 installs, @"installs",
5204 reinstalls, @"reinstalls",
5205 upgrades, @"upgrades",
5206 downgrades, @"downgrades",
5207 removes, @"removes",
5210 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5211 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5212 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5215 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5219 - (UIBarButtonItem *) leftButton {
5220 return [[[UIBarButtonItem alloc]
5221 initWithTitle:UCLocalize("CANCEL")
5222 style:UIBarButtonItemStylePlain
5224 action:@selector(cancelButtonClicked)
5229 - (void) applyRightButton {
5230 if ([issues_ count] == 0 && ![self isLoading])
5231 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5232 initWithTitle:UCLocalize("CONFIRM")
5233 style:UIBarButtonItemStyleDone
5235 action:@selector(confirmButtonClicked)
5238 [[self navigationItem] setRightBarButtonItem:nil];
5242 - (void) cancelButtonClicked {
5243 [delegate_ cancelAndClear:YES];
5244 [self dismissModalViewControllerAnimated:YES];
5248 - (void) confirmButtonClicked {
5249 if (essential_ != nil)
5259 /* Progress Data {{{ */
5260 @interface CydiaProgressData : NSObject {
5261 _transient id delegate_;
5270 _H<NSMutableArray> events_;
5271 _H<NSString> title_;
5273 _H<NSString> status_;
5274 _H<NSString> finish_;
5279 @implementation CydiaProgressData
5281 + (NSArray *) _attributeKeys {
5282 return [NSArray arrayWithObjects:
5294 - (NSArray *) attributeKeys {
5295 return [[self class] _attributeKeys];
5298 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5299 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5303 if ((self = [super init]) != nil) {
5304 events_ = [NSMutableArray arrayWithCapacity:32];
5312 - (void) setDelegate:(id)delegate {
5313 delegate_ = delegate;
5316 - (void) setPercent:(float)value {
5320 - (NSNumber *) percent {
5321 return [NSNumber numberWithFloat:percent_];
5324 - (void) setCurrent:(float)value {
5328 - (NSNumber *) current {
5329 return [NSNumber numberWithFloat:current_];
5332 - (void) setTotal:(float)value {
5336 - (NSNumber *) total {
5337 return [NSNumber numberWithFloat:total_];
5340 - (void) setSpeed:(float)value {
5344 - (NSNumber *) speed {
5345 return [NSNumber numberWithFloat:speed_];
5348 - (NSArray *) events {
5352 - (void) removeAllEvents {
5353 [events_ removeAllObjects];
5356 - (void) addEvent:(CydiaProgressEvent *)event {
5357 [events_ addObject:event];
5360 - (void) setTitle:(NSString *)text {
5364 - (NSString *) title {
5368 - (void) setFinish:(NSString *)text {
5372 - (NSString *) finish {
5373 return (id) finish_ ?: [NSNull null];
5376 - (void) setRunning:(bool)running {
5380 - (NSNumber *) running {
5381 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5386 /* Progress Controller {{{ */
5387 @interface ProgressController : CydiaWebViewController <
5390 _transient Database *database_;
5391 _H<CydiaProgressData, 1> progress_;
5395 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5397 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5399 - (void) setTitle:(NSString *)title;
5400 - (void) setCancellable:(bool)cancellable;
5404 @implementation ProgressController
5407 [database_ setProgressDelegate:nil];
5411 - (UIBarButtonItem *) leftButton {
5412 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5413 initWithTitle:UCLocalize("CANCEL")
5414 style:UIBarButtonItemStylePlain
5416 action:@selector(cancel)
5417 ] autorelease] : nil;
5420 - (void) updateCancel {
5421 [super applyLeftButton];
5424 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5425 if ((self = [super init]) != nil) {
5426 database_ = database;
5427 delegate_ = delegate;
5429 [database_ setProgressDelegate:self];
5431 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5432 [progress_ setDelegate:self];
5434 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5436 [scroller_ setBackgroundColor:[UIColor blackColor]];
5438 [[self navigationItem] setHidesBackButton:YES];
5440 [self updateCancel];
5444 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5445 [super webView:view didClearWindowObject:window forFrame:frame];
5446 [window setValue:progress_ forKey:@"cydiaProgress"];
5449 - (void) updateProgress {
5450 [self dispatchEvent:@"CydiaProgressUpdate"];
5453 - (void) viewWillAppear:(BOOL)animated {
5454 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5455 [super viewWillAppear:animated];
5458 - (void) reloadSpringBoard {
5459 if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
5460 system("/bin/launchctl stop com.apple.backboardd");
5462 system("/usr/bin/killall backboardd SpringBoard sbreload");
5466 pid_t pid(ExecFork());
5471 pid_t pid(ExecFork());
5473 execl("/usr/bin/sbreload", "sbreload", NULL);
5483 system("/usr/bin/killall backboardd SpringBoard sbreload");
5487 UpdateExternalStatus(0);
5490 [delegate_ saveState];
5494 [delegate_ returnToCydia];
5498 [delegate_ terminateWithSuccess];
5499 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5500 [delegate_ suspendWithAnimation:YES];
5502 [delegate_ suspend];*/
5514 UIProgressHUD *hud([delegate_ addProgressHUD]);
5515 [hud setText:UCLocalize("LOADING")];
5516 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5522 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5523 SBReboot(SBSSpringBoardServerPort());
5525 reboot2(RB_AUTOBOOT);
5532 - (void) setTitle:(NSString *)title {
5533 [progress_ setTitle:title];
5534 [self updateProgress];
5537 - (UIBarButtonItem *) rightButton {
5538 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5539 initWithTitle:UCLocalize("CLOSE")
5540 style:UIBarButtonItemStylePlain
5542 action:@selector(close)
5546 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5547 UpdateExternalStatus(1);
5549 [progress_ setRunning:true];
5550 [self setTitle:title];
5551 // implicit updateProgress
5553 SHA1SumValue notifyconf; {
5555 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5558 MMap mmap(file, MMap::ReadOnly);
5560 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5561 notifyconf = sha1.Result();
5565 SHA1SumValue springlist; {
5567 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5570 MMap mmap(file, MMap::ReadOnly);
5572 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5573 springlist = sha1.Result();
5577 if (invocation != nil) {
5578 [invocation yieldToSelector:@selector(invoke)];
5579 [self setTitle:@"COMPLETE"];
5584 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5587 MMap mmap(file, MMap::ReadOnly);
5589 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5590 if (!(notifyconf == sha1.Result()))
5597 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5600 MMap mmap(file, MMap::ReadOnly);
5602 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5603 if (!(springlist == sha1.Result()))
5609 if (RestartSubstrate_)
5613 RestartSubstrate_ = false;
5616 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5617 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5618 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5619 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5620 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5623 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5625 [progress_ setRunning:false];
5626 [self updateProgress];
5628 [self applyRightButton];
5631 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5632 [progress_ addEvent:event];
5633 [self updateProgress];
5636 - (bool) isProgressCancelled {
5637 return cancel_ == 2;
5642 [self updateCancel];
5645 - (void) setCancellable:(bool)cancellable {
5646 unsigned cancel(cancel_);
5650 else if (cancel_ == 0)
5653 if (cancel != cancel_)
5654 [self updateCancel];
5657 - (void) setProgressCancellable:(NSNumber *)cancellable {
5658 [self setCancellable:[cancellable boolValue]];
5661 - (void) setProgressPercent:(NSNumber *)percent {
5662 [progress_ setPercent:[percent floatValue]];
5663 [self updateProgress];
5666 - (void) setProgressStatus:(NSDictionary *)status {
5667 if (status == nil) {
5668 [progress_ setCurrent:0];
5669 [progress_ setTotal:0];
5670 [progress_ setSpeed:0];
5672 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5674 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5675 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5676 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5679 [self updateProgress];
5685 /* Package Cell {{{ */
5686 @interface PackageCell : CyteTableViewCell <
5687 CyteTableViewCellDelegate
5691 _H<NSString> description_;
5693 _H<NSString> source_;
5695 _H<UIImage> placard_;
5699 - (PackageCell *) init;
5700 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5702 - (void) drawContentRect:(CGRect)rect;
5706 @implementation PackageCell
5708 - (PackageCell *) init {
5709 CGRect frame(CGRectMake(0, 0, 320, 74));
5710 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5711 UIView *content([self contentView]);
5712 CGRect bounds([content bounds]);
5714 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5715 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5716 [content addSubview:content_];
5718 [content_ setDelegate:self];
5719 [content_ setOpaque:YES];
5723 - (NSString *) accessibilityLabel {
5727 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5728 summarized_ = summary;
5738 [content_ setBackgroundColor:[UIColor whiteColor]];
5742 Source *source = [package source];
5744 icon_ = [package icon];
5746 if (NSString *name = [package name])
5747 name_ = [NSString stringWithString:name];
5749 if (NSString *description = [package shortDescription])
5750 description_ = [NSString stringWithString:description];
5752 commercial_ = [package isCommercial];
5754 NSString *label = nil;
5755 bool trusted = false;
5757 if (source != nil) {
5758 label = [source label];
5759 trusted = [source trusted];
5760 } else if ([[package id] isEqualToString:@"firmware"])
5761 label = UCLocalize("APPLE");
5763 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5765 NSString *from(label);
5767 NSString *section = [package simpleSection];
5768 if (section != nil && ![section isEqualToString:label]) {
5769 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5770 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5773 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5775 if (NSString *purpose = [package primaryPurpose])
5776 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5781 if (NSString *mode = [package mode]) {
5782 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5783 color = RemovingColor_;
5784 placard = @"removing";
5786 color = InstallingColor_;
5787 placard = @"installing";
5790 color = [UIColor whiteColor];
5792 if ([package installed] != nil)
5793 placard = @"installed";
5798 [content_ setBackgroundColor:color];
5801 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5804 [self setNeedsDisplay];
5805 [content_ setNeedsDisplay];
5808 - (void) drawSummaryContentRect:(CGRect)rect {
5809 bool highlighted(highlighted_);
5810 float width([self bounds].size.width);
5814 rect.size = [(UIImage *) icon_ size];
5816 while (rect.size.width > 16 || rect.size.height > 16) {
5817 rect.size.width /= 2;
5818 rect.size.height /= 2;
5821 rect.origin.x = 19 - rect.size.width / 2;
5822 rect.origin.y = 19 - rect.size.height / 2;
5824 [icon_ drawInRect:rect];
5827 if (badge_ != nil) {
5829 rect.size = [(UIImage *) badge_ size];
5831 rect.size.width /= 4;
5832 rect.size.height /= 4;
5834 rect.origin.x = 25 - rect.size.width / 2;
5835 rect.origin.y = 25 - rect.size.height / 2;
5837 [badge_ drawInRect:rect];
5840 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5844 UISetColor(commercial_ ? Purple_ : Black_);
5845 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5847 if (placard_ != nil)
5848 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5851 - (void) drawNormalContentRect:(CGRect)rect {
5852 bool highlighted(highlighted_);
5853 float width([self bounds].size.width);
5857 rect.size = [(UIImage *) icon_ size];
5859 while (rect.size.width > 32 || rect.size.height > 32) {
5860 rect.size.width /= 2;
5861 rect.size.height /= 2;
5864 rect.origin.x = 25 - rect.size.width / 2;
5865 rect.origin.y = 25 - rect.size.height / 2;
5867 [icon_ drawInRect:rect];
5870 if (badge_ != nil) {
5872 rect.size = [(UIImage *) badge_ size];
5874 rect.size.width /= 2;
5875 rect.size.height /= 2;
5877 rect.origin.x = 36 - rect.size.width / 2;
5878 rect.origin.y = 36 - rect.size.height / 2;
5880 [badge_ drawInRect:rect];
5883 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5887 UISetColor(commercial_ ? Purple_ : Black_);
5888 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5889 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5892 UISetColor(commercial_ ? Purplish_ : Gray_);
5893 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
5895 if (placard_ != nil)
5896 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5899 - (void) drawContentRect:(CGRect)rect {
5901 [self drawSummaryContentRect:rect];
5903 [self drawNormalContentRect:rect];
5908 /* Section Cell {{{ */
5909 @interface SectionCell : CyteTableViewCell <
5910 CyteTableViewCellDelegate
5912 _H<NSString> basic_;
5913 _H<NSString> section_;
5915 _H<NSString> count_;
5917 _H<UISwitch> switch_;
5921 - (void) setSection:(Section *)section editing:(BOOL)editing;
5925 @implementation SectionCell
5927 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5928 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5929 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5930 // XXX: this initial frame is wrong, but is fixed later
5931 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5932 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5934 UIView *content([self contentView]);
5935 CGRect bounds([content bounds]);
5937 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5938 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5939 [content addSubview:content_];
5940 [content_ setBackgroundColor:[UIColor whiteColor]];
5942 [content_ setDelegate:self];
5946 - (void) onSwitch:(id)sender {
5947 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5948 if (metadata == nil) {
5949 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5950 [Sections_ setObject:metadata forKey:basic_];
5953 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5957 - (void) setSection:(Section *)section editing:(BOOL)editing {
5958 if (editing != editing_) {
5960 [switch_ removeFromSuperview];
5962 [self addSubview:switch_];
5971 if (section == nil) {
5972 name_ = UCLocalize("ALL_PACKAGES");
5975 basic_ = [section name];
5976 section_ = [section localized];
5978 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5979 count_ = [NSString stringWithFormat:@"%zd", [section count]];
5982 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5985 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5986 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5988 [content_ setNeedsDisplay];
5991 - (void) setFrame:(CGRect)frame {
5992 [super setFrame:frame];
5994 CGRect rect([switch_ frame]);
5995 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
5998 - (NSString *) accessibilityLabel {
6002 - (void) drawContentRect:(CGRect)rect {
6003 bool highlighted(highlighted_ && !editing_);
6005 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6007 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6010 float width(rect.size.width);
6012 width -= 9 + [switch_ frame].size.width;
6016 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6018 CGSize size = [count_ sizeWithFont:Font14_];
6020 UISetColor(Folder_);
6022 [count_ drawAtPoint:CGPointMake(10 + (30 - size.width) / 2, 18) withFont:Font12Bold_];
6028 /* File Table {{{ */
6029 @interface FileTable : CyteViewController <
6030 UITableViewDataSource,
6033 _transient Database *database_;
6034 _H<Package> package_;
6036 _H<NSMutableArray> files_;
6037 _H<UITableView, 2> list_;
6040 - (id) initWithDatabase:(Database *)database;
6041 - (void) setPackage:(Package *)package;
6045 @implementation FileTable
6047 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6048 return files_ == nil ? 0 : [files_ count];
6051 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6055 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6056 static NSString *reuseIdentifier = @"Cell";
6058 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6060 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6061 [cell setFont:[UIFont systemFontOfSize:16]];
6063 [cell setText:[files_ objectAtIndex:indexPath.row]];
6064 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6069 - (NSURL *) navigationURL {
6070 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6074 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6075 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6076 [list_ setRowHeight:24.0f];
6077 [(UITableView *) list_ setDataSource:self];
6078 [list_ setDelegate:self];
6079 [self setView:list_];
6082 - (void) viewDidLoad {
6083 [super viewDidLoad];
6085 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6088 - (void) releaseSubviews {
6094 [super releaseSubviews];
6097 - (id) initWithDatabase:(Database *)database {
6098 if ((self = [super init]) != nil) {
6099 database_ = database;
6103 - (void) setPackage:(Package *)package {
6107 files_ = [NSMutableArray arrayWithCapacity:32];
6109 if (package != nil) {
6111 name_ = [package id];
6113 if (NSArray *files = [package files])
6114 [files_ addObjectsFromArray:files];
6116 if ([files_ count] != 0) {
6117 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6118 [files_ removeObjectAtIndex:0];
6119 [files_ sortUsingSelector:@selector(compareByPath:)];
6121 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6122 [stack addObject:@"/"];
6124 for (int i(0), e([files_ count]); i != e; ++i) {
6125 NSString *file = [files_ objectAtIndex:i];
6126 while (![file hasPrefix:[stack lastObject]])
6127 [stack removeLastObject];
6128 NSString *directory = [stack lastObject];
6129 [stack addObject:[file stringByAppendingString:@"/"]];
6130 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6131 ([stack count] - 2) * 3, "",
6132 [file substringFromIndex:[directory length]]
6141 - (void) reloadData {
6144 [self setPackage:[database_ packageWithName:name_]];
6149 /* Package Controller {{{ */
6150 @interface CYPackageController : CydiaWebViewController <
6151 UIActionSheetDelegate
6153 _transient Database *database_;
6154 _H<Package> package_;
6157 _H<NSMutableArray> buttons_;
6158 _H<UIBarButtonItem> button_;
6161 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6165 @implementation CYPackageController
6167 - (NSURL *) navigationURL {
6168 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6171 /* XXX: this is not safe at all... localization of /fail/ */
6172 - (void) _clickButtonWithName:(NSString *)name {
6173 if ([name isEqualToString:UCLocalize("CLEAR")])
6174 [delegate_ clearPackage:package_];
6175 else if ([name isEqualToString:UCLocalize("INSTALL")])
6176 [delegate_ installPackage:package_];
6177 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6178 [delegate_ installPackage:package_];
6179 else if ([name isEqualToString:UCLocalize("REMOVE")])
6180 [delegate_ removePackage:package_];
6181 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6182 [delegate_ installPackage:package_];
6183 else _assert(false);
6186 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6187 NSString *context([sheet context]);
6189 if ([context isEqualToString:@"modify"]) {
6190 if (button != [sheet cancelButtonIndex]) {
6191 NSString *buttonName = [buttons_ objectAtIndex:button];
6192 [self _clickButtonWithName:buttonName];
6195 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6199 - (bool) _allowJavaScriptPanel {
6204 - (void) _customButtonClicked {
6205 int count([buttons_ count]);
6210 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6212 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6213 [buttons addObjectsFromArray:buttons_];
6215 UIActionSheet *sheet = [[[UIActionSheet alloc]
6218 cancelButtonTitle:nil
6219 destructiveButtonTitle:nil
6220 otherButtonTitles:nil
6223 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6225 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6226 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6228 [sheet setContext:@"modify"];
6230 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6234 - (void) reloadButtonClicked {
6235 if (commercial_ && function_ == nil && [package_ uninstalled])
6237 [self customButtonClicked];
6240 - (void) applyLoadingTitle {
6241 // Don't show "Loading" as the title. Ever.
6244 - (UIBarButtonItem *) rightButton {
6249 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6250 if ((self = [super init]) != nil) {
6251 database_ = database;
6252 buttons_ = [NSMutableArray arrayWithCapacity:4];
6253 name_ = name == nil ? @"" : [NSString stringWithString:name];
6254 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6258 - (void) reloadData {
6261 package_ = [database_ packageWithName:name_];
6263 [buttons_ removeAllObjects];
6265 if (package_ != nil) {
6266 [(Package *) package_ parse];
6268 commercial_ = [package_ isCommercial];
6270 if ([package_ mode] != nil)
6271 [buttons_ addObject:UCLocalize("CLEAR")];
6272 if ([package_ source] == nil);
6273 else if ([package_ upgradableAndEssential:NO])
6274 [buttons_ addObject:UCLocalize("UPGRADE")];
6275 else if ([package_ uninstalled])
6276 [buttons_ addObject:UCLocalize("INSTALL")];
6278 [buttons_ addObject:UCLocalize("REINSTALL")];
6279 if (![package_ uninstalled])
6280 [buttons_ addObject:UCLocalize("REMOVE")];
6284 switch ([buttons_ count]) {
6285 case 0: title = nil; break;
6286 case 1: title = [buttons_ objectAtIndex:0]; break;
6287 default: title = UCLocalize("MODIFY"); break;
6290 button_ = [[[UIBarButtonItem alloc]
6292 style:UIBarButtonItemStylePlain
6294 action:@selector(customButtonClicked)
6298 - (bool) isLoading {
6299 return commercial_ ? [super isLoading] : false;
6305 /* Package List Controller {{{ */
6306 @interface PackageListController : CyteViewController <
6307 UITableViewDataSource,
6310 _transient Database *database_;
6312 _H<NSArray> packages_;
6313 _H<NSArray> sections_;
6314 _H<UITableView, 2> list_;
6316 _H<NSArray> thumbs_;
6317 std::vector<NSInteger> offset_;
6319 _H<NSString> title_;
6320 unsigned reloading_;
6323 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6324 - (void) setDelegate:(id)delegate;
6325 - (void) resetCursor;
6328 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6332 @implementation PackageListController
6334 - (NSURL *) referrerURL {
6335 return [self navigationURL];
6338 - (bool) isSummarized {
6342 - (bool) showsSections {
6346 - (void) deselectWithAnimation:(BOOL)animated {
6347 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6350 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6351 CGRect base = [[self view] bounds];
6352 base.size.height -= bounds.size.height;
6353 base.origin = [list_ frame].origin;
6355 [UIView beginAnimations:nil context:NULL];
6356 [UIView setAnimationBeginsFromCurrentState:YES];
6357 [UIView setAnimationCurve:curve];
6358 [UIView setAnimationDuration:duration];
6359 [list_ setFrame:base];
6360 [UIView commitAnimations];
6363 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6364 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6367 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6368 [self resizeForKeyboardBounds:bounds duration:0];
6371 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6372 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6373 *curve = UIViewAnimationCurveEaseInOut;
6375 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6377 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6380 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6383 - (void) keyboardWillShow:(NSNotification *)notification {
6386 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6387 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6389 NSTimeInterval duration;
6390 UIViewAnimationCurve curve;
6391 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6393 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);
6394 UIViewController *base = self;
6395 while ([base parentOrPresentingViewController] != nil)
6396 base = [base parentOrPresentingViewController];
6397 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6398 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6400 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6401 intersection.size.height += CYStatusBarHeight();
6403 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6406 - (void) keyboardWillHide:(NSNotification *)notification {
6407 NSTimeInterval duration;
6408 UIViewAnimationCurve curve;
6409 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6411 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6414 - (void) viewWillAppear:(BOOL)animated {
6415 [super viewWillAppear:animated];
6417 [self resizeForKeyboardBounds:CGRectZero];
6418 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6419 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6422 - (void) viewWillDisappear:(BOOL)animated {
6423 [super viewWillDisappear:animated];
6425 [self resizeForKeyboardBounds:CGRectZero];
6426 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6427 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6430 - (void) viewDidAppear:(BOOL)animated {
6431 [super viewDidAppear:animated];
6432 [self deselectWithAnimation:animated];
6435 - (void) didSelectPackage:(Package *)package {
6436 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6437 [view setDelegate:delegate_];
6438 [[self navigationController] pushViewController:view animated:YES];
6441 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6442 NSInteger count([sections_ count]);
6443 return count == 0 ? 1 : count;
6446 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6447 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6449 return [[sections_ objectAtIndex:section] name];
6452 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6453 if ([sections_ count] == 0)
6455 return [[sections_ objectAtIndex:section] count];
6458 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6459 @synchronized (database_) {
6460 if ([database_ era] != era_)
6463 Section *section([sections_ objectAtIndex:[path section]]);
6464 NSInteger row([path row]);
6465 Package *package([packages_ objectAtIndex:([section row] + row)]);
6466 return [[package retain] autorelease];
6469 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6470 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6472 cell = [[[PackageCell alloc] init] autorelease];
6474 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6475 [cell setPackage:package asSummary:[self isSummarized]];
6479 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6480 Package *package([self packageAtIndexPath:path]);
6481 package = [database_ packageWithName:[package id]];
6482 [self didSelectPackage:package];
6485 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6489 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6490 return offset_[index];
6493 - (void) updateHeight {
6494 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6497 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6498 if ((self = [super init]) != nil) {
6499 database_ = database;
6500 title_ = [title copy];
6501 [[self navigationItem] setTitle:title_];
6506 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6507 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6508 [self setView:view];
6510 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6511 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6512 [view addSubview:list_];
6514 // XXX: is 20 the most optimal number here?
6515 [list_ setSectionIndexMinimumDisplayRowCount:20];
6517 [(UITableView *) list_ setDataSource:self];
6518 [list_ setDelegate:self];
6520 [self updateHeight];
6523 - (void) releaseSubviews {
6532 [super releaseSubviews];
6535 - (void) setDelegate:(id)delegate {
6536 delegate_ = delegate;
6539 - (bool) shouldYield {
6543 - (bool) shouldBlock {
6547 - (NSMutableArray *) _reloadPackages {
6548 @synchronized (database_) {
6549 era_ = [database_ era];
6550 NSArray *packages([database_ packages]);
6552 return [NSMutableArray arrayWithArray:packages];
6555 - (void) _reloadData {
6556 if (reloading_ != 0) {
6561 NSMutableArray *packages;
6564 if ([self shouldYield]) {
6568 if (![self shouldBlock])
6571 hud = [delegate_ addProgressHUD];
6572 [hud setText:UCLocalize("LOADING")];
6576 packages = [self yieldToSelector:@selector(_reloadPackages)];
6579 [delegate_ removeProgressHUD:hud];
6580 } while (reloading_ == 2);
6582 packages = [self _reloadPackages];
6585 @synchronized (database_) {
6586 if (era_ != [database_ era])
6593 packages_ = packages;
6595 if ([self showsSections])
6596 sections_ = [self sectionsForPackages:packages];
6598 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6599 [section setCount:[packages_ count]];
6600 sections_ = [NSArray arrayWithObject:section];
6603 [self updateHeight];
6605 _profile(PackageTable$reloadData$List)
6606 [(UITableView *) list_ setDataSource:self];
6614 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6615 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6616 size_t end([packages count]);
6618 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6619 Section *section(prefix);
6621 thumbs_ = CollationThumbs_;
6622 offset_ = CollationOffset_;
6625 size_t offsets([CollationStarts_ count]);
6627 NSString *start([CollationStarts_ objectAtIndex:offset]);
6628 size_t length([start length]);
6630 for (size_t index(0); index != end; ++index) {
6632 Package *package([packages objectAtIndex:index]);
6633 NSString *name(PackageName(package, @selector(cyname)));
6635 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6636 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6637 NSString *title([CollationTitles_ objectAtIndex:offset]);
6638 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6639 [sections addObject:section];
6641 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6644 length = [start length];
6648 [section addToCount];
6651 for (; offset != offsets; ++offset) {
6652 NSString *title([CollationTitles_ objectAtIndex:offset]);
6653 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6654 [sections addObject:section];
6657 if ([prefix count] != 0) {
6658 Section *suffix([sections lastObject]);
6659 [prefix setName:[suffix name]];
6660 [suffix setName:nil];
6661 [sections insertObject:prefix atIndex:(offsets - 1)];
6667 - (void) reloadData {
6670 if ([self shouldYield])
6671 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6676 - (void) resetCursor {
6677 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6680 - (void) clearData {
6681 [self updateHeight];
6683 [list_ setDataSource:nil];
6691 /* Filtered Package List Controller {{{ */
6692 typedef Function<bool, Package *> PackageFilter;
6693 typedef Function<void, NSMutableArray *> PackageSorter;
6694 @interface FilteredPackageListController : PackageListController {
6695 PackageFilter filter_;
6696 PackageSorter sorter_;
6699 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6701 - (void) setFilter:(PackageFilter)filter;
6702 - (void) setSorter:(PackageSorter)sorter;
6706 @implementation FilteredPackageListController
6708 - (void) setFilter:(PackageFilter)filter {
6709 @synchronized (self) {
6713 - (void) setSorter:(PackageSorter)sorter {
6714 @synchronized (self) {
6718 - (NSMutableArray *) _reloadPackages {
6719 @synchronized (database_) {
6720 era_ = [database_ era];
6722 NSArray *packages([database_ packages]);
6723 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6725 PackageFilter filter;
6726 PackageSorter sorter;
6728 @synchronized (self) {
6733 _profile(PackageTable$reloadData$Filter)
6734 for (Package *package in packages)
6735 if ([package valid] && filter(package))
6736 [filtered addObject:package];
6744 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6745 if ((self = [super initWithDatabase:database title:title]) != nil) {
6746 [self setFilter:filter];
6753 /* Home Controller {{{ */
6754 @interface HomeController : CydiaWebViewController {
6755 CFRunLoopRef runloop_;
6756 SCNetworkReachabilityRef reachability_;
6761 @implementation HomeController
6763 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6764 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6768 if ((self = [super init]) != nil) {
6769 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6772 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6773 if (reachability_ != NULL) {
6774 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6775 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6777 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6778 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6785 if (reachability_ != NULL && runloop_ != NULL)
6786 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6790 - (NSURL *) navigationURL {
6791 return [NSURL URLWithString:@"cydia://home"];
6794 - (void) aboutButtonClicked {
6795 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6797 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6798 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6799 [alert setCancelButtonIndex:0];
6802 @"Copyright \u00a9 2008-2013\n"
6805 "Jay Freeman (saurik)\n"
6806 "saurik@saurik.com\n"
6807 "http://www.saurik.com/"
6813 - (UIBarButtonItem *) leftButton {
6814 return [[[UIBarButtonItem alloc]
6815 initWithTitle:UCLocalize("ABOUT")
6816 style:UIBarButtonItemStylePlain
6818 action:@selector(aboutButtonClicked)
6825 /* Cydia Navigation Controller Interface {{{ */
6826 @interface UINavigationController (Cydia)
6828 - (NSArray *) navigationURLCollection;
6829 - (void) unloadData;
6834 /* Cydia Tab Bar Controller {{{ */
6835 @interface CydiaTabBarController : CyteTabBarController <
6836 UITabBarControllerDelegate,
6839 _transient Database *database_;
6841 _H<UIActivityIndicatorView> indicator_;
6844 // XXX: ok, "updatedelegate_"?...
6845 _transient NSObject<CydiaDelegate> *updatedelegate_;
6848 - (NSArray *) navigationURLCollection;
6849 - (void) beginUpdate;
6854 @implementation CydiaTabBarController
6856 - (NSArray *) navigationURLCollection {
6857 NSMutableArray *items([NSMutableArray array]);
6859 // XXX: Should this deal with transient view controllers?
6860 for (id navigation in [self viewControllers]) {
6861 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6863 [items addObject:stack];
6869 - (id) initWithDatabase:(Database *)database {
6870 if ((self = [super init]) != nil) {
6871 database_ = database;
6872 [self setDelegate:self];
6874 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6875 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6877 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6881 - (void) setUpdate:(NSDate *)date {
6885 - (void) beginUpdate {
6889 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6890 UITabBarItem *item([controller tabBarItem]);
6892 [item setBadgeValue:@""];
6893 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6895 [indicator_ startAnimating];
6896 [badge addSubview:indicator_];
6898 [updatedelegate_ retainNetworkActivityIndicator];
6902 detachNewThreadSelector:@selector(performUpdate)
6908 - (void) performUpdate {
6909 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6911 SourceStatus status(self, database_);
6912 [database_ updateWithStatus:status];
6915 performSelectorOnMainThread:@selector(completeUpdate)
6923 - (void) stopUpdateWithSelector:(SEL)selector {
6925 [updatedelegate_ releaseNetworkActivityIndicator];
6927 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6928 [[controller tabBarItem] setBadgeValue:nil];
6930 [indicator_ removeFromSuperview];
6931 [indicator_ stopAnimating];
6933 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6936 - (void) completeUpdate {
6939 [self stopUpdateWithSelector:@selector(reloadData)];
6942 - (void) cancelUpdate {
6943 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
6946 - (void) cancelPressed {
6947 [self cancelUpdate];
6954 - (bool) isSourceCancelled {
6958 - (void) startSourceFetch:(NSString *)uri {
6961 - (void) stopSourceFetch:(NSString *)uri {
6964 - (void) setUpdateDelegate:(id)delegate {
6965 updatedelegate_ = delegate;
6968 - (UIView *) transitionView {
6969 if (![self respondsToSelector:@selector(_transitionView)])
6970 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6971 else if (kCFCoreFoundationVersionNumber < 800)
6972 return [self _transitionView];
6974 return [[[self _transitionView] superview] superview];
6980 /* Cydia Navigation Controller Implementation {{{ */
6981 @implementation UINavigationController (Cydia)
6983 - (NSArray *) navigationURLCollection {
6984 NSMutableArray *stack([NSMutableArray array]);
6986 for (CyteViewController *controller in [self viewControllers]) {
6987 NSString *url = [[controller navigationURL] absoluteString];
6989 [stack addObject:url];
6995 - (void) reloadData {
6998 UIViewController *visible([self visibleViewController]);
7000 [visible reloadData];
7002 // on the iPad, this view controller is ALSO visible. :(
7004 if (UIViewController *top = [self topViewController])
7009 - (void) unloadData {
7010 for (CyteViewController *page in [self viewControllers])
7019 /* Cydia:// Protocol {{{ */
7020 @interface CydiaURLProtocol : NSURLProtocol {
7025 @implementation CydiaURLProtocol
7027 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7028 NSURL *url([request URL]);
7032 NSString *scheme([[url scheme] lowercaseString]);
7033 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7035 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7041 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7045 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7046 id<NSURLProtocolClient> client([self client]);
7048 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7050 NSData *data(UIImagePNGRepresentation(icon));
7052 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7053 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7054 [client URLProtocol:self didLoadData:data];
7055 [client URLProtocolDidFinishLoading:self];
7059 - (void) startLoading {
7060 id<NSURLProtocolClient> client([self client]);
7061 NSURLRequest *request([self request]);
7063 NSURL *url([request URL]);
7064 NSString *href([url absoluteString]);
7065 NSString *scheme([[url scheme] lowercaseString]);
7069 if ([scheme isEqualToString:@"cydia"])
7070 path = [href substringFromIndex:8];
7071 else if ([scheme isEqualToString:@"about"])
7072 path = [href substringFromIndex:12];
7073 else _assert(false);
7075 NSRange slash([path rangeOfString:@"/"]);
7078 if (slash.location == NSNotFound) {
7082 command = [path substringToIndex:slash.location];
7083 path = [path substringFromIndex:(slash.location + 1)];
7086 Database *database([Database sharedInstance]);
7088 if ([command isEqualToString:@"package-icon"]) {
7091 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7092 Package *package([database packageWithName:path]);
7096 UIImage *icon([package icon]);
7097 [self _returnPNGWithImage:icon forRequest:request];
7098 } else if ([command isEqualToString:@"uikit-image"]) {
7101 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7102 UIImage *icon(_UIImageWithName(path));
7103 [self _returnPNGWithImage:icon forRequest:request];
7104 } else if ([command isEqualToString:@"section-icon"]) {
7107 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7108 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7110 icon = [UIImage applicationImageNamed:@"unknown.png"];
7111 [self _returnPNGWithImage:icon forRequest:request];
7113 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7117 - (void) stopLoading {
7123 /* Section Controller {{{ */
7124 @interface SectionController : FilteredPackageListController {
7126 _H<NSString> section_;
7129 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7133 @implementation SectionController
7135 - (NSURL *) referrerURL {
7136 NSString *name(section_);
7137 name = name ?: @"*";
7138 NSString *key(key_);
7140 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7143 - (NSURL *) navigationURL {
7144 NSString *name(section_);
7145 name = name ?: @"*";
7146 NSString *key(key_);
7148 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7151 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7154 title = UCLocalize("ALL_PACKAGES");
7155 else if (![section isEqual:@""])
7156 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7158 title = UCLocalize("NO_SECTION");
7160 if ((self = [super initWithDatabase:database title:title]) != nil) {
7161 key_ = [source key];
7166 - (void) reloadData {
7167 Source *source([database_ sourceWithKey:key_]);
7168 _H<NSString> name(section_);
7170 [self setFilter:[=](Package *package) {
7171 NSString *section([package section]);
7175 section == nil && [name length] == 0 ||
7176 [name isEqualToString:section]
7179 [package source] == source
7180 ) && [package visible];
7188 /* Sections Controller {{{ */
7189 @interface SectionsController : CyteViewController <
7190 UITableViewDataSource,
7193 _transient Database *database_;
7195 _H<NSMutableArray> sections_;
7196 _H<NSMutableArray> filtered_;
7197 _H<UITableView, 2> list_;
7200 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7201 - (void) editButtonClicked;
7205 @implementation SectionsController
7207 - (NSURL *) navigationURL {
7208 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7211 - (Source *) source {
7214 return [database_ sourceWithKey:key_];
7217 - (void) updateNavigationItem {
7218 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7219 if ([sections_ count] == 0) {
7220 [[self navigationItem] setRightBarButtonItem:nil];
7222 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7223 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7225 action:@selector(editButtonClicked)
7226 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7230 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7231 [super setEditing:editing animated:animated];
7236 [delegate_ updateData];
7238 [self updateNavigationItem];
7241 - (void) viewDidAppear:(BOOL)animated {
7242 [super viewDidAppear:animated];
7243 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7246 - (void) viewWillDisappear:(BOOL)animated {
7247 [super viewWillDisappear:animated];
7248 [self setEditing:NO];
7251 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7252 Section *section = nil;
7253 int index = [indexPath row];
7254 if (![self isEditing]) {
7257 section = [filtered_ objectAtIndex:index];
7259 section = [sections_ objectAtIndex:index];
7264 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7265 if ([self isEditing])
7266 return [sections_ count];
7268 return [filtered_ count] + 1;
7271 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7275 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7276 static NSString *reuseIdentifier = @"SectionCell";
7278 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7280 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7282 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7287 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7288 if ([self isEditing])
7291 Section *section = [self sectionAtIndexPath:indexPath];
7293 SectionController *controller = [[[SectionController alloc]
7294 initWithDatabase:database_
7295 source:[self source]
7296 section:[section name]
7298 [controller setDelegate:delegate_];
7300 [[self navigationController] pushViewController:controller animated:YES];
7304 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7305 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7306 [list_ setRowHeight:46];
7307 [(UITableView *) list_ setDataSource:self];
7308 [list_ setDelegate:self];
7309 [self setView:list_];
7312 - (void) viewDidLoad {
7313 [super viewDidLoad];
7315 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7318 - (void) releaseSubviews {
7324 [super releaseSubviews];
7327 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7328 if ((self = [super init]) != nil) {
7329 database_ = database;
7330 key_ = [source key];
7334 - (void) reloadData {
7337 NSArray *packages = [database_ packages];
7339 sections_ = [NSMutableArray arrayWithCapacity:16];
7340 filtered_ = [NSMutableArray arrayWithCapacity:16];
7342 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7344 Source *source([self source]);
7347 for (Package *package in packages) {
7348 if (source != nil && [package source] != source)
7351 NSString *name([package section]);
7352 NSString *key(name == nil ? @"" : name);
7356 _profile(SectionsView$reloadData$Section)
7357 section = [sections objectForKey:key];
7358 if (section == nil) {
7359 _profile(SectionsView$reloadData$Section$Allocate)
7360 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7361 [sections setObject:section forKey:key];
7366 [section addToCount];
7368 _profile(SectionsView$reloadData$Filter)
7369 if (![package valid] || ![package visible])
7377 [sections_ addObjectsFromArray:[sections allValues]];
7379 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7381 for (Section *section in (id) sections_) {
7382 size_t count([section row]);
7386 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7387 [section setCount:count];
7388 [filtered_ addObject:section];
7391 [self updateNavigationItem];
7396 - (void) editButtonClicked {
7397 [self setEditing:![self isEditing] animated:YES];
7403 /* Changes Controller {{{ */
7404 @interface ChangesController : FilteredPackageListController {
7408 - (id) initWithDatabase:(Database *)database;
7412 @implementation ChangesController
7414 - (NSURL *) referrerURL {
7415 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7418 - (NSURL *) navigationURL {
7419 return [NSURL URLWithString:@"cydia://changes"];
7422 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7423 @synchronized (database_) {
7424 if ([database_ era] != era_)
7427 NSUInteger sectionIndex([path section]);
7428 if (sectionIndex >= [sections_ count])
7430 Section *section([sections_ objectAtIndex:sectionIndex]);
7431 NSInteger row([path row]);
7432 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7435 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7436 NSString *context([alert context]);
7438 if ([context isEqualToString:@"norefresh"])
7439 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7442 - (void) setLeftBarButtonItem {
7443 if ([delegate_ updating])
7444 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7445 initWithTitle:UCLocalize("CANCEL")
7446 style:UIBarButtonItemStyleDone
7448 action:@selector(cancelButtonClicked)
7449 ] autorelease] animated:YES];
7451 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7452 initWithTitle:UCLocalize("REFRESH")
7453 style:UIBarButtonItemStylePlain
7455 action:@selector(refreshButtonClicked)
7456 ] autorelease] animated:YES];
7459 - (void) refreshButtonClicked {
7460 if ([delegate_ requestUpdate])
7461 [self setLeftBarButtonItem];
7464 - (void) cancelButtonClicked {
7465 [delegate_ cancelUpdate];
7468 - (void) upgradeButtonClicked {
7469 [delegate_ distUpgrade];
7470 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7473 - (bool) shouldYield {
7477 - (bool) shouldBlock {
7481 - (void) useFilter {
7482 @synchronized (self) {
7483 [self setFilter:[](Package *package) {
7484 return [package upgradableAndEssential:YES] || [package visible];
7487 [self setSorter:[](NSMutableArray *packages) {
7488 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7492 - (id) initWithDatabase:(Database *)database {
7493 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7498 - (void) viewDidLoad {
7499 [super viewDidLoad];
7500 [self setLeftBarButtonItem];
7503 - (void) viewWillAppear:(BOOL)animated {
7504 [super viewWillAppear:animated];
7505 [self setLeftBarButtonItem];
7508 - (void) reloadData {
7509 [self setLeftBarButtonItem];
7513 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7514 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7516 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7517 Section *ignored = nil;
7518 Section *section = nil;
7522 bool unseens = false;
7524 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7526 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7527 Package *package = [packages objectAtIndex:offset];
7529 BOOL uae = [package upgradableAndEssential:YES];
7533 time_t seen([package seen]);
7535 if (section == nil || last != seen) {
7539 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7542 _profile(ChangesController$reloadData$Allocate)
7543 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7544 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7545 [sections addObject:section];
7549 [section addToCount];
7550 } else if ([package ignored]) {
7551 if (ignored == nil) {
7552 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7554 [ignored addToCount];
7557 [upgradable addToCount];
7562 CFRelease(formatter);
7565 Section *last = [sections lastObject];
7566 size_t count = [last count];
7567 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7568 [sections removeLastObject];
7571 if ([ignored count] != 0)
7572 [sections insertObject:ignored atIndex:0];
7574 [sections insertObject:upgradable atIndex:0];
7578 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7579 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7580 style:UIBarButtonItemStylePlain
7582 action:@selector(upgradeButtonClicked)
7583 ] autorelease]) animated:YES];
7590 /* Search Controller {{{ */
7591 @interface SearchController : FilteredPackageListController <
7594 _H<UISearchBar, 1> search_;
7599 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7600 - (void) reloadData;
7604 @implementation SearchController
7606 - (NSURL *) referrerURL {
7607 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7610 - (NSURL *) navigationURL {
7611 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7612 return [NSURL URLWithString:@"cydia://search"];
7614 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7617 - (NSArray *) termsForQuery:(NSString *)query {
7618 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7619 for (NSString *component in [query componentsSeparatedByString:@" "])
7620 if ([component length] != 0)
7621 [terms addObject:component];
7626 - (void) useSearch {
7627 _H<NSArray> query([self termsForQuery:[search_ text]]);
7630 @synchronized (self) {
7631 [self setFilter:[=](Package *package) {
7632 if (![package unfiltered])
7634 if (![package matches:query])
7639 [self setSorter:[](NSMutableArray *packages) {
7640 [packages radixSortUsingSelector:@selector(rank)];
7648 - (void) usePrefix:(NSString *)prefix {
7649 _H<NSString> query(prefix);
7652 @synchronized (self) {
7653 [self setFilter:[=](Package *package) {
7654 if ([query length] == 0)
7656 if (![package unfiltered])
7658 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7663 [self setSorter:nullptr];
7669 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7671 [self usePrefix:[search_ text]];
7674 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7675 [search_ resignFirstResponder];
7679 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7680 [search_ setText:@""];
7681 [self searchBarButtonClicked:searchBar];
7684 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7685 [self searchBarButtonClicked:searchBar];
7688 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7689 [self usePrefix:text];
7692 - (bool) shouldYield {
7696 - (bool) shouldBlock {
7700 - (bool) isSummarized {
7704 - (bool) showsSections {
7708 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7709 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7710 search_ = [[[UISearchBar alloc] init] autorelease];
7711 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7712 [search_ setDelegate:self];
7714 UITextField *textField;
7715 if ([search_ respondsToSelector:@selector(searchField)])
7716 textField = [search_ searchField];
7718 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7720 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7721 [textField setEnablesReturnKeyAutomatically:NO];
7722 [[self navigationItem] setTitleView:textField];
7725 [search_ setText:query];
7730 - (void) viewDidAppear:(BOOL)animated {
7731 [super viewDidAppear:animated];
7733 if (!searchloaded_) {
7734 searchloaded_ = YES;
7735 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7736 [search_ layoutSubviews];
7739 if ([self isSummarized])
7740 [search_ becomeFirstResponder];
7743 - (void) reloadData {
7748 - (void) didSelectPackage:(Package *)package {
7749 [search_ resignFirstResponder];
7750 [super didSelectPackage:package];
7755 /* Package Settings Controller {{{ */
7756 @interface PackageSettingsController : CyteViewController <
7757 UITableViewDataSource,
7760 _transient Database *database_;
7762 _H<Package> package_;
7763 _H<UITableView, 2> table_;
7764 _H<UISwitch> subscribedSwitch_;
7765 _H<UISwitch> ignoredSwitch_;
7766 _H<UITableViewCell> subscribedCell_;
7767 _H<UITableViewCell> ignoredCell_;
7770 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7774 @implementation PackageSettingsController
7776 - (NSURL *) navigationURL {
7777 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7780 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7781 if (package_ == nil)
7784 if ([package_ installed] == nil)
7790 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7791 if (package_ == nil)
7794 // both sections contain just one item right now.
7798 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7802 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7804 return UCLocalize("SHOW_ALL_CHANGES_EX");
7806 return UCLocalize("IGNORE_UPGRADES_EX");
7809 - (void) onSubscribed:(id)control {
7810 bool value([control isOn]);
7811 if (package_ == nil)
7813 if ([package_ setSubscribed:value])
7814 [delegate_ updateData];
7817 - (void) _updateIgnored {
7818 const char *package([name_ UTF8String]);
7819 bool on([ignoredSwitch_ isOn]);
7821 pid_t pid(ExecFork());
7823 FILE *dpkg(popen("dpkg --set-selections", "w"));
7824 fwrite(package, strlen(package), 1, dpkg);
7827 fwrite(" hold\n", 6, 1, dpkg);
7829 fwrite(" install\n", 9, 1, dpkg);
7837 - (void) onIgnored:(id)control {
7838 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7839 [invocation setTarget:self];
7840 [invocation setSelector:@selector(_updateIgnored)];
7842 [delegate_ reloadDataWithInvocation:invocation];
7845 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7846 if (package_ == nil)
7849 switch ([indexPath section]) {
7850 case 0: return subscribedCell_;
7851 case 1: return ignoredCell_;
7860 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7861 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7862 [self setView:view];
7864 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7865 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7866 [(UITableView *) table_ setDataSource:self];
7867 [table_ setDelegate:self];
7868 [view addSubview:table_];
7870 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7871 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7872 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7874 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7875 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7876 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7878 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7879 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7880 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7881 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7883 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7884 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7885 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7886 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7889 - (void) viewDidLoad {
7890 [super viewDidLoad];
7892 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7895 - (void) releaseSubviews {
7897 subscribedCell_ = nil;
7899 ignoredSwitch_ = nil;
7900 subscribedSwitch_ = nil;
7902 [super releaseSubviews];
7905 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7906 if ((self = [super init]) != nil) {
7907 database_ = database;
7912 - (void) reloadData {
7915 package_ = [database_ packageWithName:name_];
7917 if (package_ != nil) {
7918 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7919 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7920 } // XXX: what now, G?
7922 [table_ reloadData];
7928 /* Installed Controller {{{ */
7929 @interface InstalledController : FilteredPackageListController {
7933 - (id) initWithDatabase:(Database *)database;
7934 - (void) queueStatusDidChange;
7938 @implementation InstalledController
7940 - (NSURL *) referrerURL {
7941 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
7944 - (NSURL *) navigationURL {
7945 return [NSURL URLWithString:@"cydia://installed"];
7948 - (bool) showsSections {
7952 - (void) useUpdated {
7955 @synchronized (self) {
7956 [self setFilter:[](Package *package) {
7957 return ![package uninstalled] && package->role_ < 7;
7960 [self setSorter:[](NSMutableArray *packages) {
7961 [packages radixSortUsingSelector:@selector(updated)];
7965 - (void) useFilter:(UISegmentedControl *)segmented {
7966 NSInteger selected([segmented selectedSegmentIndex]);
7968 return [self useUpdated];
7969 bool simple(selected == 0);
7972 @synchronized (self) {
7973 [self setFilter:[=](Package *package) {
7974 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
7977 [self setSorter:nullptr];
7980 - (id) initWithDatabase:(Database *)database {
7981 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
7982 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
7983 [segmented setSelectedSegmentIndex:0];
7984 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
7985 [[self navigationItem] setTitleView:segmented];
7987 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
7988 [self useFilter:segmented];
7990 [self queueStatusDidChange];
7995 - (void) queueButtonClicked {
8000 - (void) queueStatusDidChange {
8003 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8004 initWithTitle:UCLocalize("QUEUE")
8005 style:UIBarButtonItemStyleDone
8007 action:@selector(queueButtonClicked)
8010 [[self navigationItem] setLeftBarButtonItem:nil];
8015 - (void) modeChanged:(UISegmentedControl *)segmented {
8016 [self useFilter:segmented];
8023 /* Source Cell {{{ */
8024 @interface SourceCell : CyteTableViewCell <
8025 CyteTableViewCellDelegate,
8028 _H<Source, 1> source_;
8031 _H<NSString> origin_;
8032 _H<NSString> label_;
8033 _H<UIActivityIndicatorView> indicator_;
8036 - (void) setSource:(Source *)source;
8037 - (void) setFetch:(NSNumber *)fetch;
8041 @implementation SourceCell
8043 - (void) _setImage:(NSArray *)data {
8044 if ([url_ isEqual:[data objectAtIndex:0]]) {
8045 icon_ = [data objectAtIndex:1];
8046 [content_ setNeedsDisplay];
8050 - (void) _setSource:(NSURL *) url {
8051 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8053 if (NSData *data = [NSURLConnection
8054 sendSynchronousRequest:[NSURLRequest
8056 cachePolicy:NSURLRequestUseProtocolCachePolicy
8060 returningResponse:NULL
8063 if (UIImage *image = [UIImage imageWithData:data])
8064 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8069 - (void) setSource:(Source *)source {
8071 [source_ setDelegate:self];
8073 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8075 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8077 origin_ = [source name];
8078 label_ = [source rooturi];
8080 [content_ setNeedsDisplay];
8082 url_ = [source iconURL];
8083 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8086 - (void) setAllSource {
8088 [indicator_ stopAnimating];
8090 icon_ = [UIImage applicationImageNamed:@"folder.png"];
8091 origin_ = UCLocalize("ALL_SOURCES");
8092 label_ = UCLocalize("ALL_SOURCES_EX");
8093 [content_ setNeedsDisplay];
8096 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8097 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8098 UIView *content([self contentView]);
8099 CGRect bounds([content bounds]);
8101 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8102 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8103 [content_ setBackgroundColor:[UIColor whiteColor]];
8104 [content addSubview:content_];
8106 [content_ setDelegate:self];
8107 [content_ setOpaque:YES];
8109 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8110 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8111 [content addSubview:indicator_];
8113 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8117 - (void) layoutSubviews {
8118 [super layoutSubviews];
8120 UIView *content([self contentView]);
8121 CGRect bounds([content bounds]);
8123 CGRect frame([indicator_ frame]);
8124 frame.origin.x = bounds.size.width - frame.size.width;
8125 frame.origin.y = (bounds.size.height - frame.size.height) / 2;
8127 if (kCFCoreFoundationVersionNumber < 800)
8128 frame.origin.x -= 8;
8129 [indicator_ setFrame:frame];
8132 - (NSString *) accessibilityLabel {
8136 - (void) drawContentRect:(CGRect)rect {
8137 bool highlighted(highlighted_);
8138 float width(rect.size.width);
8142 rect.size = [(UIImage *) icon_ size];
8144 while (rect.size.width > 32 || rect.size.height > 32) {
8145 rect.size.width /= 2;
8146 rect.size.height /= 2;
8149 rect.origin.x = 26 - rect.size.width / 2;
8150 rect.origin.y = 26 - rect.size.height / 2;
8152 [icon_ drawInRect:rect];
8155 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8160 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 61) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8164 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 61) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8167 - (void) setFetch:(NSNumber *)fetch {
8168 if ([fetch boolValue])
8169 [indicator_ startAnimating];
8171 [indicator_ stopAnimating];
8176 /* Sources Controller {{{ */
8177 @interface SourcesController : CyteViewController <
8178 UITableViewDataSource,
8181 _transient Database *database_;
8184 _H<UITableView, 2> list_;
8185 _H<NSMutableArray> sources_;
8189 _H<UIProgressHUD> hud_;
8192 NSURLConnection *trivial_bz2_;
8193 NSURLConnection *trivial_gz_;
8198 - (id) initWithDatabase:(Database *)database;
8199 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8203 @implementation SourcesController
8205 - (void) _releaseConnection:(NSURLConnection *)connection {
8206 if (connection != nil) {
8207 [connection cancel];
8208 //[connection setDelegate:nil];
8209 [connection release];
8214 [self _releaseConnection:trivial_gz_];
8215 [self _releaseConnection:trivial_bz2_];
8220 - (NSURL *) navigationURL {
8221 return [NSURL URLWithString:@"cydia://sources"];
8224 - (void) viewDidAppear:(BOOL)animated {
8225 [super viewDidAppear:animated];
8226 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8229 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8233 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8235 return UCLocalize("INDIVIDUAL_SOURCES");
8239 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8242 case 1: return [sources_ count];
8247 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8248 @synchronized (database_) {
8249 if ([database_ era] != era_)
8251 if ([indexPath section] != 1)
8253 NSUInteger index([indexPath row]);
8254 if (index >= [sources_ count])
8256 return [sources_ objectAtIndex:index];
8259 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8260 static NSString *cellIdentifier = @"SourceCell";
8262 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8263 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8264 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8266 Source *source([self sourceAtIndexPath:indexPath]);
8268 [cell setAllSource];
8270 [cell setSource:source];
8275 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8276 SectionsController *controller([[[SectionsController alloc]
8277 initWithDatabase:database_
8278 source:[self sourceAtIndexPath:indexPath]
8281 [controller setDelegate:delegate_];
8282 [[self navigationController] pushViewController:controller animated:YES];
8285 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8286 if ([indexPath section] != 1)
8288 Source *source = [self sourceAtIndexPath:indexPath];
8289 return [source record] != nil;
8292 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8293 _assert([indexPath section] == 1);
8294 if (editingStyle == UITableViewCellEditingStyleDelete) {
8295 Source *source = [self sourceAtIndexPath:indexPath];
8296 if (source == nil) return;
8298 [Sources_ removeObjectForKey:[source key]];
8301 [delegate_ _saveConfig];
8302 [delegate_ reloadDataWithInvocation:nil];
8306 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8307 [self updateButtonsForEditingStatusAnimated:YES];
8311 [delegate_ addTrivialSource:href_];
8314 [delegate_ syncData];
8317 - (NSString *) getWarning {
8318 NSString *href(href_);
8319 NSRange colon([href rangeOfString:@"://"]);
8320 if (colon.location != NSNotFound)
8321 href = [href substringFromIndex:(colon.location + 3)];
8322 href = [href stringByAddingPercentEscapes];
8323 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8325 NSURL *url([NSURL URLWithString:href]);
8327 NSStringEncoding encoding;
8328 NSError *error(nil);
8330 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8331 return [warning length] == 0 ? nil : warning;
8335 - (void) _endConnection:(NSURLConnection *)connection {
8336 // XXX: the memory management in this method is horribly awkward
8338 NSURLConnection **field = NULL;
8339 if (connection == trivial_bz2_)
8340 field = &trivial_bz2_;
8341 else if (connection == trivial_gz_)
8342 field = &trivial_gz_;
8343 _assert(field != NULL);
8344 [connection release];
8348 trivial_bz2_ == nil &&
8351 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8353 [delegate_ releaseNetworkActivityIndicator];
8355 [delegate_ removeProgressHUD:hud_];
8359 if (warning != nil) {
8360 UIAlertView *alert = [[[UIAlertView alloc]
8361 initWithTitle:UCLocalize("SOURCE_WARNING")
8364 cancelButtonTitle:UCLocalize("CANCEL")
8366 UCLocalize("ADD_ANYWAY"),
8370 [alert setContext:@"warning"];
8371 [alert setNumberOfRows:1];
8374 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8380 } else if (error_ != nil) {
8381 UIAlertView *alert = [[[UIAlertView alloc]
8382 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8383 message:[error_ localizedDescription]
8385 cancelButtonTitle:UCLocalize("OK")
8386 otherButtonTitles:nil
8389 [alert setContext:@"urlerror"];
8394 UIAlertView *alert = [[[UIAlertView alloc]
8395 initWithTitle:UCLocalize("NOT_REPOSITORY")
8396 message:UCLocalize("NOT_REPOSITORY_EX")
8398 cancelButtonTitle:UCLocalize("OK")
8399 otherButtonTitles:nil
8402 [alert setContext:@"trivial"];
8412 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8413 switch ([response statusCode]) {
8419 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8420 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8422 [self _endConnection:connection];
8425 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8426 [self _endConnection:connection];
8429 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8430 NSURL *url([NSURL URLWithString:href]);
8432 NSMutableURLRequest *request = [NSMutableURLRequest
8434 cachePolicy:NSURLRequestUseProtocolCachePolicy
8438 [request setHTTPMethod:method];
8440 if (Machine_ != NULL)
8441 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8443 if (UniqueID_ != nil)
8444 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8446 if ([url isCydiaSecure]) {
8447 if (UniqueID_ != nil)
8448 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8451 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8454 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8455 NSString *context([alert context]);
8457 if ([context isEqualToString:@"source"]) {
8460 NSString *href = [[alert textField] text];
8462 static Pcre href_r("^http(s?)://[^# ]*$");
8463 if (!href_r(href)) {
8464 UIAlertView *alert = [[[UIAlertView alloc]
8465 initWithTitle:Error_
8466 message:UCLocalize("INVALID_URL")
8468 cancelButtonTitle:UCLocalize("OK")
8469 otherButtonTitles:nil
8472 [alert setContext:@"badurl"];
8478 if (![href hasSuffix:@"/"])
8479 href_ = [href stringByAppendingString:@"/"];
8483 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8484 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8488 // XXX: this is stupid
8489 hud_ = [delegate_ addProgressHUD];
8490 [hud_ setText:UCLocalize("VERIFYING_URL")];
8491 [delegate_ retainNetworkActivityIndicator];
8500 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8501 } else if ([context isEqualToString:@"trivial"])
8502 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8503 else if ([context isEqualToString:@"urlerror"])
8504 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8505 else if ([context isEqualToString:@"warning"]) {
8508 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8517 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8521 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8522 BOOL editing([list_ isEditing]);
8525 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8526 initWithTitle:UCLocalize("ADD")
8527 style:UIBarButtonItemStylePlain
8529 action:@selector(addButtonClicked)
8530 ] autorelease] animated:animated];
8531 else if ([delegate_ updating])
8532 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8533 initWithTitle:UCLocalize("CANCEL")
8534 style:UIBarButtonItemStyleDone
8536 action:@selector(cancelButtonClicked)
8537 ] autorelease] animated:animated];
8539 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8540 initWithTitle:UCLocalize("REFRESH")
8541 style:UIBarButtonItemStylePlain
8543 action:@selector(refreshButtonClicked)
8544 ] autorelease] animated:animated];
8546 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8547 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8548 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8550 action:@selector(editButtonClicked)
8551 ] autorelease] animated:animated];
8555 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8556 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8557 [list_ setRowHeight:53];
8558 [(UITableView *) list_ setDataSource:self];
8559 [list_ setDelegate:self];
8560 [self setView:list_];
8563 - (void) viewDidLoad {
8564 [super viewDidLoad];
8566 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8567 [self updateButtonsForEditingStatusAnimated:NO];
8570 - (void) viewWillAppear:(BOOL)animated {
8571 [super viewWillAppear:animated];
8573 [list_ setEditing:NO];
8574 [self updateButtonsForEditingStatusAnimated:NO];
8577 - (void) releaseSubviews {
8582 [super releaseSubviews];
8585 - (id) initWithDatabase:(Database *)database {
8586 if ((self = [super init]) != nil) {
8587 database_ = database;
8591 - (void) reloadData {
8593 [self updateButtonsForEditingStatusAnimated:YES];
8595 @synchronized (database_) {
8596 era_ = [database_ era];
8598 sources_ = [NSMutableArray arrayWithCapacity:16];
8599 [sources_ addObjectsFromArray:[database_ sources]];
8601 [sources_ sortUsingSelector:@selector(compareByName:)];
8604 int count([sources_ count]);
8606 for (int i = 0; i != count; i++) {
8607 if ([[sources_ objectAtIndex:i] record] == nil)
8615 - (void) showAddSourcePrompt {
8616 UIAlertView *alert = [[[UIAlertView alloc]
8617 initWithTitle:UCLocalize("ENTER_APT_URL")
8620 cancelButtonTitle:UCLocalize("CANCEL")
8622 UCLocalize("ADD_SOURCE"),
8626 [alert setContext:@"source"];
8628 [alert setNumberOfRows:1];
8629 [alert addTextFieldWithValue:@"http://" label:@""];
8631 UITextInputTraits *traits = [[alert textField] textInputTraits];
8632 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8633 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8634 [traits setKeyboardType:UIKeyboardTypeURL];
8635 // XXX: UIReturnKeyDone
8636 [traits setReturnKeyType:UIReturnKeyNext];
8641 - (void) addButtonClicked {
8642 [self showAddSourcePrompt];
8645 - (void) refreshButtonClicked {
8646 if ([delegate_ requestUpdate])
8647 [self updateButtonsForEditingStatusAnimated:YES];
8650 - (void) cancelButtonClicked {
8651 [delegate_ cancelUpdate];
8654 - (void) editButtonClicked {
8655 [list_ setEditing:![list_ isEditing] animated:YES];
8656 [self updateButtonsForEditingStatusAnimated:YES];
8662 /* Stash Controller {{{ */
8663 @interface StashController : CyteViewController {
8664 _H<UIActivityIndicatorView> spinner_;
8665 _H<UILabel> status_;
8666 _H<UILabel> caption_;
8671 @implementation StashController
8674 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8675 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8676 [self setView:view];
8678 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8680 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8681 CGRect spinrect = [spinner_ frame];
8682 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8683 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8684 [spinner_ setFrame:spinrect];
8685 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8686 [view addSubview:spinner_];
8687 [spinner_ startAnimating];
8690 captrect.size.width = [[self view] frame].size.width;
8691 captrect.size.height = 40.0f;
8692 captrect.origin.x = 0;
8693 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8694 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8695 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8696 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8697 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8698 [caption_ setTextColor:[UIColor whiteColor]];
8699 [caption_ setBackgroundColor:[UIColor clearColor]];
8700 [caption_ setShadowColor:[UIColor blackColor]];
8701 [caption_ setTextAlignment:NSTextAlignmentCenter];
8702 [view addSubview:caption_];
8705 statusrect.size.width = [[self view] frame].size.width;
8706 statusrect.size.height = 30.0f;
8707 statusrect.origin.x = 0;
8708 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8709 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8710 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8711 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8712 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8713 [status_ setTextColor:[UIColor whiteColor]];
8714 [status_ setBackgroundColor:[UIColor clearColor]];
8715 [status_ setShadowColor:[UIColor blackColor]];
8716 [status_ setTextAlignment:NSTextAlignmentCenter];
8717 [view addSubview:status_];
8720 - (void) releaseSubviews {
8725 [super releaseSubviews];
8731 @interface CYURLCache : SDURLCache {
8736 @implementation CYURLCache
8738 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8741 else if ([event isEqualToString:@"no-cache"])
8743 else if ([event isEqualToString:@"store"])
8745 else if ([event isEqualToString:@"invalid"])
8747 else if ([event isEqualToString:@"memory"])
8749 else if ([event isEqualToString:@"disk"])
8751 else if ([event isEqualToString:@"miss"])
8754 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8758 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8759 if (NSURLResponse *response = [cached response])
8760 if (NSString *mime = [response MIMEType])
8761 if ([mime isEqualToString:@"text/cache-manifest"]) {
8762 NSURL *url([response URL]);
8765 NSLog(@"###: %@", [url absoluteString]);
8768 @synchronized (HostConfig_) {
8769 [CachedURLs_ addObject:url];
8773 [super storeCachedResponse:cached forRequest:request];
8778 @interface Cydia : UIApplication <
8779 ConfirmationControllerDelegate,
8782 UINavigationControllerDelegate,
8783 UITabBarControllerDelegate
8785 _H<UIWindow> window_;
8786 _H<CydiaTabBarController> tabbar_;
8787 _H<CydiaLoadingViewController> emulated_;
8789 _H<NSMutableArray> essential_;
8790 _H<NSMutableArray> broken_;
8792 Database *database_;
8794 _H<NSURL> starturl_;
8799 _H<StashController> stash_;
8808 @implementation Cydia
8810 - (void) lockSuspend {
8811 if (locked_++ == 0) {
8812 if ($SBSSetInterceptsMenuButtonForever != NULL)
8813 (*$SBSSetInterceptsMenuButtonForever)(true);
8815 [self setIdleTimerDisabled:YES];
8819 - (void) unlockSuspend {
8820 if (--locked_ == 0) {
8821 [self setIdleTimerDisabled:NO];
8823 if ($SBSSetInterceptsMenuButtonForever != NULL)
8824 (*$SBSSetInterceptsMenuButtonForever)(false);
8828 - (void) beginUpdate {
8829 [tabbar_ beginUpdate];
8832 - (void) cancelUpdate {
8833 [tabbar_ cancelUpdate];
8836 - (bool) requestUpdate {
8837 if (IsReachable("cydia.saurik.com")) {
8841 UIAlertView *alert = [[[UIAlertView alloc]
8842 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8843 message:@"Host Unreachable" // XXX: Localize
8845 cancelButtonTitle:UCLocalize("OK")
8846 otherButtonTitles:nil
8849 [alert setContext:@"norefresh"];
8857 return [tabbar_ updating];
8861 if ([broken_ count] != 0) {
8862 int count = [broken_ count];
8864 UIAlertView *alert = [[[UIAlertView alloc]
8865 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8866 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8868 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8870 UCLocalize("TEMPORARY_IGNORE"),
8874 [alert setContext:@"fixhalf"];
8875 [alert setNumberOfRows:2];
8877 } else if (!Ignored_ && [essential_ count] != 0) {
8878 int count = [essential_ count];
8880 UIAlertView *alert = [[[UIAlertView alloc]
8881 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8882 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8884 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8886 UCLocalize("UPGRADE_ESSENTIAL"),
8887 UCLocalize("COMPLETE_UPGRADE"),
8891 [alert setContext:@"upgrade"];
8896 - (void) returnToCydia {
8900 - (void) _saveConfig {
8901 @synchronized (database_) {
8908 NSString *error(nil);
8910 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8912 NSError *error(nil);
8913 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8914 NSLog(@"failure to save metadata data: %@", error);
8919 NSLog(@"failure to serialize metadata: %@", error);
8923 CydiaWriteSources();
8926 // Navigation controller for the queuing badge.
8927 - (UINavigationController *) queueNavigationController {
8928 NSArray *controllers = [tabbar_ viewControllers];
8929 return [controllers objectAtIndex:3];
8932 - (void) unloadData {
8933 [tabbar_ unloadData];
8936 - (void) _updateData {
8940 UINavigationController *navigation = [self queueNavigationController];
8942 id queuedelegate = nil;
8943 if ([[navigation viewControllers] count] > 0)
8944 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8946 [queuedelegate queueStatusDidChange];
8947 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8950 - (void) _refreshIfPossible:(NSDate *)update {
8951 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8953 bool recently = false;
8954 if (update != nil) {
8955 NSTimeInterval interval([update timeIntervalSinceNow]);
8956 if (interval <= 0 && interval > -(15*60))
8960 // Don't automatic refresh if:
8961 // - We already refreshed recently.
8962 // - We already auto-refreshed this launch.
8963 // - Auto-refresh is disabled.
8964 // - Cydia's server is not reachable
8965 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
8966 // If we are cancelling, we need to make sure it knows it's already loaded.
8969 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8971 // We are going to load, so remember that.
8974 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8980 - (void) refreshIfPossible {
8981 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8984 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8985 _profile(reloadDataWithInvocation)
8986 @synchronized (self) {
8987 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8989 [hud setText:UCLocalize("RELOADING_DATA")];
8991 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8995 [essential_ removeAllObjects];
8996 [broken_ removeAllObjects];
8998 _profile(reloadDataWithInvocation$Essential)
8999 NSArray *packages([database_ packages]);
9000 for (Package *package in packages) {
9002 [broken_ addObject:package];
9003 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9004 if ([package essential] && [package installed] != nil)
9005 [essential_ addObject:package];
9011 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9014 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9015 [changesItem setBadgeValue:badge];
9016 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9017 [self setApplicationIconBadgeNumber:changes];
9020 [changesItem setBadgeValue:nil];
9021 [changesItem setAnimatedBadge:NO];
9022 [self setApplicationIconBadgeNumber:0];
9028 [self removeProgressHUD:hud];
9035 - (void) updateData {
9039 - (void) updateDataAndLoad {
9041 if ([database_ progressDelegate] == nil)
9047 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9050 - (void) disemulate {
9051 if (emulated_ == nil)
9054 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9055 [window_ setRootViewController:tabbar_];
9057 [window_ addSubview:[tabbar_ view]];
9058 [[emulated_ view] removeFromSuperview];
9062 [window_ setUserInteractionEnabled:YES];
9065 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9066 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9068 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9070 UIViewController *parent;
9071 if (emulated_ == nil)
9080 [parent presentModalViewController:navigation animated:YES];
9083 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9084 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9086 if (navigation != nil)
9087 [navigation pushViewController:progress animated:YES];
9089 [self presentModalViewController:progress force:YES];
9091 [progress invoke:invocation withTitle:title];
9095 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9096 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9099 - (void) repairWithInvocation:(NSInvocation *)invocation {
9101 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9105 - (void) repairWithSelector:(SEL)selector {
9106 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9109 - (void) reloadData {
9110 [self reloadDataWithInvocation:nil];
9111 if ([database_ progressDelegate] == nil)
9117 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9120 - (void) addSource:(NSDictionary *) source {
9121 CydiaAddSource(source);
9124 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9125 CydiaAddSource(href, distribution, sections);
9128 - (void) addTrivialSource:(NSString *)href {
9129 CydiaAddSource(href, @"./");
9132 - (void) updateValues {
9137 pkgProblemResolver *resolver = [database_ resolver];
9139 resolver->InstallProtect();
9140 if (!resolver->Resolve(true))
9145 // XXX: this is a really crappy way of doing this.
9146 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9147 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9148 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9149 if ([tabbar_ updating])
9150 [tabbar_ cancelUpdate];
9152 if (![database_ prepare])
9155 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9156 [page setDelegate:self];
9157 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9160 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9161 [tabbar_ presentModalViewController:confirm_ animated:YES];
9167 @synchronized (self) {
9172 - (void) clearPackage:(Package *)package {
9173 @synchronized (self) {
9180 - (void) installPackages:(NSArray *)packages {
9181 @synchronized (self) {
9182 for (Package *package in packages)
9189 - (void) installPackage:(Package *)package {
9190 @synchronized (self) {
9197 - (void) removePackage:(Package *)package {
9198 @synchronized (self) {
9205 - (void) distUpgrade {
9206 @synchronized (self) {
9207 if (![database_ upgrade])
9215 system("su -c /usr/bin/uicache mobile");
9220 UIProgressHUD *hud([self addProgressHUD]);
9221 [hud setText:UCLocalize("LOADING")];
9222 [self yieldToSelector:@selector(_uicache)];
9223 [self removeProgressHUD:hud];
9227 [database_ perform];
9228 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9229 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9232 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9235 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9236 [self unlockSuspend];
9239 - (void) retainNetworkActivityIndicator {
9240 if (activity_++ == 0)
9241 [self setNetworkActivityIndicatorVisible:YES];
9244 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9248 - (void) releaseNetworkActivityIndicator {
9249 if (--activity_ == 0)
9250 [self setNetworkActivityIndicatorVisible:NO];
9253 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9258 - (void) cancelAndClear:(bool)clear {
9259 @synchronized (self) {
9271 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9272 NSString *context([alert context]);
9274 if ([context isEqualToString:@"conffile"]) {
9275 FILE *input = [database_ input];
9276 if (button == [alert cancelButtonIndex])
9277 fprintf(input, "N\n");
9278 else if (button == [alert firstOtherButtonIndex])
9279 fprintf(input, "Y\n");
9282 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9283 } else if ([context isEqualToString:@"fixhalf"]) {
9284 if (button == [alert cancelButtonIndex]) {
9285 @synchronized (self) {
9286 for (Package *broken in (id) broken_) {
9289 NSString *id = [broken id];
9290 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9291 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9292 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9293 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9299 } else if (button == [alert firstOtherButtonIndex]) {
9300 [broken_ removeAllObjects];
9304 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9305 } else if ([context isEqualToString:@"upgrade"]) {
9306 if (button == [alert firstOtherButtonIndex]) {
9307 @synchronized (self) {
9308 for (Package *essential in (id) essential_)
9309 [essential install];
9314 } else if (button == [alert firstOtherButtonIndex] + 1) {
9316 } else if (button == [alert cancelButtonIndex]) {
9320 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9324 - (void) system:(NSString *)command {
9325 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9328 system([command UTF8String]);
9334 - (void) applicationWillSuspend {
9336 [super applicationWillSuspend];
9339 - (BOOL) isSafeToSuspend {
9342 NSLog(@"isSafeToSuspend: locked_ != 0");
9347 if ([tabbar_ modalViewController] != nil)
9350 // Use external process status API internally.
9351 // This is probably a really bad idea.
9352 // XXX: what is the point of this? does this solve anything at all?
9353 uint64_t status = 0;
9355 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9356 notify_get_state(notify_token, &status);
9357 notify_cancel(notify_token);
9362 NSLog(@"isSafeToSuspend: status != 0");
9368 NSLog(@"isSafeToSuspend: -> true");
9373 - (void) applicationSuspend:(__GSEvent *)event {
9374 if ([self isSafeToSuspend])
9375 [super applicationSuspend:event];
9378 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9379 if ([self isSafeToSuspend])
9380 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9383 - (void) _setSuspended:(BOOL)value {
9384 if ([self isSafeToSuspend])
9385 [super _setSuspended:value];
9388 - (UIProgressHUD *) addProgressHUD {
9389 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9390 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9392 [window_ setUserInteractionEnabled:NO];
9394 UIViewController *target(tabbar_);
9395 if (UIViewController *modal = [target modalViewController])
9398 [hud showInView:[target view]];
9404 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9405 [self unlockSuspend];
9407 [hud removeFromSuperview];
9408 [window_ setUserInteractionEnabled:YES];
9411 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9412 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9415 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9416 NSString *scheme([[url scheme] lowercaseString]);
9417 if ([[url absoluteString] length] <= [scheme length] + 3)
9419 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9420 NSArray *components([path componentsSeparatedByString:@"/"]);
9422 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9423 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9424 if (controller != nil)
9425 [controller setDelegate:self];
9429 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9432 NSString *base([components objectAtIndex:0]);
9434 CyteViewController *controller = nil;
9436 if ([base isEqualToString:@"url"]) {
9437 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9438 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9439 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9440 } else if (!external && [components count] == 1) {
9441 if ([base isEqualToString:@"sources"]) {
9442 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9445 if ([base isEqualToString:@"home"]) {
9446 controller = [[[HomeController alloc] init] autorelease];
9449 if ([base isEqualToString:@"sections"]) {
9450 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9453 if ([base isEqualToString:@"search"]) {
9454 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9457 if ([base isEqualToString:@"changes"]) {
9458 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9461 if ([base isEqualToString:@"installed"]) {
9462 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9464 } else if ([components count] == 2) {
9465 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9467 if ([base isEqualToString:@"package"]) {
9468 controller = [self pageForPackage:argument withReferrer:referrer];
9471 if (!external && [base isEqualToString:@"search"]) {
9472 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9475 if (!external && [base isEqualToString:@"sections"]) {
9476 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9478 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9481 if (!external && [base isEqualToString:@"sources"]) {
9482 if ([argument isEqualToString:@"add"]) {
9483 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9484 [(SourcesController *)controller showAddSourcePrompt];
9486 Source *source([database_ sourceWithKey:argument]);
9487 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9491 if (!external && [base isEqualToString:@"launch"]) {
9492 [self launchApplicationWithIdentifier:argument suspended:NO];
9495 } else if (!external && [components count] == 3) {
9496 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9497 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9499 if ([base isEqualToString:@"package"]) {
9500 if ([arg2 isEqualToString:@"settings"]) {
9501 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9502 } else if ([arg2 isEqualToString:@"files"]) {
9503 if (Package *package = [database_ packageWithName:arg1]) {
9504 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9505 [(FileTable *)controller setPackage:package];
9510 if ([base isEqualToString:@"sections"]) {
9511 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9512 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9513 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9517 [controller setDelegate:self];
9521 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9522 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9525 [tabbar_ setUnselectedViewController:page];
9530 - (void) applicationOpenURL:(NSURL *)url {
9531 [super applicationOpenURL:url];
9536 [self openCydiaURL:url forExternal:YES];
9539 - (void) applicationWillResignActive:(UIApplication *)application {
9540 // Stop refreshing if you get a phone call or lock the device.
9541 if ([tabbar_ updating])
9542 [tabbar_ cancelUpdate];
9544 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9545 [super applicationWillResignActive:application];
9548 - (void) saveState {
9549 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9550 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9551 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9557 - (void) applicationWillTerminate:(UIApplication *)application {
9561 - (void) setConfigurationData:(NSString *)data {
9562 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9564 if (!conffile_r(data)) {
9565 lprintf("E:invalid conffile\n");
9569 NSString *ofile = conffile_r[1];
9570 //NSString *nfile = conffile_r[2];
9572 UIAlertView *alert = [[[UIAlertView alloc]
9573 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9574 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9576 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9578 UCLocalize("ACCEPT_NEW_COPY"),
9579 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9583 [alert setContext:@"conffile"];
9584 [alert setNumberOfRows:2];
9588 - (void) addStashController {
9590 stash_ = [[[StashController alloc] init] autorelease];
9591 [window_ addSubview:[stash_ view]];
9594 - (void) removeStashController {
9595 [[stash_ view] removeFromSuperview];
9597 [self unlockSuspend];
9601 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9602 UpdateExternalStatus(1);
9603 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9604 UpdateExternalStatus(0);
9606 [self removeStashController];
9608 pid_t pid(ExecFork());
9610 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9611 perror("launchctl stop");
9617 - (void) setupViewControllers {
9618 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9620 NSMutableArray *items;
9621 if (kCFCoreFoundationVersionNumber < 800) {
9622 items = [NSMutableArray arrayWithObjects:
9623 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9624 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9625 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9626 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease],
9627 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9630 items = [NSMutableArray arrayWithObjects:
9631 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home7.png"] selectedImage:[UIImage applicationImageNamed:@"home7s.png"]] autorelease],
9632 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install7.png"] selectedImage:[UIImage applicationImageNamed:@"install7s.png"]] autorelease],
9633 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes7.png"] selectedImage:[UIImage applicationImageNamed:@"changes7s.png"]] autorelease],
9634 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage7.png"] selectedImage:[UIImage applicationImageNamed:@"manage7s.png"]] autorelease],
9635 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search7.png"] selectedImage:[UIImage applicationImageNamed:@"search7s.png"]] autorelease],
9639 NSMutableArray *controllers([NSMutableArray array]);
9640 for (UITabBarItem *item in items) {
9641 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9642 [controller setTabBarItem:item];
9643 [controllers addObject:controller];
9645 [tabbar_ setViewControllers:controllers];
9647 [tabbar_ setUpdateDelegate:self];
9650 - (void) _sendMemoryWarningNotification {
9651 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9652 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9654 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9657 - (void) _sendMemoryWarningNotifications {
9659 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9665 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9667 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9670 - (void) applicationDidFinishLaunching:(id)unused {
9671 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9674 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9675 [self setApplicationSupportsShakeToEdit:NO];
9677 @synchronized (HostConfig_) {
9678 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9681 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9682 initWithMemoryCapacity:524288
9683 diskCapacity:10485760
9684 diskPath:[NSString stringWithFormat:@"%@/SDURLCache", Cache_]
9687 [CydiaWebViewController _initialize];
9689 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9691 // this would disallow http{,s} URLs from accessing this data
9692 //[WebView registerURLSchemeAsLocal:@"cydia"];
9694 Font12_ = [UIFont systemFontOfSize:12];
9695 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9696 Font14_ = [UIFont systemFontOfSize:14];
9697 Font18_ = [UIFont systemFontOfSize:18];
9698 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9699 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9701 essential_ = [NSMutableArray arrayWithCapacity:4];
9702 broken_ = [NSMutableArray arrayWithCapacity:4];
9704 // XXX: I really need this thing... like, seriously... I'm sorry
9705 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9707 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9708 [window_ orderFront:self];
9709 [window_ makeKey:self];
9710 [window_ setHidden:NO];
9713 [self addStashController];
9714 // XXX: this would be much cleaner as a yieldToSelector:
9715 // that way the removeStashController could happen right here inline
9716 // we also could no longer require the useless stash_ field anymore
9717 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9722 int error(stat("/", &root));
9723 _assert(error != -1);
9725 #define Stash_(path) do { \
9726 struct stat folder; \
9727 int error(lstat((path), &folder)); \
9728 if (error != -1 && ( \
9729 folder.st_dev == root.st_dev && \
9730 S_ISDIR(folder.st_mode) \
9731 ) || error == -1 && ( \
9732 errno == ENOENT || \
9737 Stash_("/Applications");
9738 Stash_("/Library/Ringtones");
9739 Stash_("/Library/Wallpaper");
9740 //Stash_("/usr/bin");
9741 Stash_("/usr/include");
9742 Stash_("/usr/lib/pam");
9743 Stash_("/usr/share");
9744 //Stash_("/var/lib");
9746 database_ = [Database sharedInstance];
9747 [database_ setDelegate:self];
9749 [window_ setUserInteractionEnabled:NO];
9750 [self setupViewControllers];
9752 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9753 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9754 [window_ setRootViewController:emulated_];
9756 [window_ addSubview:[emulated_ view]];
9758 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9762 - (NSArray *) defaultStartPages {
9763 NSMutableArray *standard = [NSMutableArray array];
9764 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9765 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9766 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9767 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9768 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9774 if ([emulated_ modalViewController] != nil)
9775 [emulated_ dismissModalViewControllerAnimated:YES];
9776 [window_ setUserInteractionEnabled:NO];
9778 [self reloadDataWithInvocation:nil];
9779 [self refreshIfPossible];
9782 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9783 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9784 int standardIndex = 0;
9785 NSArray *standard = [self defaultStartPages];
9792 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9793 if (valid && closed != nil) {
9794 NSTimeInterval interval([closed timeIntervalSinceNow]);
9795 // XXX: Is 30 minutes the optimal time here?
9796 if (interval <= -(30*60))
9800 if (valid && [saved count] != [standard count])
9804 for (unsigned int i = 0; i < [standard count]; i++) {
9805 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9806 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9807 // but it's good enough for now.
9808 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9815 NSArray *items = nil;
9817 [tabbar_ setSelectedIndex:savedIndex];
9820 [tabbar_ setSelectedIndex:standardIndex];
9824 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9825 NSArray *stack = [items objectAtIndex:tab];
9826 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9827 NSMutableArray *current = [NSMutableArray array];
9829 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9830 NSString *addr = [stack objectAtIndex:nav];
9831 NSURL *url = [NSURL URLWithString:addr];
9832 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9834 [current addObject:page];
9837 [navigation setViewControllers:current];
9840 // (Try to) show the startup URL.
9841 if (starturl_ != nil) {
9842 [self openCydiaURL:starturl_ forExternal:YES];
9847 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9848 if (item != nil && IsWildcat_) {
9849 [sheet showFromBarButtonItem:item animated:YES];
9851 [sheet showInView:window_];
9855 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9856 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9857 [progress setTitle:task];
9858 [progress addProgressEvent:event];
9861 - (void) addProgressEventForTask:(NSArray *)data {
9862 CydiaProgressEvent *event([data objectAtIndex:0]);
9863 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9864 [self addProgressEvent:event forTask:task];
9867 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9868 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9874 id Alloc_(id self, SEL selector) {
9875 id object = alloc_(self, selector);
9876 lprintf("[%s]A-%p\n", self->isa->name, object);
9881 id Dealloc_(id self, SEL selector) {
9882 id object = dealloc_(self, selector);
9883 lprintf("[%s]D-%p\n", self->isa->name, object);
9887 static NSSet *MobilizedFiles_;
9889 static NSURL *MobilizeURL(NSURL *url) {
9890 NSString *path([url path]);
9891 if ([path hasPrefix:@"/var/root/"]) {
9892 NSString *file([path substringFromIndex:10]);
9893 if ([MobilizedFiles_ containsObject:file])
9894 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9900 Class $CFXPreferencesPropertyListSource;
9901 @class CFXPreferencesPropertyListSource;
9903 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9904 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9905 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9907 url = MobilizeURL(url);
9909 value = _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd);
9910 //NSLog(@"CFX %@ %s", [url absoluteString], value ? "YES" : "NO");
9919 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9920 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9921 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9923 url = MobilizeURL(url);
9925 value = _CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd);
9926 //NSLog(@"CFX %@ %@", [url absoluteString], value);
9935 Class $NSURLConnection;
9937 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9938 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
9940 NSURL *url([copy URL]);
9942 NSString *host([url host]);
9943 NSString *scheme([[url scheme] lowercaseString]);
9945 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9947 @synchronized (HostConfig_) {
9948 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9949 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9950 [copy setHTTPShouldUsePipelining:YES];
9952 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9953 if ([control isEqualToString:@"max-age=0"])
9954 if ([CachedURLs_ containsObject:url]) {
9956 NSLog(@"~~~: %@", url);
9959 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9961 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9962 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9963 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9967 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9973 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
9974 CGSize size([[UIScreen mainScreen] bounds].size);
9975 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
9976 if ([$WAKWindow hasLandscapeOrientation])
9977 std::swap(size.width, size.height);*/
9981 Class $NSUserDefaults;
9983 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
9984 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
9985 return [NSString stringWithFormat:@"%@/LocalStorage", Cache_];
9986 return _NSUserDefaults$objectForKey$(self, _cmd, key);
9989 int main(int argc, char *argv[]) {
9990 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9994 UpdateExternalStatus(0);
9996 UIScreen *screen([UIScreen mainScreen]);
9997 if ([screen respondsToSelector:@selector(scale)])
9998 ScreenScale_ = [screen scale];
10002 UIDevice *device([UIDevice currentDevice]);
10003 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10004 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10005 if (idiom == UIUserInterfaceIdiomPad)
10009 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10011 Pcre pattern("^([0-9]+\\.[0-9]+)");
10013 if (pattern([device systemVersion]))
10014 Firmware_ = pattern[1];
10015 if (pattern(Cydia_))
10016 Major_ = pattern[1];
10018 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10020 HostConfig_ = [[[NSObject alloc] init] autorelease];
10021 @synchronized (HostConfig_) {
10022 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10023 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10024 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10025 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10026 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10029 NSString *ui(@"ui/ios");
10031 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10032 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10033 UI_ = CydiaURL(ui);
10035 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10037 MobilizedFiles_ = [NSMutableSet setWithObjects:
10038 @"Library/Preferences/.GlobalPreferences.plist",
10039 @"Library/Preferences/com.apple.Accessibility.plist",
10040 @"Library/Preferences/com.apple.preferences.sounds.plist",
10043 /* Library Hacks {{{ */
10044 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10046 $WAKWindow = objc_getClass("WAKWindow");
10047 if ($WAKWindow != NULL)
10048 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10049 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10051 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSourceSynchronizer");
10052 if ($CFXPreferencesPropertyListSource == Nil)
10053 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10055 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10056 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10057 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10058 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10061 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10062 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10063 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10064 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10067 $NSURLConnection = objc_getClass("NSURLConnection");
10068 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10069 if (NSURLConnection$init$ != NULL) {
10070 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10071 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10074 $NSUserDefaults = objc_getClass("NSUserDefaults");
10075 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10076 if (NSUserDefaults$objectForKey$ != NULL) {
10077 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10078 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10081 /* Set Locale {{{ */
10082 Locale_ = CFLocaleCopyCurrent();
10083 Languages_ = [NSLocale preferredLanguages];
10085 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10086 //NSLog(@"%@", [Languages_ description]);
10089 if (Locale_ != NULL)
10090 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10091 else if (Languages_ != nil && [Languages_ count] != 0)
10092 lang = [[Languages_ objectAtIndex:0] UTF8String];
10094 // XXX: consider just setting to C and then falling through?
10097 if (lang != NULL) {
10098 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10099 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10102 NSLog(@"Setting Language: %s", lang);
10104 if (lang != NULL) {
10105 setenv("LANG", lang, true);
10106 std::setlocale(LC_ALL, lang);
10109 /* Index Collation {{{ */
10110 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) {
10111 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10112 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10113 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10114 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10115 _H<UILocalizedIndexedCollation> collation([[[UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10117 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10119 CollationThumbs_ = [collation sectionIndexTitles];
10120 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10121 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10123 CollationTitles_ = [collation sectionTitles];
10124 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10126 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10127 if (&transform != NULL && transform != nil) {
10128 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10129 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10130 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10131 UErrorCode code(U_ZERO_ERROR);
10132 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10133 if (!U_SUCCESS(code))
10134 NSLog(@"%s", u_errorName(code));
10137 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10139 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];
10140 for (NSInteger offset(0); offset != 28; ++offset)
10141 CollationOffset_.push_back(offset);
10143 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];
10144 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];
10148 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10150 /* Parse Arguments {{{ */
10151 bool substrate(false);
10157 for (int argi(1); argi != argc; ++argi)
10158 if (strcmp(argv[argi], "--") == 0) {
10160 argv[argi] = argv[0];
10166 for (int argi(1); argi != arge; ++argi)
10167 if (strcmp(args[argi], "--substrate") == 0)
10170 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10174 App_ = [[NSBundle mainBundle] bundlePath];
10180 if (access("/var/mobile/Library/Keyboard/UserDictionary.sqlite", F_OK) == 0)
10181 system("mkdir -p /var/root/Library/Keyboard; cp -af /var/mobile/Library/Keyboard/UserDictionary.sqlite /var/root/Library/Keyboard/");
10183 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/root"] retain];
10185 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10186 alloc_ = alloc->method_imp;
10187 alloc->method_imp = (IMP) &Alloc_;*/
10189 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10190 dealloc_ = dealloc->method_imp;
10191 dealloc->method_imp = (IMP) &Dealloc_;*/
10193 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10194 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10196 /* System Information {{{ */
10200 size = sizeof(maxproc);
10201 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10202 perror("sysctlbyname(\"kern.maxproc\", ?)");
10203 else if (maxproc < 64) {
10205 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10206 perror("sysctlbyname(\"kern.maxproc\", #)");
10209 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10210 char *osversion = new char[size];
10211 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10212 perror("sysctlbyname(\"kern.osversion\", ?)");
10214 System_ = [NSString stringWithUTF8String:osversion];
10216 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10217 char *machine = new char[size];
10218 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10219 perror("sysctlbyname(\"hw.machine\", ?)");
10221 Machine_ = machine;
10223 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10224 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10225 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10227 UniqueID_ = UniqueIdentifier(device);
10229 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10230 Product_ = [info objectForKey:@"SafariProductVersion"];
10231 Safari_ = [info objectForKey:@"CFBundleVersion"];
10234 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10236 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10237 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10238 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10239 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10240 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10241 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10243 UserAgent_ = agent;
10245 /* Load Database {{{ */
10247 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10249 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10251 if (Metadata_ == NULL)
10252 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10254 Settings_ = [Metadata_ objectForKey:@"Settings"];
10256 Packages_ = [Metadata_ objectForKey:@"Packages"];
10258 Values_ = [Metadata_ objectForKey:@"Values"];
10259 Sections_ = [Metadata_ objectForKey:@"Sections"];
10260 Sources_ = [Metadata_ objectForKey:@"Sources"];
10262 Token_ = [Metadata_ objectForKey:@"Token"];
10264 Version_ = [Metadata_ objectForKey:@"Version"];
10267 if (Values_ == nil) {
10268 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10269 [Metadata_ setObject:Values_ forKey:@"Values"];
10272 if (Sections_ == nil) {
10273 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10274 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10277 if (Sources_ == nil) {
10278 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10279 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10282 if (Version_ == nil) {
10283 Version_ = [NSNumber numberWithUnsignedInt:0];
10284 [Metadata_ setObject:Version_ forKey:@"Version"];
10287 if ([Version_ unsignedIntValue] == 0) {
10288 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10289 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10290 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10291 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10293 Version_ = [NSNumber numberWithUnsignedInt:1];
10294 [Metadata_ setObject:Version_ forKey:@"Version"];
10296 [Metadata_ removeObjectForKey:@"LastUpdate"];
10301 _H<NSMutableArray> broken([NSMutableArray array]);
10302 for (NSString *key in (id) Sources_)
10303 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound)
10304 [broken addObject:key];
10305 if ([broken count] != 0) {
10306 for (NSString *key in (id) broken)
10307 [Sources_ removeObjectForKey:key];
10312 CydiaWriteSources();
10315 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10318 if (Packages_ != nil) {
10320 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10324 [Metadata_ removeObjectForKey:@"Packages"];
10330 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10332 #define MobileSubstrate_(name) \
10333 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10334 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10335 if (handle == NULL) \
10336 NSLog(@"%s", dlerror()); \
10339 MobileSubstrate_(Activator)
10340 MobileSubstrate_(libstatusbar)
10341 MobileSubstrate_(SimulatedKeyEvents)
10342 MobileSubstrate_(WinterBoard)
10344 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10345 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10347 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10349 if (access("/User", F_OK) != 0 || version != 6) {
10351 system("/usr/libexec/cydia/firmware.sh");
10355 _assert([[NSFileManager defaultManager]
10356 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10357 withIntermediateDirectories:YES
10362 if (access("/tmp/cydia.chk", F_OK) == 0) {
10363 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10364 _assert(errno == ENOENT);
10365 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10366 _assert(errno == ENOENT);
10369 /* APT Initialization {{{ */
10370 _assert(pkgInitConfig(*_config));
10371 _assert(pkgInitSystem(*_config, _system));
10374 _config->Set("APT::Acquire::Translation", lang);
10376 // XXX: this timeout might be important :(
10377 //_config->Set("Acquire::http::Timeout", 15);
10379 _config->Set("Acquire::http::MaxParallel", 3);
10381 /* Color Choices {{{ */
10382 space_ = CGColorSpaceCreateDeviceRGB();
10384 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10385 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10386 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10387 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10388 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10389 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10390 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10391 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10392 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10393 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10395 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10396 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10398 /* UIKit Configuration {{{ */
10399 // XXX: I have a feeling this was important
10400 //UIKeyboardDisableAutomaticAppearance();
10403 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10405 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10406 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10407 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10409 PulseInterval_ = fast ? 50000 : 500000;
10411 Colon_ = UCLocalize("COLON_DELIMITED");
10412 Elision_ = UCLocalize("ELISION");
10413 Error_ = UCLocalize("ERROR");
10414 Warning_ = UCLocalize("WARNING");
10417 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10419 CGColorSpaceRelease(space_);
10420 CFRelease(Locale_);