1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2015 Jay Freeman (saurik)
5 /* GNU General Public License, Version 3 {{{ */
7 * Cydia is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
12 * Cydia is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Cydia. If not, see <http://www.gnu.org/licenses/>.
22 // XXX: wtf/FastMalloc.h... wtf?
23 #define USE_SYSTEM_MALLOC 1
25 /* #include Directives {{{ */
26 #include "CyteKit/UCPlatform.h"
27 #include "CyteKit/Localize.h"
29 #include <unicode/ustring.h>
30 #include <unicode/utrans.h>
32 #include <objc/objc.h>
33 #include <objc/runtime.h>
35 #include <CoreGraphics/CoreGraphics.h>
36 #include <Foundation/Foundation.h>
39 #define DEPLOYMENT_TARGET_MACOSX 1
40 #define CF_BUILDING_CF 1
41 #include <CoreFoundation/CFInternal.h>
44 #include <CoreFoundation/CFUniChar.h>
46 #include <SystemConfiguration/SystemConfiguration.h>
48 #include <UIKit/UIKit.h>
49 #include "iPhonePrivate.h"
51 #include <IOKit/IOKitLib.h>
53 #include <QuartzCore/CALayer.h>
55 #include <WebCore/WebCoreThread.h>
56 #include <WebKit/DOMHTMLIFrameElement.h>
64 #include <ext/stdio_filebuf.h>
68 #include <apt-pkg/acquire.h>
69 #include <apt-pkg/acquire-item.h>
70 #include <apt-pkg/algorithms.h>
71 #include <apt-pkg/cachefile.h>
72 #include <apt-pkg/clean.h>
73 #include <apt-pkg/configuration.h>
74 #include <apt-pkg/debindexfile.h>
75 #include <apt-pkg/debmetaindex.h>
76 #include <apt-pkg/error.h>
77 #include <apt-pkg/init.h>
78 #include <apt-pkg/mmap.h>
79 #include <apt-pkg/pkgrecords.h>
80 #include <apt-pkg/sha1.h>
81 #include <apt-pkg/sourcelist.h>
82 #include <apt-pkg/sptr.h>
83 #include <apt-pkg/strutl.h>
84 #include <apt-pkg/tagfile.h>
86 #include <sys/types.h>
88 #include <sys/sysctl.h>
89 #include <sys/param.h>
90 #include <sys/mount.h>
91 #include <sys/reboot.h>
99 #include <mach-o/nlist.h>
108 #include <Cytore.hpp>
111 #include "Substrate.hpp"
112 #include "Menes/Menes.h"
114 #include "CyteKit/IndirectDelegate.h"
115 #include "CyteKit/RegEx.hpp"
116 #include "CyteKit/TableViewCell.h"
117 #include "CyteKit/TabBarController.h"
118 #include "CyteKit/WebScriptObject-Cyte.h"
119 #include "CyteKit/WebViewController.h"
120 #include "CyteKit/WebViewTableViewCell.h"
121 #include "CyteKit/stringWithUTF8Bytes.h"
123 #include "Cydia/MIMEAddress.h"
124 #include "Cydia/LoadingViewController.h"
125 #include "Cydia/ProgressEvent.h"
127 #include "SDURLCache/SDURLCache.h"
134 #define _timestamp ({ \
136 gettimeofday(&tv, NULL); \
137 tv.tv_sec * 1000000 + tv.tv_usec; \
140 typedef std::vector<class ProfileTime *> TimeList;
150 ProfileTime(const char *name) :
154 times_.push_back(this);
157 void AddTime(uint64_t time) {
164 std::cerr << std::setw(7) << count_ << ", " << std::setw(8) << total_ << " : " << name_ << std::endl;
176 ProfileTimer(ProfileTime &time) :
183 time_.AddTime(_timestamp - start_);
188 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
190 std::cerr << "========" << std::endl;
193 #define _profile(name) { \
194 static ProfileTime name(#name); \
195 ProfileTimer _ ## name(name);
200 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
201 #define synchronized(lock) \
202 synchronized(static_cast<NSObject *>(lock))
204 extern NSString *Cydia_;
206 #define lprintf(args...) fprintf(stderr, args)
209 #define TraceLogging (1 && !ForRelease)
210 #define HistogramInsertionSort (0 && !ForRelease)
211 #define ProfileTimes (0 && !ForRelease)
212 #define ForSaurik (0 && !ForRelease)
213 #define LogBrowser (0 && !ForRelease)
214 #define TrackResize (0 && !ForRelease)
215 #define ManualRefresh (1 && !ForRelease)
216 #define ShowInternals (0 && !ForRelease)
217 #define AlwaysReload (0 && !ForRelease)
221 #define _trace(args...)
226 #define _profile(name) {
229 #define PrintTimes() do {} while (false)
232 // Hash Functions/Structures {{{
233 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
241 static NSString *Colon_;
243 static NSString *Error_;
244 static NSString *Warning_;
246 static NSString *Cache_;
247 #define Cache(file) \
248 [NSString stringWithFormat:@"%@/%s", Cache_, file]
250 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
251 static NSData *(*$SBSCopyIconImagePNGDataForDisplayIdentifier)(NSString *);
253 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
255 static NSString *UniqueIdentifier(UIDevice *device = nil) {
256 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
257 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
259 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
262 static bool IsReachable(const char *name) {
263 SCNetworkReachabilityFlags flags; {
264 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
265 SCNetworkReachabilityGetFlags(reachability, &flags);
266 CFRelease(reachability);
269 // XXX: this elaborate mess is what Apple is using to determine this? :(
270 // XXX: do we care if the user has to intervene? maybe that's ok?
272 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
273 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
274 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
275 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
276 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
277 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
282 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
284 static _finline NSString *CydiaURL(NSString *path) {
286 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
287 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
288 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
289 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
290 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
292 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
295 static NSString *ShellEscape(NSString *value) {
296 return [NSString stringWithFormat:@"'%@'", [value stringByReplacingOccurrencesOfString:@"'" withString:@"'\\''"]];
299 static _finline void UpdateExternalStatus(uint64_t newStatus) {
301 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
302 notify_set_state(notify_token, newStatus);
303 notify_cancel(notify_token);
305 notify_post("com.saurik.Cydia.status");
308 static CGFloat CYStatusBarHeight() {
309 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
310 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
313 /* NSForcedOrderingSearch doesn't work on the iPhone */
314 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
315 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
316 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
318 /* Insertion Sort {{{ */
320 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
321 const char *ptr = (const char *)list;
323 CFIndex half = count / 2;
324 const char *probe = ptr + elementSize * half;
325 CFComparisonResult cr = comparator(element, probe, context);
326 if (0 == cr) return (probe - (const char *)list) / elementSize;
327 ptr = (cr < 0) ? ptr : probe + elementSize;
328 count = (cr < 0) ? half : (half + (count & 1) - 1);
330 return (ptr - (const char *)list) / elementSize;
333 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
334 const char *ptr = (const char *)list;
336 CFIndex half = count / 2;
337 const char *probe = ptr + elementSize * half;
338 CFComparisonResult cr = comparator(element, probe, context);
339 if (0 == cr) return (probe - (const char *)list) / elementSize;
340 ptr = (cr < 0) ? ptr : probe + elementSize;
341 count = (cr < 0) ? half : (half + (count & 1) - 1);
343 return (ptr - (const char *)list) / elementSize;
346 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
347 if (range.length == 0)
349 const void **values(new const void *[range.length]);
350 CFArrayGetValues(array, range, values);
352 #if HistogramInsertionSort > 0
353 uint32_t total(0), *offsets(new uint32_t[range.length]);
356 for (CFIndex index(1); index != range.length; ++index) {
357 const void *value(values[index]);
358 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
359 CFIndex correct(index);
360 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
361 #if HistogramInsertionSort > 1
362 NSLog(@"%@ < %@", value, values[correct - 1]);
367 if (correct != index) {
368 size_t offset(index - correct);
369 #if HistogramInsertionSort
373 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
375 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
376 values[correct] = value;
380 CFArrayReplaceValues(array, range, values, range.length);
383 #if HistogramInsertionSort > 0
384 for (CFIndex index(0); index != range.length; ++index)
385 if (offsets[index] != 0)
386 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
387 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
394 /* Apple Bug Fixes {{{ */
395 @implementation UIWebDocumentView (Cydia)
397 - (void) _setScrollerOffset:(CGPoint)offset {
398 UIScroller *scroller([self _scroller]);
400 CGSize size([scroller contentSize]);
401 CGSize bounds([scroller bounds].size);
404 max.x = size.width - bounds.width;
405 max.y = size.height - bounds.height;
413 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
414 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
416 [scroller setOffset:offset];
422 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
423 size_t length([self length] - state->state);
426 else if (length > count)
428 for (size_t i(0); i != length; ++i)
429 objects[i] = [self item:state->state++];
430 state->itemsPtr = objects;
431 state->mutationsPtr = (unsigned long *) self;
435 /* Cydia NSString Additions {{{ */
436 @interface NSString (Cydia)
437 - (NSComparisonResult) compareByPath:(NSString *)other;
438 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
441 @implementation NSString (Cydia)
443 - (NSComparisonResult) compareByPath:(NSString *)other {
444 NSString *prefix = [self commonPrefixWithString:other options:0];
445 size_t length = [prefix length];
447 NSRange lrange = NSMakeRange(length, [self length] - length);
448 NSRange rrange = NSMakeRange(length, [other length] - length);
450 lrange = [self rangeOfString:@"/" options:0 range:lrange];
451 rrange = [other rangeOfString:@"/" options:0 range:rrange];
453 NSComparisonResult value;
455 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
456 value = NSOrderedSame;
457 else if (lrange.location == NSNotFound)
458 value = NSOrderedAscending;
459 else if (rrange.location == NSNotFound)
460 value = NSOrderedDescending;
462 value = NSOrderedSame;
464 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
465 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
466 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
467 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
469 NSComparisonResult result = [lpath compare:rpath];
470 return result == NSOrderedSame ? value : result;
473 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
474 return [(id)CFURLCreateStringByAddingPercentEscapes(
479 kCFStringEncodingUTF8
486 /* C++ NSString Wrapper Cache {{{ */
487 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
488 return size == 0 ? NULL :
489 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
490 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
493 static _finline CFStringRef CYStringCreate(const char *data) {
494 return CYStringCreate(data, strlen(data));
503 _finline void clear_() {
504 if (cache_ != NULL) {
511 _finline bool empty() const {
515 _finline size_t size() const {
519 _finline char *data() const {
523 _finline void clear() {
528 _finline CYString() :
535 _finline ~CYString() {
539 void operator =(const CYString &rhs) {
543 if (rhs.cache_ == nil)
546 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
549 void copy(CYPool *pool) {
550 char *temp(pool->malloc<char>(size_ + 1));
551 memcpy(temp, data_, size_);
556 void set(CYPool *pool, const char *data, size_t size) {
562 data_ = const_cast<char *>(data);
570 _finline void set(CYPool *pool, const char *data) {
571 set(pool, data, data == NULL ? 0 : strlen(data));
574 _finline void set(CYPool *pool, const std::string &rhs) {
575 set(pool, rhs.data(), rhs.size());
578 bool operator ==(const CYString &rhs) const {
579 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
582 _finline operator CFStringRef() {
584 cache_ = CYStringCreate(data_, size_);
588 _finline operator id() {
589 return (NSString *) static_cast<CFStringRef>(*this);
592 _finline operator const char *() {
593 return reinterpret_cast<const char *>(data_);
597 /* C++ NSString Algorithm Adapters {{{ */
599 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
602 struct NSStringMapHash :
603 std::unary_function<NSString *, size_t>
605 _finline size_t operator ()(NSString *value) const {
606 return CFStringHashNSString((CFStringRef) value);
610 struct NSStringMapLess :
611 std::binary_function<NSString *, NSString *, bool>
613 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
614 return [lhs compare:rhs] == NSOrderedAscending;
618 struct NSStringMapEqual :
619 std::binary_function<NSString *, NSString *, bool>
621 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
622 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
623 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
624 //[lhs isEqualToString:rhs];
629 /* CoreGraphics Primitives {{{ */
634 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
635 CGFloat color[] = {red, green, blue, alpha};
636 return CGColorCreate(space, color);
645 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
646 color_(Create_(space, red, green, blue, alpha))
648 Set(space, red, green, blue, alpha);
653 CGColorRelease(color_);
660 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
662 color_ = Create_(space, red, green, blue, alpha);
665 operator CGColorRef() {
671 /* Random Global Variables {{{ */
672 static int PulseInterval_ = 500000;
674 static const NSString *UI_;
677 static bool RestartSubstrate_;
678 static NSArray *Finishes_;
680 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
681 #define NotifyConfig_ "/etc/notify.conf"
683 static bool Queuing_;
685 static CYColor Blue_;
686 static CYColor Blueish_;
687 static CYColor Black_;
688 static CYColor Folder_;
690 static CYColor White_;
691 static CYColor Gray_;
692 static CYColor Green_;
693 static CYColor Purple_;
694 static CYColor Purplish_;
696 static UIColor *InstallingColor_;
697 static UIColor *RemovingColor_;
699 static NSString *App_;
701 static BOOL Advanced_;
702 static BOOL Ignored_;
704 static _H<UIFont> Font12_;
705 static _H<UIFont> Font12Bold_;
706 static _H<UIFont> Font14_;
707 static _H<UIFont> Font18_;
708 static _H<UIFont> Font18Bold_;
709 static _H<UIFont> Font22Bold_;
711 static const char *Machine_ = NULL;
712 static _H<NSString> System_;
713 static NSString *SerialNumber_ = nil;
714 static NSString *ChipID_ = nil;
715 static NSString *BBSNum_ = nil;
716 static _H<NSString> UniqueID_;
717 static _H<NSString> UserAgent_;
718 static _H<NSString> Product_;
719 static _H<NSString> Safari_;
721 static _H<NSLocale> CollationLocale_;
722 static _H<NSArray> CollationThumbs_;
723 static std::vector<NSInteger> CollationOffset_;
724 static _H<NSArray> CollationTitles_;
725 static _H<NSArray> CollationStarts_;
726 static UTransliterator *CollationTransl_;
727 //static Function<NSString *, NSString *> CollationModify_;
729 typedef std::basic_string<UChar> ustring;
730 static ustring CollationString_;
732 #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
733 #define UC ustring &str(*reinterpret_cast<ustring *>(rep))
734 static struct UReplaceableCallbacks CollationUCalls_ = {
735 .length = [](const UReplaceable *rep) -> int32_t { CUC;
739 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
740 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
741 if (offset >= str.size())
746 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
747 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
748 if (offset >= str.size())
751 U16_GET(str.data(), 0, offset, str.size(), c);
755 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
756 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
757 str.replace(start, limit - start, text, length);
760 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
761 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
762 str.copy(dst, limit - start, start);
765 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
766 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
767 str.replace(dest, 0, str, start, limit - start);
771 static CFLocaleRef Locale_;
772 static NSArray *Languages_;
773 static CGColorSpaceRef space_;
775 #define CacheState_ "/var/mobile/Library/Caches/com.saurik.Cydia/CacheState.plist"
776 #define SavedState_ "/var/mobile/Library/Caches/com.saurik.Cydia/SavedState.plist"
778 static NSDictionary *SectionMap_;
779 static _H<NSDate> Backgrounded_;
780 static _transient NSMutableDictionary *Values_;
781 static _transient NSMutableDictionary *Sections_;
782 _H<NSMutableDictionary> Sources_;
783 static _transient NSNumber *Version_;
787 CGFloat ScreenScale_;
788 static NSString *Idiom_;
789 static _H<NSString> Firmware_;
790 static NSString *Major_;
792 static _H<NSMutableDictionary> SessionData_;
793 static _H<NSObject> HostConfig_;
794 static _H<NSMutableSet> BridgedHosts_;
795 static _H<NSMutableSet> InsecureHosts_;
796 static _H<NSMutableSet> PipelinedHosts_;
797 static _H<NSMutableSet> CachedURLs_;
799 static NSString *kCydiaProgressEventTypeError = @"Error";
800 static NSString *kCydiaProgressEventTypeInformation = @"Information";
801 static NSString *kCydiaProgressEventTypeStatus = @"Status";
802 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
805 /* Display Helpers {{{ */
806 inline float Interpolate(float begin, float end, float fraction) {
807 return (end - begin) * fraction + begin;
810 static inline double Retina(double value) {
811 value *= ScreenScale_;
812 value = round(value);
813 value /= ScreenScale_;
817 static inline CGRect Retina(CGRect value) {
818 value.origin.x *= ScreenScale_;
819 value.origin.y *= ScreenScale_;
820 value.size.width *= ScreenScale_;
821 value.size.height *= ScreenScale_;
822 value = CGRectIntegral(value);
823 value.origin.x /= ScreenScale_;
824 value.origin.y /= ScreenScale_;
825 value.size.width /= ScreenScale_;
826 value.size.height /= ScreenScale_;
830 static _finline const char *StripVersion_(const char *version) {
831 const char *colon(strchr(version, ':'));
832 return colon == NULL ? version : colon + 1;
835 NSString *LocalizeSection(NSString *section) {
836 static RegEx title_r("(.*?) \\((.*)\\)");
837 if (title_r(section)) {
838 NSString *parent(title_r[1]);
839 NSString *child(title_r[2]);
841 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
842 LocalizeSection(parent),
843 LocalizeSection(child)
847 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
850 NSString *Simplify(NSString *title) {
851 const char *data = [title UTF8String];
852 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
854 static RegEx square_r("\\[(.*)\\]");
855 if (square_r(data, size))
856 return Simplify(square_r[1]);
858 static RegEx paren_r("\\((.*)\\)");
859 if (paren_r(data, size))
860 return Simplify(paren_r[1]);
862 static RegEx title_r("(.*?) \\((.*)\\)");
863 if (title_r(data, size))
864 return Simplify(title_r[1]);
870 bool isSectionVisible(NSString *section) {
871 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
872 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
873 return hidden == nil || ![hidden boolValue];
876 static NSObject *CYIOGetValue(const char *path, NSString *property) {
877 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
878 if (entry == MACH_PORT_NULL)
881 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
882 IOObjectRelease(entry);
886 return [(id) value autorelease];
889 static NSString *CYHex(NSData *data, bool reverse = false) {
893 size_t length([data length]);
894 uint8_t bytes[length];
895 [data getBytes:bytes];
897 char string[length * 2 + 1];
898 for (size_t i(0); i != length; ++i)
899 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
901 return [NSString stringWithUTF8String:string];
904 static NSString *VerifySource(NSString *href) {
905 static RegEx href_r("(http(s?)://|file:///)[^# ]*");
907 [[[[UIAlertView alloc]
908 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
909 message:UCLocalize("INVALID_URL_EX")
911 cancelButtonTitle:UCLocalize("OK")
912 otherButtonTitles:nil
913 ] autorelease] show];
918 if (![href hasSuffix:@"/"])
919 href = [href stringByAppendingString:@"/"];
925 /* Delegate Prototypes {{{ */
928 @class CydiaProgressEvent;
930 @protocol DatabaseDelegate
931 - (void) repairWithSelector:(SEL)selector;
932 - (void) setConfigurationData:(NSString *)data;
933 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
936 @class CYPackageController;
938 @protocol SourceDelegate
939 - (void) setFetch:(NSNumber *)fetch;
942 @protocol FetchDelegate
943 - (bool) isSourceCancelled;
944 - (void) startSourceFetch:(NSString *)uri;
945 - (void) stopSourceFetch:(NSString *)uri;
948 @protocol CydiaDelegate
949 - (void) returnToCydia;
951 - (void) retainNetworkActivityIndicator;
952 - (void) releaseNetworkActivityIndicator;
953 - (void) clearPackage:(Package *)package;
954 - (void) installPackage:(Package *)package;
955 - (void) installPackages:(NSArray *)packages;
956 - (void) removePackage:(Package *)package;
957 - (void) beginUpdate;
959 - (bool) requestUpdate;
960 - (void) distUpgrade;
963 - (void) _saveConfig;
965 - (void) addSource:(NSDictionary *)source;
966 - (BOOL) addTrivialSource:(NSString *)href;
967 - (UIProgressHUD *) addProgressHUD;
968 - (void) removeProgressHUD:(UIProgressHUD *)hud;
969 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
970 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
974 /* CancelStatus {{{ */
976 public pkgAcquireStatus
987 virtual bool MediaChange(std::string media, std::string drive) {
991 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
995 virtual bool Pulse_(pkgAcquire *Owner) = 0;
997 virtual bool Pulse(pkgAcquire *Owner) {
998 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
1006 _finline bool WasCancelled() const {
1011 /* DelegateStatus {{{ */
1016 _transient NSObject<ProgressDelegate> *delegate_;
1024 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1025 delegate_ = delegate;
1028 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1029 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1030 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1031 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1034 virtual void Done(pkgAcquire::ItemDesc &desc) {
1035 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1036 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1037 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1040 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1042 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
1043 desc.Owner->Status == pkgAcquire::Item::StatDone
1047 std::string &error(desc.Owner->ErrorText);
1051 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
1052 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1055 virtual bool Pulse_(pkgAcquire *Owner) {
1057 double(CurrentBytes + CurrentItems) /
1058 double(TotalBytes + TotalItems)
1061 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1062 [NSNumber numberWithDouble:percent], @"Percent",
1064 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1065 [NSNumber numberWithDouble:TotalBytes], @"Total",
1066 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1067 nil] waitUntilDone:YES];
1069 return ![delegate_ isProgressCancelled];
1072 virtual void Start() {
1073 pkgAcquireStatus::Start();
1074 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1077 virtual void Stop() {
1078 pkgAcquireStatus::Stop();
1079 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1080 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1084 /* Database Interface {{{ */
1085 typedef std::map< unsigned long, _H<Source> > SourceMap;
1087 @interface Database : NSObject {
1094 pkgCacheFile cache_;
1095 pkgDepCache::Policy *policy_;
1096 pkgRecords *records_;
1097 pkgProblemResolver *resolver_;
1098 pkgAcquire *fetcher_;
1100 SPtr<pkgPackageManager> manager_;
1101 pkgSourceList *list_;
1103 SourceMap sourceMap_;
1104 _H<NSMutableArray> sourceList_;
1106 CFMutableArrayRef packages_;
1108 _transient NSObject<DatabaseDelegate> *delegate_;
1109 _transient NSObject<ProgressDelegate> *progress_;
1111 CydiaStatus status_;
1117 std::map<const char *, _H<NSString> > sections_;
1120 + (Database *) sharedInstance;
1123 - (void) _readCydia:(NSNumber *)fd;
1124 - (void) _readStatus:(NSNumber *)fd;
1125 - (void) _readOutput:(NSNumber *)fd;
1129 - (Package *) packageWithName:(NSString *)name;
1131 - (pkgCacheFile &) cache;
1132 - (pkgDepCache::Policy *) policy;
1133 - (pkgRecords *) records;
1134 - (pkgProblemResolver *) resolver;
1135 - (pkgAcquire &) fetcher;
1136 - (pkgSourceList &) list;
1137 - (NSArray *) packages;
1138 - (NSArray *) sources;
1139 - (Source *) sourceWithKey:(NSString *)key;
1140 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1148 - (void) updateWithStatus:(CancelStatus &)status;
1150 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1152 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1153 - (NSObject<ProgressDelegate> *) progressDelegate;
1155 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1156 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1157 - (void) resetFetch;
1159 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1163 /* SourceStatus {{{ */
1164 class SourceStatus :
1168 _transient NSObject<FetchDelegate> *delegate_;
1169 _transient Database *database_;
1170 std::set<std::string> fetches_;
1173 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1174 delegate_(delegate),
1179 void Set(bool fetch, const std::string &uri) {
1181 if (!fetches_.insert(uri).second)
1184 if (fetches_.erase(uri) == 0)
1188 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1189 [database_ setFetch:fetch forURI:uri.c_str()];
1192 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1193 /*unsigned long ID(fetch ? 1 : 0);
1197 Set(fetch, item->DescURI());
1200 void Log(const char *tag, pkgAcquire::Item *item) {
1201 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1204 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1205 Log("Fetch", desc.Owner);
1206 Set(true, desc.Owner);
1209 virtual void Done(pkgAcquire::ItemDesc &desc) {
1210 Log("Done", desc.Owner);
1211 Set(false, desc.Owner);
1214 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1215 Log("Fail", desc.Owner);
1216 Set(false, desc.Owner);
1219 virtual bool Pulse_(pkgAcquire *Owner) {
1220 std::set<std::string> fetches;
1221 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1223 if ((*item)->QueueCounter == 0)
1225 else switch ((*item)->Status) {
1226 case pkgAcquire::Item::StatFetching:
1227 fetches.insert((*item)->DescURI());
1236 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1240 std::vector<std::string> stops;
1241 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1242 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1243 //printf("Stop(%s)\n", stop->c_str());
1247 return ![delegate_ isSourceCancelled];
1250 virtual void Stop() {
1251 pkgAcquireStatus::Stop();
1252 [database_ resetFetch];
1256 /* ProgressEvent Implementation {{{ */
1257 @implementation CydiaProgressEvent
1259 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1260 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1263 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1264 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1265 [event setPackage:package];
1269 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1270 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1272 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1273 NSArray *fields([description componentsSeparatedByString:@" "]);
1274 [event setItem:fields];
1276 if ([fields count] > 3) {
1277 [event setPackage:[fields objectAtIndex:2]];
1278 [event setVersion:[fields objectAtIndex:3]];
1281 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1286 + (NSArray *) _attributeKeys {
1287 return [NSArray arrayWithObjects:
1297 - (NSArray *) attributeKeys {
1298 return [[self class] _attributeKeys];
1301 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1302 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1305 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1306 if ((self = [super init]) != nil) {
1312 - (NSString *) message {
1316 - (NSString *) type {
1320 - (NSArray *) item {
1321 return (id) item_ ?: [NSNull null];
1324 - (void) setItem:(NSArray *)item {
1328 - (NSString *) package {
1329 return (id) package_ ?: [NSNull null];
1332 - (void) setPackage:(NSString *)package {
1336 - (NSString *) url {
1337 return (id) url_ ?: [NSNull null];
1340 - (void) setURL:(NSString *)url {
1344 - (void) setVersion:(NSString *)version {
1348 - (NSString *) version {
1349 return (id) version_ ?: [NSNull null];
1352 - (NSString *) compound:(NSString *)value {
1354 NSString *mode(nil); {
1355 NSString *type([self type]);
1356 if ([type isEqualToString:kCydiaProgressEventTypeError])
1357 mode = UCLocalize("ERROR");
1358 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1359 mode = UCLocalize("WARNING");
1363 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1369 - (NSString *) compoundMessage {
1370 return [self compound:[self message]];
1373 - (NSString *) compoundTitle {
1376 if (package_ == nil)
1378 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1379 title = [package name];
1383 return [self compound:title];
1389 // Cytore Definitions {{{
1390 struct PackageValue :
1393 Cytore::Offset<PackageValue> next_;
1395 uint32_t index_ : 23;
1396 uint32_t subscribed_ : 1;
1413 Cytore::Offset<PackageValue> packages_[1 << 16];
1416 static Cytore::File<MetaValue> MetaFile_;
1418 // Cytore Helper Functions {{{
1419 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1420 SplitHash nhash = { hashlittle(name, length) };
1422 PackageValue *metadata;
1424 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1425 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1426 *offset = MetaFile_.New<PackageValue>(length + 1);
1427 metadata = &MetaFile_.Get(*offset);
1429 if (metadata == NULL) {
1433 metadata = new PackageValue();
1434 memset(metadata, 0, sizeof(*metadata));
1437 memcpy(metadata->name_, name, length);
1438 metadata->name_[length] = '\0';
1439 metadata->nhash_ = nhash.u16[1];
1441 metadata = &MetaFile_.Get(*offset);
1442 if (metadata->nhash_ != nhash.u16[1])
1444 if (strncmp(metadata->name_, name, length) != 0)
1446 if (metadata->name_[length] != '\0')
1453 static void PackageImport(const void *key, const void *value, void *context) {
1454 bool &fail(*reinterpret_cast<bool *>(context));
1457 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1458 NSLog(@"failed to import package %@", key);
1462 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1463 NSDictionary *package((NSDictionary *) value);
1465 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1466 if ([subscribed boolValue] && !metadata->subscribed_)
1467 metadata->subscribed_ = true;
1469 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1470 time_t time([date timeIntervalSince1970]);
1471 if (metadata->first_ > time || metadata->first_ == 0)
1472 metadata->first_ = time;
1475 NSDate *date([package objectForKey:@"LastSeen"]);
1476 NSString *version([package objectForKey:@"LastVersion"]);
1478 if (date != nil && version != nil) {
1479 time_t time([date timeIntervalSince1970]);
1480 if (metadata->last_ < time || metadata->last_ == 0)
1481 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1482 size_t length(strlen(buffer));
1483 uint16_t vhash(hashlittle(buffer, length));
1485 size_t capped(std::min<size_t>(8, length));
1486 char *latest(buffer + length - capped);
1488 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1489 metadata->vhash_ = vhash;
1491 metadata->last_ = time;
1497 static NSDate *GetStatusDate() {
1498 return [[[NSFileManager defaultManager] attributesOfItemAtPath:@"/var/lib/dpkg/status" error:NULL] fileModificationDate];
1501 static void SaveConfig(NSObject *lock) {
1502 @synchronized (lock) {
1508 CFPreferencesSetMultiple((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
1509 Values_, @"CydiaValues",
1510 Sections_, @"CydiaSections",
1511 (id) Sources_, @"CydiaSources",
1512 Version_, @"CydiaVersion",
1513 nil], NULL, CFSTR("com.saurik.Cydia"), kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
1515 if (!CFPreferencesAppSynchronize(CFSTR("com.saurik.Cydia")))
1516 NSLog(@"CFPreferencesAppSynchronize(com.saurik.Cydia) == false");
1518 CydiaWriteSources();
1521 /* Source Class {{{ */
1522 @interface Source : NSObject {
1524 Database *database_;
1527 CYString depiction_;
1528 CYString description_;
1534 CYString distribution_;
1540 _H<NSString> authority_;
1542 CYString defaultIcon_;
1544 _H<NSMutableDictionary> record_;
1547 std::set<std::string> fetches_;
1548 std::set<std::string> files_;
1549 _transient NSObject<SourceDelegate> *delegate_;
1552 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool;
1554 - (NSComparisonResult) compareByName:(Source *)source;
1556 - (NSString *) depictionForPackage:(NSString *)package;
1557 - (NSString *) supportForPackage:(NSString *)package;
1559 - (metaIndex *) metaIndex;
1560 - (NSDictionary *) record;
1563 - (NSString *) rooturi;
1564 - (NSString *) distribution;
1565 - (NSString *) type;
1568 - (NSString *) host;
1570 - (NSString *) name;
1571 - (NSString *) shortDescription;
1572 - (NSString *) label;
1573 - (NSString *) origin;
1574 - (NSString *) version;
1576 - (NSString *) defaultIcon;
1577 - (NSURL *) iconURL;
1579 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1580 - (void) resetFetch;
1584 @implementation Source
1586 + (NSString *) webScriptNameForSelector:(SEL)selector {
1588 else if (selector == @selector(addSection:))
1589 return @"addSection";
1590 else if (selector == @selector(getField:))
1592 else if (selector == @selector(removeSection:))
1593 return @"removeSection";
1594 else if (selector == @selector(remove))
1600 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1601 return [self webScriptNameForSelector:selector] == nil;
1604 + (NSArray *) _attributeKeys {
1605 return [NSArray arrayWithObjects:
1616 @"shortDescription",
1623 - (NSArray *) attributeKeys {
1624 return [[self class] _attributeKeys];
1627 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1628 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1631 - (metaIndex *) metaIndex {
1635 - (void) setMetaIndex:(metaIndex *)index inPool:(CYPool *)pool {
1636 trusted_ = index->IsTrusted();
1638 uri_.set(pool, index->GetURI());
1639 distribution_.set(pool, index->GetDist());
1640 type_.set(pool, index->GetType());
1642 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1643 if (dindex != NULL) {
1644 std::string file(dindex->MetaIndexURI(""));
1645 base_.set(pool, file);
1648 _profile(Source$setMetaIndex$GetIndexes)
1649 dindex->GetIndexes(&acquire, true);
1651 _profile(Source$setMetaIndex$DescURI)
1652 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1653 std::string file((*item)->DescURI());
1654 files_.insert(file);
1655 if (file.length() < sizeof("Packages.bz2") || file.substr(file.length() - sizeof("Packages.bz2")) != "/Packages.bz2")
1657 file = file.substr(0, file.length() - 4);
1658 files_.insert(file);
1659 files_.insert(file + ".gz");
1660 files_.insert(file + "Index");
1665 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1668 pkgTagFile tags(&fd);
1670 pkgTagSection section;
1677 {"default-icon", &defaultIcon_},
1678 {"depiction", &depiction_},
1679 {"description", &description_},
1681 {"origin", &origin_},
1682 {"support", &support_},
1683 {"version", &version_},
1686 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1687 const char *start, *end;
1689 if (section.Find(names[i].name_, start, end)) {
1690 CYString &value(*names[i].value_);
1691 value.set(pool, start, end - start);
1697 record_ = [Sources_ objectForKey:[self key]];
1699 NSURL *url([NSURL URLWithString:uri_]);
1703 host_ = [host_ lowercaseString];
1708 authority_ = [url path];
1711 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool {
1712 if ((self = [super init]) != nil) {
1713 era_ = [database era];
1714 database_ = database;
1717 _profile(Source$initWithMetaIndex$setMetaIndex)
1718 [self setMetaIndex:index inPool:pool];
1723 - (NSString *) getField:(NSString *)name {
1724 @synchronized (database_) {
1725 if ([database_ era] != era_ || index_ == NULL)
1728 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1733 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1738 pkgTagFile tags(&fd);
1740 pkgTagSection section;
1743 const char *start, *end;
1744 if (!section.Find([name UTF8String], start, end))
1745 return (NSString *) [NSNull null];
1747 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1750 - (NSComparisonResult) compareByName:(Source *)source {
1751 NSString *lhs = [self name];
1752 NSString *rhs = [source name];
1754 if ([lhs length] != 0 && [rhs length] != 0) {
1755 unichar lhc = [lhs characterAtIndex:0];
1756 unichar rhc = [rhs characterAtIndex:0];
1758 if (isalpha(lhc) && !isalpha(rhc))
1759 return NSOrderedAscending;
1760 else if (!isalpha(lhc) && isalpha(rhc))
1761 return NSOrderedDescending;
1764 return [lhs compare:rhs options:LaxCompareOptions_];
1767 - (NSString *) depictionForPackage:(NSString *)package {
1768 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1771 - (NSString *) supportForPackage:(NSString *)package {
1772 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1775 - (NSArray *) sections {
1776 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1779 - (void) _addSection:(NSString *)section {
1782 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1783 if (![sections containsObject:section])
1784 [sections addObject:section];
1786 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1789 - (bool) addSection:(NSString *)section {
1793 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1797 - (void) _removeSection:(NSString *)section {
1801 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1802 if ([sections containsObject:section])
1803 [sections removeObject:section];
1806 - (bool) removeSection:(NSString *)section {
1810 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1815 [Sources_ removeObjectForKey:[self key]];
1819 bool value(record_ != nil);
1820 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1824 - (NSDictionary *) record {
1832 - (NSString *) rooturi {
1836 - (NSString *) distribution {
1837 return distribution_;
1840 - (NSString *) type {
1844 - (NSString *) baseuri {
1845 return base_.empty() ? nil : (id) base_;
1848 - (NSString *) iconuri {
1849 if (NSString *base = [self baseuri])
1850 return [base stringByAppendingString:@"CydiaIcon.png"];
1855 - (NSURL *) iconURL {
1856 if (NSString *uri = [self iconuri])
1857 return [NSURL URLWithString:uri];
1861 - (NSString *) key {
1862 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1865 - (NSString *) host {
1869 - (NSString *) name {
1870 return origin_.empty() ? (id) authority_ : origin_;
1873 - (NSString *) shortDescription {
1874 return description_;
1877 - (NSString *) label {
1878 return label_.empty() ? (id) authority_ : label_;
1881 - (NSString *) origin {
1885 - (NSString *) version {
1889 - (NSString *) defaultIcon {
1890 return defaultIcon_;
1893 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1894 delegate_ = delegate;
1898 return !fetches_.empty();
1901 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1903 if (fetches_.erase(uri) == 0)
1905 } else if (files_.find(uri) == files_.end())
1907 else if (!fetches_.insert(uri).second)
1910 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1913 - (void) resetFetch {
1915 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1920 /* CydiaOperation Class {{{ */
1921 @interface CydiaOperation : NSObject {
1922 _H<NSString> operator_;
1923 _H<NSString> value_;
1926 - (NSString *) operator;
1927 - (NSString *) value;
1931 @implementation CydiaOperation
1933 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1934 if ((self = [super init]) != nil) {
1935 operator_ = [NSString stringWithUTF8String:_operator];
1936 value_ = [NSString stringWithUTF8String:value];
1940 + (NSArray *) _attributeKeys {
1941 return [NSArray arrayWithObjects:
1947 - (NSArray *) attributeKeys {
1948 return [[self class] _attributeKeys];
1951 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1952 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1955 - (NSString *) operator {
1959 - (NSString *) value {
1965 /* CydiaClause Class {{{ */
1966 @interface CydiaClause : NSObject {
1967 _H<NSString> package_;
1968 _H<CydiaOperation> version_;
1971 - (NSString *) package;
1972 - (CydiaOperation *) version;
1976 @implementation CydiaClause
1978 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1979 if ((self = [super init]) != nil) {
1980 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1982 if (const char *version = dep.TargetVer())
1983 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1985 version_ = (id) [NSNull null];
1989 + (NSArray *) _attributeKeys {
1990 return [NSArray arrayWithObjects:
1996 - (NSArray *) attributeKeys {
1997 return [[self class] _attributeKeys];
2000 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2001 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2004 - (NSString *) package {
2008 - (CydiaOperation *) version {
2014 /* CydiaRelation Class {{{ */
2015 @interface CydiaRelation : NSObject {
2016 _H<NSString> relationship_;
2017 _H<NSMutableArray> clauses_;
2020 - (NSString *) relationship;
2021 - (NSArray *) clauses;
2025 @implementation CydiaRelation
2027 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2028 if ((self = [super init]) != nil) {
2029 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
2030 clauses_ = [NSMutableArray arrayWithCapacity:8];
2032 pkgCache::DepIterator start;
2033 pkgCache::DepIterator end;
2034 dep.GlobOr(start, end); // ++dep
2037 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2039 // yes, seriously. (wtf?)
2047 + (NSArray *) _attributeKeys {
2048 return [NSArray arrayWithObjects:
2054 - (NSArray *) attributeKeys {
2055 return [[self class] _attributeKeys];
2058 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2059 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2062 - (NSString *) relationship {
2063 return relationship_;
2066 - (NSArray *) clauses {
2070 - (void) addClause:(CydiaClause *)clause {
2071 [clauses_ addObject:clause];
2076 /* Package Class {{{ */
2077 struct ParsedPackage {
2081 CYString architecture_;
2084 CYString depiction_;
2091 @interface Package : NSObject {
2093 @public uint32_t role_ : 3;
2094 uint32_t essential_ : 1;
2095 uint32_t obsolete_ : 1;
2096 uint32_t ignored_ : 1;
2097 uint32_t pooled_ : 1;
2103 _transient Database *database_;
2105 pkgCache::VerIterator version_;
2106 pkgCache::PkgIterator iterator_;
2107 pkgCache::VerFileIterator file_;
2111 CYString transform_;
2114 CYString installed_;
2117 const char *section_;
2118 _transient NSString *section$_;
2122 PackageValue *metadata_;
2123 ParsedPackage *parsed_;
2125 _H<NSMutableArray> tags_;
2128 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2129 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2131 - (pkgCache::PkgIterator) iterator;
2134 - (NSString *) section;
2135 - (NSString *) simpleSection;
2137 - (NSString *) longSection;
2138 - (NSString *) shortSection;
2142 - (MIMEAddress *) maintainer;
2144 - (NSString *) longDescription;
2145 - (NSString *) shortDescription;
2148 - (PackageValue *) metadata;
2151 - (bool) subscribed;
2152 - (bool) setSubscribed:(bool)subscribed;
2156 - (NSString *) latest;
2157 - (NSString *) installed;
2158 - (BOOL) uninstalled;
2160 - (BOOL) upgradableAndEssential:(BOOL)essential;
2163 - (BOOL) unfiltered;
2167 - (BOOL) halfConfigured;
2168 - (BOOL) halfInstalled;
2170 - (NSString *) mode;
2173 - (NSString *) name;
2175 - (NSString *) homepage;
2176 - (NSString *) depiction;
2177 - (MIMEAddress *) author;
2179 - (NSString *) support;
2181 - (NSArray *) files;
2182 - (NSArray *) warnings;
2183 - (NSArray *) applications;
2185 - (Source *) source;
2188 - (BOOL) matches:(NSArray *)query;
2190 - (BOOL) hasTag:(NSString *)tag;
2191 - (NSString *) primaryPurpose;
2192 - (NSArray *) purposes;
2193 - (bool) isCommercial;
2195 - (void) setIndex:(size_t)index;
2197 - (CYString &) cyname;
2199 - (uint32_t) compareBySection:(NSArray *)sections;
2206 uint32_t PackageChangesRadix(Package *self, void *) {
2211 uint32_t timestamp : 30;
2212 uint32_t ignored : 1;
2213 uint32_t upgradable : 1;
2217 bool upgradable([self upgradableAndEssential:YES]);
2218 value.bits.upgradable = upgradable ? 1 : 0;
2221 value.bits.timestamp = 0;
2222 value.bits.ignored = [self ignored] ? 0 : 1;
2223 value.bits.upgradable = 1;
2225 value.bits.timestamp = [self seen] >> 2;
2226 value.bits.ignored = 0;
2227 value.bits.upgradable = 0;
2230 return _not(uint32_t) - value.key;
2233 CYString &(*PackageName)(Package *self, SEL sel);
2235 uint32_t PackagePrefixRadix(Package *self, void *context) {
2236 size_t offset(reinterpret_cast<size_t>(context));
2237 CYString &name(PackageName(self, @selector(cyname)));
2239 size_t size(name.size());
2242 char *text(name.data());
2245 if (!isdigit(text[0]))
2249 while (size != digits && isdigit(text[digits]))
2257 if (offset == 0 && zeros != 0) {
2258 memset(data, '0', zeros);
2259 memcpy(data + zeros, text, 4 - zeros);
2261 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2262 if (size <= offset - zeros)
2265 text += offset - zeros;
2266 size -= offset - zeros;
2269 memcpy(data, text, 4);
2271 memcpy(data, text, size);
2272 memset(data + size, 0, 4 - size);
2275 for (size_t i(0); i != 4; ++i)
2276 if (isalpha(data[i]))
2284 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2286 /* XXX: ntohl may be more honest */
2287 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2290 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2291 _profile(PackageNameCompare)
2293 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2294 else if (rhn == NULL)
2295 return kCFCompareGreaterThan;
2297 CFIndex length(CFStringGetLength(lhn));
2299 _profile(PackageNameCompare$NumbersLast)
2300 if (length != 0 && CFStringGetLength(rhn) != 0) {
2301 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2302 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2303 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2304 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2305 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2309 _profile(PackageNameCompare$Compare)
2310 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2315 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2316 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2319 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2320 CYString &lhn(PackageName(lhs, @selector(cyname)));
2321 NSString *rhn(PackageName(rhs, @selector(cyname)));
2322 return StringNameCompare(lhn, rhn, lhn.size());
2325 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2326 return PackageNameCompare(*lhs, *rhs, arg);
2329 struct PackageNameOrdering :
2330 std::binary_function<Package *, Package *, bool>
2332 _finline bool operator ()(Package *lhs, Package *rhs) const {
2333 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2337 @implementation Package
2339 - (NSString *) description {
2340 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2346 if (parsed_ != NULL)
2351 + (NSString *) webScriptNameForSelector:(SEL)selector {
2353 else if (selector == @selector(clear))
2355 else if (selector == @selector(getField:))
2357 else if (selector == @selector(getRecord))
2358 return @"getRecord";
2359 else if (selector == @selector(hasTag:))
2361 else if (selector == @selector(install))
2363 else if (selector == @selector(remove))
2369 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2370 return [self webScriptNameForSelector:selector] == nil;
2373 + (NSArray *) _attributeKeys {
2374 return [NSArray arrayWithObjects:
2395 @"shortDescription",
2408 - (NSArray *) attributeKeys {
2409 return [[self class] _attributeKeys];
2412 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2413 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2416 - (NSArray *) relations {
2417 @synchronized (database_) {
2418 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2419 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2420 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2424 - (NSString *) architecture {
2426 @synchronized (database_) {
2427 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2430 - (NSString *) getField:(NSString *)name {
2431 @synchronized (database_) {
2432 if ([database_ era] != era_ || file_.end())
2435 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2437 const char *start, *end;
2438 if (!parser.Find([name UTF8String], start, end))
2439 return (NSString *) [NSNull null];
2441 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2444 - (NSString *) getRecord {
2445 @synchronized (database_) {
2446 if ([database_ era] != era_ || file_.end())
2449 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2451 const char *start, *end;
2452 parser.GetRec(start, end);
2454 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2458 if (parsed_ != NULL)
2460 @synchronized (database_) {
2461 if ([database_ era] != era_ || file_.end())
2464 ParsedPackage *parsed(new ParsedPackage);
2467 _profile(Package$parse)
2468 pkgRecords::Parser *parser;
2470 _profile(Package$parse$Lookup)
2471 parser = &[database_ records]->Lookup(file_);
2477 _profile(Package$parse$Find)
2482 {"architecture", &parsed->architecture_},
2483 {"icon", &parsed->icon_},
2484 {"depiction", &parsed->depiction_},
2485 {"homepage", &parsed->homepage_},
2486 {"website", &website},
2488 {"support", &parsed->support_},
2489 {"author", &parsed->author_},
2490 {"md5sum", &parsed->md5sum_},
2493 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2494 const char *start, *end;
2496 if (parser->Find(names[i].name_, start, end)) {
2497 CYString &value(*names[i].value_);
2498 _profile(Package$parse$Value)
2499 value.set(pool_, start, end - start);
2505 _profile(Package$parse$Tagline)
2506 const char *start, *end;
2507 if (parser->ShortDesc(start, end)) {
2508 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2511 while (stop != start && stop[-1] == '\r')
2513 parsed->tagline_.set(pool_, start, stop - start);
2517 _profile(Package$parse$Retain)
2518 if (parsed->homepage_.empty())
2519 parsed->homepage_ = website;
2520 if (parsed->homepage_ == parsed->depiction_)
2521 parsed->homepage_.clear();
2522 if (parsed->support_.empty())
2523 parsed->support_ = bugs;
2528 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2529 if ((self = [super init]) != nil) {
2530 _profile(Package$initWithVersion)
2532 pool_ = new CYPool();
2538 database_ = database;
2539 era_ = [database era];
2543 pkgCache::PkgIterator iterator(version.ParentPkg());
2544 iterator_ = iterator;
2546 _profile(Package$initWithVersion$Version)
2547 file_ = version_.FileList();
2550 _profile(Package$initWithVersion$Cache)
2551 name_.set(NULL, iterator.Display());
2553 latest_.set(NULL, StripVersion_(version_.VerStr()));
2555 pkgCache::VerIterator current(iterator.CurrentVer());
2557 installed_.set(NULL, StripVersion_(current.VerStr()));
2560 _profile(Package$initWithVersion$Transliterate) do {
2561 if (CollationTransl_ == NULL)
2566 _profile(Package$initWithVersion$Transliterate$utf8)
2567 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2568 for (size_t i(0), e(name_.size()); i != e; ++i)
2569 if (data[i] >= 0x80)
2574 UErrorCode code(U_ZERO_ERROR);
2577 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2578 CollationString_.resize(name_.size());
2579 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2580 if (!U_SUCCESS(code))
2582 CollationString_.resize(length);
2585 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2586 length = CollationString_.size();
2587 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2588 if (!U_SUCCESS(code))
2590 _assert(CollationString_.size() == length);
2593 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2594 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2595 if (code == U_BUFFER_OVERFLOW_ERROR)
2596 code = U_ZERO_ERROR;
2597 else if (!U_SUCCESS(code))
2602 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2603 transform = pool_->malloc<char>(length);
2605 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2606 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2607 if (!U_SUCCESS(code))
2611 transform_.set(NULL, transform, length);
2612 } while (false); _end
2614 _profile(Package$initWithVersion$Tags)
2615 pkgCache::TagIterator tag(iterator.TagList());
2617 tags_ = [NSMutableArray arrayWithCapacity:8];
2619 goto tag; for (; !tag.end(); ++tag) tag: {
2620 const char *name(tag.Name());
2621 NSString *string((NSString *) CYStringCreate(name));
2625 [tags_ addObject:[string autorelease]];
2627 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2628 if (strcmp(name + 6, "enduser") == 0)
2630 else if (strcmp(name + 6, "hacker") == 0)
2632 else if (strcmp(name + 6, "developer") == 0)
2634 else if (strcmp(name + 6, "cydia") == 0)
2640 if (strncmp(name, "cydia::", 7) == 0) {
2641 if (strcmp(name + 7, "essential") == 0)
2643 else if (strcmp(name + 7, "obsolete") == 0)
2650 _profile(Package$initWithVersion$Metadata)
2651 const char *mixed(iterator.Name());
2652 size_t size(strlen(mixed));
2653 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2654 char lower[prefix + size + 5 + 1];
2656 for (size_t i(0); i != size; ++i)
2657 lower[prefix + i] = mixed[i] | 0x20;
2659 if (!installed_.empty()) {
2660 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2661 memcpy(lower + prefix + size, ".list", 6);
2663 if (stat(lower, &info) != -1)
2664 upgraded_ = info.st_birthtime;
2667 PackageValue *metadata(PackageFind(lower + prefix, size));
2668 metadata_ = metadata;
2670 id_.set(NULL, metadata->name_, size);
2672 const char *latest(version_.VerStr());
2673 size_t length(strlen(latest));
2675 uint16_t vhash(hashlittle(latest, length));
2677 size_t capped(std::min<size_t>(8, length));
2678 latest = latest + length - capped;
2680 if (metadata->first_ == 0)
2681 metadata->first_ = now_;
2683 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2684 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2685 metadata->vhash_ = vhash;
2686 metadata->last_ = now_;
2687 } else if (metadata->last_ == 0)
2688 metadata->last_ = metadata->first_;
2691 _profile(Package$initWithVersion$Section)
2692 section_ = version_.Section();
2695 _profile(Package$initWithVersion$Flags)
2696 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2697 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2702 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2703 pkgCache::VerIterator version;
2705 _profile(Package$packageWithIterator$GetCandidateVer)
2706 version = [database policy]->GetCandidateVer(iterator);
2714 _profile(Package$packageWithIterator$Allocate)
2715 package = [Package allocWithZone:zone];
2718 _profile(Package$packageWithIterator$Initialize)
2720 initWithVersion:version
2727 _profile(Package$packageWithIterator$Autorelease)
2728 package = [package autorelease];
2734 - (pkgCache::PkgIterator) iterator {
2738 - (NSString *) section {
2739 if (section$_ == nil) {
2740 if (section_ == NULL)
2743 _profile(Package$section$mappedSectionForPointer)
2744 section$_ = [database_ mappedSectionForPointer:section_];
2749 - (NSString *) simpleSection {
2750 if (NSString *section = [self section])
2751 return Simplify(section);
2756 - (NSString *) longSection {
2757 return LocalizeSection([self section]);
2760 - (NSString *) shortSection {
2761 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2764 - (NSString *) uri {
2767 pkgIndexFile *index;
2768 pkgCache::PkgFileIterator file(file_.File());
2769 if (![database_ list].FindIndex(file, index))
2771 return [NSString stringWithUTF8String:iterator_->Path];
2772 //return [NSString stringWithUTF8String:file.Site()];
2773 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2777 - (MIMEAddress *) maintainer {
2778 @synchronized (database_) {
2779 if ([database_ era] != era_ || file_.end())
2782 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2783 const std::string &maintainer(parser->Maintainer());
2784 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2787 - (NSString *) md5sum {
2788 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2792 @synchronized (database_) {
2793 if ([database_ era] != era_ || version_.end())
2796 return version_->InstalledSize;
2799 - (NSString *) longDescription {
2800 @synchronized (database_) {
2801 if ([database_ era] != era_ || file_.end())
2804 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2805 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2807 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2808 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2809 if ([lines count] < 2)
2812 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2813 for (size_t i(1), e([lines count]); i != e; ++i) {
2814 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2815 [trimmed addObject:trim];
2818 return [trimmed componentsJoinedByString:@"\n"];
2821 - (NSString *) shortDescription {
2822 if (parsed_ != NULL)
2823 return static_cast<NSString *>(parsed_->tagline_);
2825 @synchronized (database_) {
2826 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2828 const char *start, *end;
2829 if (!parser.ShortDesc(start, end))
2832 if (end - start > 200)
2836 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2839 while (end != start && end[-1] == '\r')
2843 return [(id) CYStringCreate(start, end - start) autorelease];
2847 _profile(Package$index)
2848 CFStringRef name((CFStringRef) [self name]);
2849 if (CFStringGetLength(name) == 0)
2851 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2852 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2854 return toupper(character);
2858 - (PackageValue *) metadata {
2863 PackageValue *metadata([self metadata]);
2864 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2867 - (bool) subscribed {
2868 return [self metadata]->subscribed_;
2871 - (bool) setSubscribed:(bool)subscribed {
2872 PackageValue *metadata([self metadata]);
2873 if (metadata->subscribed_ == subscribed)
2875 metadata->subscribed_ = subscribed;
2883 - (NSString *) latest {
2887 - (NSString *) installed {
2891 - (BOOL) uninstalled {
2892 return installed_.empty();
2895 - (BOOL) upgradableAndEssential:(BOOL)essential {
2896 _profile(Package$upgradableAndEssential)
2897 pkgCache::VerIterator current(iterator_.CurrentVer());
2899 return essential && essential_;
2901 return version_ != current;
2905 - (BOOL) essential {
2910 return [database_ cache][iterator_].InstBroken();
2913 - (BOOL) unfiltered {
2914 _profile(Package$unfiltered$obsolete)
2915 if (_unlikely(obsolete_))
2919 _profile(Package$unfiltered$role)
2920 if (_unlikely(role_ > 3))
2928 if (![self unfiltered])
2933 _profile(Package$visible$section)
2934 section = [self section];
2937 _profile(Package$visible$isSectionVisible)
2938 if (!isSectionVisible(section))
2946 unsigned char current(iterator_->CurrentState);
2947 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2950 - (BOOL) halfConfigured {
2951 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2954 - (BOOL) halfInstalled {
2955 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2959 @synchronized (database_) {
2960 if ([database_ era] != era_ || iterator_.end())
2963 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2964 return state.Mode != pkgDepCache::ModeKeep;
2967 - (NSString *) mode {
2968 @synchronized (database_) {
2969 if ([database_ era] != era_ || iterator_.end())
2972 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2974 switch (state.Mode) {
2975 case pkgDepCache::ModeDelete:
2976 if ((state.iFlags & pkgDepCache::Purge) != 0)
2980 case pkgDepCache::ModeKeep:
2981 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2982 return @"REINSTALL";
2983 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2987 case pkgDepCache::ModeInstall:
2988 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2989 return @"REINSTALL";
2990 else*/ switch (state.Status) {
2992 return @"DOWNGRADE";
2998 return @"NEW_INSTALL";
3009 - (NSString *) name {
3010 return name_.empty() ? id_ : name_;
3013 - (UIImage *) icon {
3014 NSString *section = [self simpleSection];
3017 if (parsed_ != NULL)
3018 if (NSString *href = parsed_->icon_)
3019 if ([href hasPrefix:@"file:///"])
3020 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3021 if (icon == nil) if (section != nil)
3022 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
3023 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
3024 if ([dicon hasPrefix:@"file:///"])
3025 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3027 icon = [UIImage imageNamed:@"unknown.png"];
3031 - (NSString *) homepage {
3032 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
3035 - (NSString *) depiction {
3036 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
3039 - (MIMEAddress *) author {
3040 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
3043 - (NSString *) support {
3044 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
3047 - (NSArray *) files {
3048 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
3049 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
3052 fin.open([path UTF8String]);
3057 while (std::getline(fin, line))
3058 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
3063 - (NSString *) state {
3064 @synchronized (database_) {
3065 if ([database_ era] != era_ || file_.end())
3068 switch (iterator_->CurrentState) {
3069 case pkgCache::State::NotInstalled:
3070 return @"NotInstalled";
3071 case pkgCache::State::UnPacked:
3073 case pkgCache::State::HalfConfigured:
3074 return @"HalfConfigured";
3075 case pkgCache::State::HalfInstalled:
3076 return @"HalfInstalled";
3077 case pkgCache::State::ConfigFiles:
3078 return @"ConfigFiles";
3079 case pkgCache::State::Installed:
3080 return @"Installed";
3081 case pkgCache::State::TriggersAwaited:
3082 return @"TriggersAwaited";
3083 case pkgCache::State::TriggersPending:
3084 return @"TriggersPending";
3087 return (NSString *) [NSNull null];
3090 - (NSString *) selection {
3091 @synchronized (database_) {
3092 if ([database_ era] != era_ || file_.end())
3095 switch (iterator_->SelectedState) {
3096 case pkgCache::State::Unknown:
3098 case pkgCache::State::Install:
3100 case pkgCache::State::Hold:
3102 case pkgCache::State::DeInstall:
3103 return @"DeInstall";
3104 case pkgCache::State::Purge:
3108 return (NSString *) [NSNull null];
3111 - (NSArray *) warnings {
3112 @synchronized (database_) {
3113 if ([database_ era] != era_ || file_.end())
3116 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3117 const char *name(iterator_.Name());
3119 size_t length(strlen(name));
3120 if (length < 2) invalid:
3121 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3122 else for (size_t i(0); i != length; ++i)
3124 /* XXX: technically this is not allowed */
3125 (name[i] < 'A' || name[i] > 'Z') &&
3126 (name[i] < 'a' || name[i] > 'z') &&
3127 (name[i] < '0' || name[i] > '9') &&
3128 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3131 if (strcmp(name, "cydia") != 0) {
3134 bool _private = false;
3136 bool dbstash = false;
3137 bool dsstore = false;
3139 bool repository = [[self section] isEqualToString:@"Repositories"];
3141 if (NSArray *files = [self files])
3142 for (NSString *file in files)
3143 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3145 else if (!user && [file isEqualToString:@"/User"])
3147 else if (!_private && [file isEqualToString:@"/private"])
3149 else if (!stash && [file isEqualToString:@"/var/stash"])
3151 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3153 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3156 /* XXX: this is not sensitive enough. only some folders are valid. */
3157 if (cydia && !repository)
3158 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3160 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3162 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3164 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3166 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3168 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3171 return [warnings count] == 0 ? nil : warnings;
3174 - (NSArray *) applications {
3175 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3177 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3179 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3180 if (NSArray *files = [self files])
3181 for (NSString *file in files)
3182 if (application_r(file)) {
3183 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3186 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3187 if (id == nil || [id isEqualToString:me])
3190 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3192 display = application_r[1];
3194 NSString *bundle([file stringByDeletingLastPathComponent]);
3195 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3196 // XXX: maybe this should check if this is really a string, not just for length
3197 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3199 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3201 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3202 [applications addObject:application];
3204 [application addObject:id];
3205 [application addObject:display];
3206 [application addObject:url];
3209 return [applications count] == 0 ? nil : applications;
3212 - (Source *) source {
3213 if (source_ == nil) {
3214 @synchronized (database_) {
3215 if ([database_ era] != era_ || file_.end())
3216 source_ = (Source *) [NSNull null];
3218 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3222 return source_ == (Source *) [NSNull null] ? nil : source_;
3225 - (time_t) upgraded {
3229 - (uint32_t) recent {
3230 return std::numeric_limits<uint32_t>::max() - upgraded_;
3237 - (BOOL) matches:(NSArray *)query {
3238 if (query == nil || [query count] == 0)
3247 string = [self name];
3248 length = [string length];
3251 for (NSString *term in query) {
3252 range = [string rangeOfString:term options:MatchCompareOptions_];
3253 if (range.location != NSNotFound)
3254 rank_ -= 6 * 1000000 / length;
3259 length = [string length];
3262 for (NSString *term in query) {
3263 range = [string rangeOfString:term options:MatchCompareOptions_];
3264 if (range.location != NSNotFound)
3265 rank_ -= 6 * 1000000 / length;
3269 string = [self shortDescription];
3270 length = [string length];
3271 NSUInteger stop(std::min<NSUInteger>(length, 200));
3274 for (NSString *term in query) {
3275 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3276 if (range.location != NSNotFound)
3277 rank_ -= 2 * 100000;
3283 - (NSArray *) tags {
3287 - (BOOL) hasTag:(NSString *)tag {
3288 return tags_ == nil ? NO : [tags_ containsObject:tag];
3291 - (NSString *) primaryPurpose {
3292 for (NSString *tag in (NSArray *) tags_)
3293 if ([tag hasPrefix:@"purpose::"])
3294 return [tag substringFromIndex:9];
3298 - (NSArray *) purposes {
3299 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3300 for (NSString *tag in (NSArray *) tags_)
3301 if ([tag hasPrefix:@"purpose::"])
3302 [purposes addObject:[tag substringFromIndex:9]];
3303 return [purposes count] == 0 ? nil : purposes;
3306 - (bool) isCommercial {
3307 return [self hasTag:@"cydia::commercial"];
3310 - (void) setIndex:(size_t)index {
3311 if (metadata_->index_ != index)
3312 metadata_->index_ = index;
3315 - (CYString &) cyname {
3316 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3319 - (uint32_t) compareBySection:(NSArray *)sections {
3320 NSString *section([self section]);
3321 for (size_t i(0), e([sections count]); i != e; ++i) {
3322 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3326 return _not(uint32_t);
3330 @synchronized (database_) {
3331 if ([database_ era] != era_ || file_.end())
3334 pkgProblemResolver *resolver = [database_ resolver];
3335 resolver->Clear(iterator_);
3337 pkgCacheFile &cache([database_ cache]);
3338 cache->SetReInstall(iterator_, false);
3339 cache->MarkKeep(iterator_, false);
3343 @synchronized (database_) {
3344 if ([database_ era] != era_ || file_.end())
3347 pkgProblemResolver *resolver = [database_ resolver];
3348 resolver->Clear(iterator_);
3349 resolver->Protect(iterator_);
3351 pkgCacheFile &cache([database_ cache]);
3352 cache->SetReInstall(iterator_, false);
3353 cache->MarkInstall(iterator_, false);
3355 pkgDepCache::StateCache &state((*cache)[iterator_]);
3356 if (!state.Install())
3357 cache->SetReInstall(iterator_, true);
3361 @synchronized (database_) {
3362 if ([database_ era] != era_ || file_.end())
3365 pkgProblemResolver *resolver = [database_ resolver];
3366 resolver->Clear(iterator_);
3367 resolver->Remove(iterator_);
3368 resolver->Protect(iterator_);
3370 pkgCacheFile &cache([database_ cache]);
3371 cache->SetReInstall(iterator_, false);
3372 cache->MarkDelete(iterator_, true);
3377 /* Section Class {{{ */
3378 @interface Section : NSObject {
3382 _H<NSString> localized_;
3385 - (NSComparisonResult) compareByLocalized:(Section *)section;
3386 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3387 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3388 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3390 - (NSString *) name;
3391 - (void) setName:(NSString *)name;
3397 - (void) addToCount;
3399 - (void) setCount:(size_t)count;
3400 - (NSString *) localized;
3404 @implementation Section
3406 - (NSComparisonResult) compareByLocalized:(Section *)section {
3407 NSString *lhs(localized_);
3408 NSString *rhs([section localized]);
3410 /*if ([lhs length] != 0 && [rhs length] != 0) {
3411 unichar lhc = [lhs characterAtIndex:0];
3412 unichar rhc = [rhs characterAtIndex:0];
3414 if (isalpha(lhc) && !isalpha(rhc))
3415 return NSOrderedAscending;
3416 else if (!isalpha(lhc) && isalpha(rhc))
3417 return NSOrderedDescending;
3420 return [lhs compare:rhs options:LaxCompareOptions_];
3423 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3424 if ((self = [self initWithName:name localize:NO]) != nil) {
3425 if (localized != nil)
3426 localized_ = localized;
3430 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3431 return [self initWithName:name row:0 localize:localize];
3434 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3435 if ((self = [super init]) != nil) {
3439 localized_ = LocalizeSection(name_);
3443 - (NSString *) name {
3447 - (void) setName:(NSString *)name {
3463 - (void) addToCount {
3467 - (void) setCount:(size_t)count {
3471 - (NSString *) localized {
3478 class CydiaLogCleaner :
3479 public pkgArchiveCleaner
3482 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3487 /* Database Implementation {{{ */
3488 @implementation Database
3490 + (Database *) sharedInstance {
3491 static _H<Database> instance;
3492 if (instance == nil)
3493 instance = [[[Database alloc] init] autorelease];
3501 - (void) releasePackages {
3502 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3503 CFArrayRemoveAllValues(packages_);
3507 // XXX: actually implement this thing
3509 [self releasePackages];
3510 NSRecycleZone(zone_);
3514 - (void) _readCydia:(NSNumber *)fd {
3515 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3516 std::istream is(&ib);
3519 static RegEx finish_r("finish:([^:]*)");
3521 while (std::getline(is, line)) {
3522 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3524 const char *data(line.c_str());
3525 size_t size = line.size();
3526 lprintf("C:%s\n", data);
3528 if (finish_r(data, size)) {
3529 NSString *finish = finish_r[1];
3530 int index = [Finishes_ indexOfObject:finish];
3531 if (index != INT_MAX && index > Finish_)
3541 - (void) _readStatus:(NSNumber *)fd {
3542 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3543 std::istream is(&ib);
3546 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3547 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3549 while (std::getline(is, line)) {
3550 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3552 const char *data(line.c_str());
3553 size_t size(line.size());
3554 lprintf("S:%s\n", data);
3556 if (conffile_r(data, size)) {
3557 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3558 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3559 } else if (strncmp(data, "status: ", 8) == 0) {
3560 // status: <package>: {unpacked,half-configured,installed}
3561 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3562 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3563 } else if (strncmp(data, "processing: ", 12) == 0) {
3564 // processing: configure: config-test
3565 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3566 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3567 } else if (pmstatus_r(data, size)) {
3568 std::string type([pmstatus_r[1] UTF8String]);
3570 NSString *package = pmstatus_r[2];
3571 if ([package isEqualToString:@"dpkg-exec"])
3574 float percent([pmstatus_r[3] floatValue]);
3575 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3577 NSString *string = pmstatus_r[4];
3579 if (type == "pmerror") {
3580 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3581 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3582 } else if (type == "pmstatus") {
3583 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3584 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3585 } else if (type == "pmconffile")
3586 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3588 lprintf("E:unknown pmstatus\n");
3590 lprintf("E:unknown status\n");
3598 - (void) _readOutput:(NSNumber *)fd {
3599 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3600 std::istream is(&ib);
3603 while (std::getline(is, line)) {
3604 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3606 lprintf("O:%s\n", line.c_str());
3608 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3609 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3621 - (Package *) packageWithName:(NSString *)name {
3624 @synchronized (self) {
3625 if (static_cast<pkgDepCache *>(cache_) == NULL)
3627 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3628 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3632 if ((self = [super init]) != nil) {
3639 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3641 size_t capacity(MetaFile_->active_);
3647 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3648 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3652 _assert(pipe(fds) != -1);
3655 _config->Set("APT::Keep-Fds::", cydiafd_);
3656 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3659 detachNewThreadSelector:@selector(_readCydia:)
3661 withObject:[NSNumber numberWithInt:fds[0]]
3664 _assert(pipe(fds) != -1);
3668 detachNewThreadSelector:@selector(_readStatus:)
3670 withObject:[NSNumber numberWithInt:fds[0]]
3673 _assert(pipe(fds) != -1);
3674 _assert(dup2(fds[0], 0) != -1);
3675 _assert(close(fds[0]) != -1);
3677 input_ = fdopen(fds[1], "a");
3679 _assert(pipe(fds) != -1);
3680 _assert(dup2(fds[1], 1) != -1);
3681 _assert(close(fds[1]) != -1);
3684 detachNewThreadSelector:@selector(_readOutput:)
3686 withObject:[NSNumber numberWithInt:fds[0]]
3691 - (pkgCacheFile &) cache {
3695 - (pkgDepCache::Policy *) policy {
3699 - (pkgRecords *) records {
3703 - (pkgProblemResolver *) resolver {
3707 - (pkgAcquire &) fetcher {
3711 - (pkgSourceList &) list {
3715 - (NSArray *) packages {
3716 return (NSArray *) packages_;
3719 - (NSArray *) sources {
3723 - (Source *) sourceWithKey:(NSString *)key {
3724 for (Source *source in [self sources]) {
3725 if ([[source key] isEqualToString:key])
3730 - (bool) popErrorWithTitle:(NSString *)title {
3733 while (!_error->empty()) {
3735 bool warning(!_error->PopMessage(error));
3740 size_t size(error.size());
3741 if (size == 0 || error[size - 1] != '\n')
3743 error.resize(size - 1);
3746 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3748 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3749 if (warning && no_pubkey(error.c_str()))
3752 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3758 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3759 return [self popErrorWithTitle:title] || !success;
3762 - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3763 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3771 if (access("/etc/apt/sources.list", F_OK) == 0)
3772 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend("/etc/apt/sources.list")];
3774 std::string base("/etc/apt/sources.list.d");
3775 if (DIR *sources = opendir(base.c_str())) {
3776 while (dirent *source = readdir(sources))
3777 if (source->d_name[0] != '.' && source->d_namlen > 5 && strcmp(source->d_name + source->d_namlen - 5, ".list") == 0 && strcmp(source->d_name, "cydia.list") != 0)
3778 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend((base + "/" + source->d_name).c_str())];
3782 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend(SOURCES_LIST)];
3787 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3788 @synchronized (self) {
3791 [self releasePackages];
3794 [sourceList_ removeAllObjects];
3815 new (&pool_) CYPool();
3817 NSRecycleZone(zone_);
3818 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3820 int chk(creat("/tmp/cydia.chk", 0644));
3824 if (invocation != nil)
3825 [invocation invoke];
3827 NSString *title(UCLocalize("DATABASE"));
3829 list_ = new pkgSourceList();
3830 _profile(reloadDataWithInvocation$ReadMainList)
3831 if ([self popErrorWithTitle:title forReadList:*list_])
3835 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3836 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3837 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3838 [sourceList_ addObject:object];
3843 OpProgress progress;
3846 delock_ = GetStatusDate();
3847 _profile(reloadDataWithInvocation$pkgCacheFile)
3848 opened = cache_.Open(progress, false);
3851 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3852 while (!_error->empty()) {
3854 bool warning(!_error->PopMessage(error));
3856 lprintf("cache_.Open():[%s]\n", error.c_str());
3858 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3862 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3863 repair = @selector(configure);
3864 //else if (error == "The package lists or status file could not be parsed or opened.")
3865 // repair = @selector(update);
3866 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3867 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3868 // else if (error == "Malformed Status line")
3869 // else if (error == "The list of sources could not be read.")
3871 if (repair != NULL) {
3873 [delegate_ repairWithSelector:repair];
3882 unlink("/tmp/cydia.chk");
3884 now_ = [[NSDate date] timeIntervalSince1970];
3886 policy_ = new pkgDepCache::Policy();
3887 records_ = new pkgRecords(cache_);
3888 resolver_ = new pkgProblemResolver(cache_);
3889 fetcher_ = new pkgAcquire(&status_);
3892 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3893 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3897 _profile(reloadDataWithInvocation$pkgApplyStatus)
3898 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3902 if (cache_->BrokenCount() != 0) {
3903 _profile(pkgApplyStatus$pkgFixBroken)
3904 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3908 if (cache_->BrokenCount() != 0) {
3909 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3913 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3914 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3919 for (Source *object in (id) sourceList_) {
3920 metaIndex *source([object metaIndex]);
3921 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3922 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3923 // XXX: this could be more intelligent
3924 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3925 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3927 sourceMap_[cached->ID] = object;
3932 /*std::vector<Package *> packages;
3933 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3936 _profile(reloadDataWithInvocation$packageWithIterator)
3937 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3938 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self])
3939 //packages.push_back(package);
3940 CFArrayAppendValue(packages_, CFRetain(package));
3944 /*if (packages.empty())
3945 packages_ = [[NSArray alloc] init];
3947 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3950 _profile(reloadDataWithInvocation$radix$8)
3951 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3954 _profile(reloadDataWithInvocation$radix$4)
3955 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3958 _profile(reloadDataWithInvocation$radix$0)
3959 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3962 _profile(reloadDataWithInvocation$insertion)
3963 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3966 /*_profile(reloadDataWithInvocation$CFQSortArray)
3967 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3970 /*_profile(reloadDataWithInvocation$stdsort)
3971 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3974 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3975 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3978 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3979 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3983 size_t count(CFArrayGetCount(packages_));
3984 MetaFile_->active_ = count;
3985 for (size_t index(0); index != count; ++index)
3986 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3991 @synchronized (self) {
3993 resolver_ = new pkgProblemResolver(cache_);
3995 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3996 if (!cache_[iterator].Keep())
3997 cache_->MarkKeep(iterator, false);
3998 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3999 cache_->SetReInstall(iterator, false);
4002 - (void) configure {
4003 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
4005 system([dpkg UTF8String]);
4010 @synchronized (self) {
4011 // XXX: I don't remember this condition
4016 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4018 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
4020 if ([self popErrorWithTitle:title])
4024 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4026 CydiaLogCleaner cleaner;
4027 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4034 fetcher_->Shutdown();
4036 pkgRecords records(cache_);
4038 lock_ = new FileFd();
4039 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4041 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4043 if ([self popErrorWithTitle:title])
4047 if ([self popErrorWithTitle:title forReadList:list])
4050 manager_ = (_system->CreatePM(cache_));
4051 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4058 bool substrate(RestartSubstrate_);
4059 RestartSubstrate_ = false;
4061 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4063 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4065 if ([self popErrorWithTitle:title forReadList:list])
4067 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4068 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4071 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4073 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4075 [self popErrorWithTitle:title];
4079 bool failed = false;
4080 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4081 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4083 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4086 std::string uri = (*item)->DescURI();
4087 std::string error = (*item)->ErrorText;
4089 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4092 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4093 [delegate_ addProgressEventOnMainThread:event forTask:title];
4096 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4104 RestartSubstrate_ = true;
4106 if (![delock_ isEqual:GetStatusDate()]) {
4107 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title];
4113 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4115 NSString *oextended(@"/var/lib/apt/extended_states");
4116 NSString *nextended(Cache("extended_states"));
4119 if (stat([nextended UTF8String], &info) != -1 && (info.st_mode & S_IFMT) == S_IFREG) {
4120 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/mv -f %@ %@", ShellEscape(nextended), ShellEscape(oextended)] UTF8String]);
4121 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/chown 0:0 %@", ShellEscape(oextended)] UTF8String]);
4124 unlink([nextended UTF8String]);
4125 symlink([oextended UTF8String], [nextended UTF8String]);
4127 if ([self popErrorWithTitle:title])
4130 if (result == pkgPackageManager::Failed) {
4135 if (result != pkgPackageManager::Completed) {
4140 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4142 if ([self popErrorWithTitle:title forReadList:list])
4144 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4145 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4148 if (![before isEqualToArray:after])
4153 return ![delock_ isEqual:GetStatusDate()];
4157 NSString *title(UCLocalize("UPGRADE"));
4158 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4164 [self updateWithStatus:status_];
4167 - (void) updateWithStatus:(CancelStatus &)status {
4168 NSString *title(UCLocalize("REFRESHING_DATA"));
4171 if ([self popErrorWithTitle:title forReadList:list])
4175 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4176 if ([self popErrorWithTitle:title])
4179 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4181 bool success(ListUpdate(status, list, PulseInterval_));
4182 if (status.WasCancelled())
4185 [self popErrorWithTitle:title forOperation:success];
4187 [[NSDictionary dictionaryWithObjectsAndKeys:
4188 [NSDate date], @"LastUpdate",
4189 nil] writeToFile:@ CacheState_ atomically:YES];
4192 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4195 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4196 delegate_ = delegate;
4199 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4200 progress_ = delegate;
4201 status_.setDelegate(delegate);
4204 - (NSObject<ProgressDelegate> *) progressDelegate {
4208 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4209 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4210 return i == sourceMap_.end() ? nil : i->second;
4213 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4214 for (Source *source in (id) sourceList_)
4215 [source setFetch:fetch forURI:uri];
4218 - (void) resetFetch {
4219 for (Source *source in (id) sourceList_)
4220 [source resetFetch];
4223 - (NSString *) mappedSectionForPointer:(const char *)section {
4224 _H<NSString> *mapped;
4226 _profile(Database$mappedSectionForPointer$Cache)
4227 mapped = §ions_[section];
4230 if (*mapped == NULL) {
4231 size_t length(strlen(section));
4232 char spaced[length + 1];
4234 _profile(Database$mappedSectionForPointer$Replace)
4235 for (size_t index(0); index != length; ++index)
4236 spaced[index] = section[index] == '_' ? ' ' : section[index];
4237 spaced[length] = '\0';
4242 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4243 string = [NSString stringWithUTF8String:spaced];
4246 _profile(Database$mappedSectionForPointer$Map)
4247 string = [SectionMap_ objectForKey:string] ?: string;
4257 static _H<NSMutableSet> Diversions_;
4259 @interface Diversion : NSObject {
4262 _H<NSString> format_;
4267 @implementation Diversion
4269 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4270 if ((self = [super init]) != nil) {
4271 pattern_ = [from UTF8String];
4277 - (NSString *) divert:(NSString *)url {
4278 return !pattern_(url) ? nil : pattern_->*format_;
4281 + (NSURL *) divertURL:(NSURL *)url {
4283 NSString *href([url absoluteString]);
4285 for (Diversion *diversion in (id) Diversions_)
4286 if (NSString *diverted = [diversion divert:href]) {
4288 NSLog(@"div: %@", diverted);
4290 url = [NSURL URLWithString:diverted];
4297 - (NSString *) key {
4301 - (NSUInteger) hash {
4305 - (BOOL) isEqual:(Diversion *)object {
4306 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4311 @interface CydiaObject : NSObject {
4312 _H<CyteWebViewController> indirect_;
4313 _transient id delegate_;
4316 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4322 @interface CydiaWebViewController : CyteWebViewController {
4323 _H<CydiaObject> cydia_;
4326 + (void) addDiversion:(Diversion *)diversion;
4327 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4328 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4329 - (void) setDelegate:(id)delegate;
4333 /* Web Scripting {{{ */
4334 @implementation CydiaObject
4336 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4337 if ((self = [super init]) != nil) {
4338 indirect_ = (CyteWebViewController *) indirect;
4342 - (void) setDelegate:(id)delegate {
4343 delegate_ = delegate;
4346 + (NSArray *) _attributeKeys {
4347 return [NSArray arrayWithObjects:
4350 @"coreFoundationVersionNumber",
4366 - (NSArray *) attributeKeys {
4367 return [[self class] _attributeKeys];
4370 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4371 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4374 - (NSString *) version {
4378 - (NSString *) build {
4382 - (NSString *) coreFoundationVersionNumber {
4383 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4386 - (NSString *) device {
4387 return UniqueIdentifier();
4390 - (NSString *) firmware {
4391 return [[UIDevice currentDevice] systemVersion];
4394 - (NSString *) hostname {
4395 return [[UIDevice currentDevice] name];
4398 - (NSString *) idiom {
4399 return (id) Idiom_ ?: [NSNull null];
4402 - (NSString *) mcc {
4403 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4404 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4408 - (NSString *) mnc {
4409 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4410 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4414 - (NSString *) operator {
4415 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4416 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4420 - (NSString *) bbsnum {
4421 return (id) BBSNum_ ?: [NSNull null];
4424 - (NSString *) ecid {
4425 return (id) ChipID_ ?: [NSNull null];
4428 - (NSString *) serial {
4429 return SerialNumber_;
4432 - (NSString *) role {
4433 return (id) [NSNull null];
4436 - (NSString *) model {
4437 return [NSString stringWithUTF8String:Machine_];
4440 + (NSString *) webScriptNameForSelector:(SEL)selector {
4442 else if (selector == @selector(addBridgedHost:))
4443 return @"addBridgedHost";
4444 else if (selector == @selector(addInsecureHost:))
4445 return @"addInsecureHost";
4446 else if (selector == @selector(addInternalRedirect::))
4447 return @"addInternalRedirect";
4448 else if (selector == @selector(addPipelinedHost:scheme:))
4449 return @"addPipelinedHost";
4450 else if (selector == @selector(addSource:::))
4451 return @"addSource";
4452 else if (selector == @selector(addTrivialSource:))
4453 return @"addTrivialSource";
4454 else if (selector == @selector(close))
4456 else if (selector == @selector(du:))
4458 else if (selector == @selector(stringWithFormat:arguments:))
4460 else if (selector == @selector(getAllSources))
4461 return @"getAllSources";
4462 else if (selector == @selector(getApplicationInfo:value:))
4463 return @"getApplicationInfoValue";
4464 else if (selector == @selector(getDisplayIdentifiers))
4465 return @"getDisplayIdentifiers";
4466 else if (selector == @selector(getLocalizedNameForDisplayIdentifier:))
4467 return @"getLocalizedNameForDisplayIdentifier";
4468 else if (selector == @selector(getKernelNumber:))
4469 return @"getKernelNumber";
4470 else if (selector == @selector(getKernelString:))
4471 return @"getKernelString";
4472 else if (selector == @selector(getInstalledPackages))
4473 return @"getInstalledPackages";
4474 else if (selector == @selector(getIORegistryEntry::))
4475 return @"getIORegistryEntry";
4476 else if (selector == @selector(getLocaleIdentifier))
4477 return @"getLocaleIdentifier";
4478 else if (selector == @selector(getPreferredLanguages))
4479 return @"getPreferredLanguages";
4480 else if (selector == @selector(getPackageById:))
4481 return @"getPackageById";
4482 else if (selector == @selector(getMetadataKeys))
4483 return @"getMetadataKeys";
4484 else if (selector == @selector(getMetadataValue:))
4485 return @"getMetadataValue";
4486 else if (selector == @selector(getSessionValue:))
4487 return @"getSessionValue";
4488 else if (selector == @selector(installPackages:))
4489 return @"installPackages";
4490 else if (selector == @selector(isReachable:))
4491 return @"isReachable";
4492 else if (selector == @selector(localizedStringForKey:value:table:))
4494 else if (selector == @selector(popViewController:))
4495 return @"popViewController";
4496 else if (selector == @selector(refreshSources))
4497 return @"refreshSources";
4498 else if (selector == @selector(registerFrame:))
4499 return @"registerFrame";
4500 else if (selector == @selector(removeButton))
4501 return @"removeButton";
4502 else if (selector == @selector(saveConfig))
4503 return @"saveConfig";
4504 else if (selector == @selector(setMetadataValue::))
4505 return @"setMetadataValue";
4506 else if (selector == @selector(setSessionValue::))
4507 return @"setSessionValue";
4508 else if (selector == @selector(substitutePackageNames:))
4509 return @"substitutePackageNames";
4510 else if (selector == @selector(scrollToBottom:))
4511 return @"scrollToBottom";
4512 else if (selector == @selector(setAllowsNavigationAction:))
4513 return @"setAllowsNavigationAction";
4514 else if (selector == @selector(setBadgeValue:))
4515 return @"setBadgeValue";
4516 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4517 return @"setButtonImage";
4518 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4519 return @"setButtonTitle";
4520 else if (selector == @selector(setHidesBackButton:))
4521 return @"setHidesBackButton";
4522 else if (selector == @selector(setHidesNavigationBar:))
4523 return @"setHidesNavigationBar";
4524 else if (selector == @selector(setNavigationBarStyle:))
4525 return @"setNavigationBarStyle";
4526 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4527 return @"setNavigationBarTintColor";
4528 else if (selector == @selector(setPasteboardString:))
4529 return @"setPasteboardString";
4530 else if (selector == @selector(setPasteboardURL:))
4531 return @"setPasteboardURL";
4532 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4533 return @"setScrollAlwaysBounceVertical";
4534 else if (selector == @selector(setScrollIndicatorStyle:))
4535 return @"setScrollIndicatorStyle";
4536 else if (selector == @selector(setToken:))
4538 else if (selector == @selector(setViewportWidth:))
4539 return @"setViewportWidth";
4540 else if (selector == @selector(statfs:))
4542 else if (selector == @selector(supports:))
4544 else if (selector == @selector(unload))
4550 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4551 return [self webScriptNameForSelector:selector] == nil;
4554 - (BOOL) supports:(NSString *)feature {
4555 return [feature isEqualToString:@"window.open"];
4559 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4562 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4563 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4566 - (void) setScrollIndicatorStyle:(NSString *)style {
4567 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4570 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4571 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4574 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4576 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4577 return (id) [NSNull null];
4578 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4580 return (id) [NSNull null];
4581 return [info objectForKey:key];
4584 - (NSArray *) getDisplayIdentifiers {
4585 NSSet *set([SBSCopyDisplayIdentifiers() autorelease]);
4586 if (set == nil || ![set isKindOfClass:[NSSet class]])
4587 return [NSArray array];
4588 return [set allObjects];
4591 - (NSString *) getLocalizedNameForDisplayIdentifier:(NSString *)identifier {
4592 return [SBSCopyLocalizedApplicationNameForDisplayIdentifier(identifier) autorelease] ?: (id) [NSNull null];
4595 - (NSNumber *) getKernelNumber:(NSString *)name {
4596 const char *string([name UTF8String]);
4599 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4600 return (id) [NSNull null];
4602 if (size != sizeof(int))
4603 return (id) [NSNull null];
4606 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4607 return (id) [NSNull null];
4609 return [NSNumber numberWithInt:value];
4612 - (NSString *) getKernelString:(NSString *)name {
4613 const char *string([name UTF8String]);
4616 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4617 return (id) [NSNull null];
4619 char value[size + 1];
4620 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4621 return (id) [NSNull null];
4623 // XXX: just in case you request something ludicrous
4626 return [NSString stringWithCString:value];
4629 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4630 NSObject *value(CYIOGetValue([path UTF8String], entry));
4633 if ([value isKindOfClass:[NSData class]])
4634 value = CYHex((NSData *) value);
4639 - (NSArray *) getMetadataKeys {
4640 @synchronized (Values_) {
4641 return [Values_ allKeys];
4644 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4645 WebFrame *frame([iframe contentFrame]);
4646 [indirect_ registerFrame:frame];
4649 - (id) getMetadataValue:(NSString *)key {
4650 @synchronized (Values_) {
4651 return [Values_ objectForKey:key];
4654 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4655 @synchronized (Values_) {
4656 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4657 [Values_ removeObjectForKey:key];
4659 [Values_ setObject:value forKey:key];
4662 - (id) getSessionValue:(NSString *)key {
4663 @synchronized (SessionData_) {
4664 return [SessionData_ objectForKey:key];
4667 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4668 @synchronized (SessionData_) {
4669 if (value == (id) [WebUndefined undefined])
4670 [SessionData_ removeObjectForKey:key];
4672 [SessionData_ setObject:value forKey:key];
4675 - (void) addBridgedHost:(NSString *)host {
4676 @synchronized (HostConfig_) {
4677 [BridgedHosts_ addObject:host];
4680 - (void) addInsecureHost:(NSString *)host {
4681 @synchronized (HostConfig_) {
4682 [InsecureHosts_ addObject:host];
4685 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4686 @synchronized (HostConfig_) {
4687 if (scheme != (id) [WebUndefined undefined])
4688 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4690 [PipelinedHosts_ addObject:host];
4693 - (void) popViewController:(NSNumber *)value {
4694 if (value == (id) [WebUndefined undefined])
4695 value = [NSNumber numberWithBool:YES];
4696 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4699 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4700 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4702 for (NSString *section in sections)
4703 [array addObject:section];
4705 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4708 distribution, @"Distribution",
4710 nil] waitUntilDone:NO];
4713 - (BOOL) addTrivialSource:(NSString *)href {
4714 href = VerifySource(href);
4717 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4721 - (void) refreshSources {
4722 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4725 - (void) saveConfig {
4726 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4729 - (NSArray *) getAllSources {
4730 return [[Database sharedInstance] sources];
4733 - (NSArray *) getInstalledPackages {
4734 Database *database([Database sharedInstance]);
4735 @synchronized (database) {
4736 NSArray *packages([database packages]);
4737 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4738 for (Package *package in packages)
4739 if (![package uninstalled])
4740 [installed addObject:package];
4744 - (Package *) getPackageById:(NSString *)id {
4745 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4749 return (Package *) [NSNull null];
4752 - (NSString *) getLocaleIdentifier {
4753 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4756 - (NSArray *) getPreferredLanguages {
4760 - (NSArray *) statfs:(NSString *)path {
4763 if (path == nil || statfs([path UTF8String], &stat) == -1)
4766 return [NSArray arrayWithObjects:
4767 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4768 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4769 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4773 - (NSNumber *) du:(NSString *)path {
4774 NSNumber *value(nil);
4776 FILE *du(popen([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/du -ks %@", ShellEscape(path)] UTF8String], "r"));
4779 while (fgets(line, sizeof(line), du) != NULL) {
4780 size_t length(strlen(line));
4781 while (length != 0 && line[length - 1] == '\n')
4782 line[--length] = '\0';
4783 if (char *tab = strchr(line, '\t')) {
4785 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4795 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4798 - (NSNumber *) isReachable:(NSString *)name {
4799 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4802 - (void) installPackages:(NSArray *)packages {
4803 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4806 - (NSString *) substitutePackageNames:(NSString *)message {
4807 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4808 for (size_t i(0), e([words count]); i != e; ++i) {
4809 NSString *word([words objectAtIndex:i]);
4810 if (Package *package = [[Database sharedInstance] packageWithName:word])
4811 [words replaceObjectAtIndex:i withObject:[package name]];
4814 return [words componentsJoinedByString:@" "];
4817 - (void) removeButton {
4818 [indirect_ removeButton];
4821 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4822 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4825 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4826 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4829 - (void) setBadgeValue:(id)value {
4830 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4833 - (void) setAllowsNavigationAction:(NSString *)value {
4834 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4837 - (void) setHidesBackButton:(NSString *)value {
4838 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4841 - (void) setHidesNavigationBar:(NSString *)value {
4842 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4845 - (void) setNavigationBarStyle:(NSString *)value {
4846 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4849 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4850 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4851 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4852 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4855 - (void) setPasteboardString:(NSString *)value {
4856 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4859 - (void) setPasteboardURL:(NSString *)value {
4860 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4863 - (void) setToken:(NSString *)token {
4864 // XXX: the website expects this :/
4867 - (void) scrollToBottom:(NSNumber *)animated {
4868 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4871 - (void) setViewportWidth:(float)width {
4872 [indirect_ setViewportWidthOnMainThread:width];
4875 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4876 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4877 unsigned count([arguments count]);
4879 for (unsigned i(0); i != count; ++i)
4880 values[i] = [arguments objectAtIndex:i];
4881 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4884 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4885 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4887 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4889 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4895 @interface NSURL (CydiaSecure)
4898 @implementation NSURL (CydiaSecure)
4900 - (bool) isCydiaSecure {
4901 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4904 @synchronized (HostConfig_) {
4905 if ([InsecureHosts_ containsObject:[self host]])
4914 /* Cydia Browser Controller {{{ */
4915 @implementation CydiaWebViewController
4917 - (NSURL *) navigationURL {
4918 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4921 + (void) _initialize {
4922 [super _initialize];
4924 Diversions_ = [NSMutableSet setWithCapacity:0];
4927 + (void) addDiversion:(Diversion *)diversion {
4928 [Diversions_ addObject:diversion];
4931 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4932 [super webView:view didClearWindowObject:window forFrame:frame];
4933 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4936 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4937 WebDataSource *source([frame dataSource]);
4938 NSURLResponse *response([source response]);
4939 NSURL *url([response URL]);
4940 NSString *scheme([[url scheme] lowercaseString]);
4942 bool bridged(false);
4944 @synchronized (HostConfig_) {
4945 if ([scheme isEqualToString:@"file"])
4947 else if ([scheme isEqualToString:@"https"])
4948 if ([BridgedHosts_ containsObject:[url host]])
4953 [window setValue:cydia forKey:@"cydia"];
4956 - (void) _setupMail:(MFMailComposeViewController *)controller {
4957 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4959 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4960 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4963 - (NSURL *) URLWithURL:(NSURL *)url {
4964 return [Diversion divertURL:url];
4967 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4968 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4971 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4972 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4975 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4976 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4978 NSURL *url([copy URL]);
4979 NSString *href([url absoluteString]);
4980 NSString *host([url host]);
4982 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4983 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4984 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4985 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4988 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4989 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4991 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4995 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4996 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4997 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4998 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5000 bool bridged; @synchronized (HostConfig_) {
5001 bridged = [BridgedHosts_ containsObject:host];
5004 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
5005 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
5010 - (void) setDelegate:(id)delegate {
5011 [super setDelegate:delegate];
5012 [cydia_ setDelegate:delegate];
5015 - (NSString *) applicationNameForUserAgent {
5020 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
5021 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
5027 @interface AppCacheController : CydiaWebViewController {
5032 @implementation AppCacheController
5034 - (void) didReceiveMemoryWarning {
5035 // XXX: this doesn't work
5038 - (bool) retainsNetworkActivityIndicator {
5046 @interface NSObject (CydiaScript)
5047 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
5050 @implementation NSObject (CydiaScript)
5052 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5058 @implementation NSArray (CydiaScript)
5060 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5061 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5062 for (size_t i(0), e([self count]); i != e; ++i)
5063 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5069 @implementation NSDictionary (CydiaScript)
5071 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5072 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5074 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5081 /* Confirmation Controller {{{ */
5082 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5083 if (!iterator.end())
5084 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5085 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5087 pkgCache::PkgIterator package(dep.TargetPkg());
5090 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5097 @protocol ConfirmationControllerDelegate
5098 - (void) cancelAndClear:(bool)clear;
5099 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5103 @interface ConfirmationController : CydiaWebViewController {
5104 _transient Database *database_;
5106 _H<UIAlertView> essential_;
5108 _H<NSDictionary> changes_;
5109 _H<NSMutableArray> issues_;
5110 _H<NSDictionary> sizes_;
5115 - (id) initWithDatabase:(Database *)database;
5119 @implementation ConfirmationController
5123 RestartSubstrate_ = true;
5124 [delegate_ confirmWithNavigationController:[self navigationController]];
5127 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5128 NSString *context([alert context]);
5130 if ([context isEqualToString:@"remove"]) {
5131 if (button == [alert cancelButtonIndex])
5133 else if (button == [alert firstOtherButtonIndex]) {
5134 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5137 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5138 } else if ([context isEqualToString:@"unable"]) {
5139 [self dismissModalViewControllerAnimated:YES];
5140 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5142 [super alertView:alert clickedButtonAtIndex:button];
5146 - (void) _doContinue {
5147 [delegate_ cancelAndClear:NO];
5148 [self dismissModalViewControllerAnimated:YES];
5151 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5152 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5156 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5157 [super webView:view didClearWindowObject:window forFrame:frame];
5159 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5160 (id) changes_, @"changes",
5161 (id) issues_, @"issues",
5162 (id) sizes_, @"sizes",
5164 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5167 - (id) initWithDatabase:(Database *)database {
5168 if ((self = [super init]) != nil) {
5169 database_ = database;
5171 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5172 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5173 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5174 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5175 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5179 pkgCacheFile &cache([database_ cache]);
5180 NSArray *packages([database_ packages]);
5181 pkgDepCache::Policy *policy([database_ policy]);
5183 issues_ = [NSMutableArray arrayWithCapacity:4];
5185 for (Package *package in packages) {
5186 pkgCache::PkgIterator iterator([package iterator]);
5187 NSString *name([package id]);
5189 if ([package broken]) {
5190 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5192 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5194 reasons, @"reasons",
5197 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5201 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5202 pkgCache::DepIterator start;
5203 pkgCache::DepIterator end;
5204 dep.GlobOr(start, end); // ++dep
5206 if (!cache->IsImportantDep(end))
5208 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5211 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5213 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5214 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5215 clauses, @"clauses",
5219 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5221 pkgCache::PkgIterator target(start.TargetPkg());
5222 if (target->ProvidesList != 0)
5223 reason = @"missing";
5225 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5227 reason = @"installed";
5228 installed = [NSString stringWithUTF8String:ver.VerStr()];
5229 } else if (!cache[target].CandidateVerIter(cache).end())
5230 reason = @"uninstalled";
5231 else if (target->ProvidesList == 0)
5232 reason = @"uninstallable";
5234 reason = @"virtual";
5237 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5238 [NSString stringWithUTF8String:start.CompType()], @"operator",
5239 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5242 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5243 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5244 version, @"version",
5246 installed, @"installed",
5249 // yes, seriously. (wtf?)
5257 pkgDepCache::StateCache &state(cache[iterator]);
5259 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
5261 if (state.NewInstall())
5262 [installs addObject:name];
5263 // XXX: else if (state.Install())
5264 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5265 [reinstalls addObject:name];
5266 // XXX: move before previous if
5267 else if (state.Upgrade())
5268 [upgrades addObject:name];
5269 else if (state.Downgrade())
5270 [downgrades addObject:name];
5271 else if (!state.Delete())
5272 // XXX: _assert(state.Keep());
5274 else if (special_r(name))
5275 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5276 [NSNull null], @"package",
5277 [NSArray arrayWithObjects:
5278 [NSDictionary dictionaryWithObjectsAndKeys:
5279 @"Conflicts", @"relationship",
5280 [NSArray arrayWithObjects:
5281 [NSDictionary dictionaryWithObjectsAndKeys:
5283 [NSNull null], @"version",
5284 @"installed", @"reason",
5291 if ([package essential])
5293 [removes addObject:name];
5296 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5297 substrate_ |= DepSubstrate(iterator.CurrentVer());
5302 else if (Advanced_) {
5303 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5305 essential_ = [[[UIAlertView alloc]
5306 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5307 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5309 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5311 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5315 [essential_ setContext:@"remove"];
5316 [essential_ setNumberOfRows:2];
5318 essential_ = [[[UIAlertView alloc]
5319 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5320 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5322 cancelButtonTitle:UCLocalize("OKAY")
5323 otherButtonTitles:nil
5326 [essential_ setContext:@"unable"];
5329 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5330 installs, @"installs",
5331 reinstalls, @"reinstalls",
5332 upgrades, @"upgrades",
5333 downgrades, @"downgrades",
5334 removes, @"removes",
5337 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5338 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5339 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5342 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5346 - (UIBarButtonItem *) leftButton {
5347 return [[[UIBarButtonItem alloc]
5348 initWithTitle:UCLocalize("CANCEL")
5349 style:UIBarButtonItemStylePlain
5351 action:@selector(cancelButtonClicked)
5356 - (void) applyRightButton {
5357 if ([issues_ count] == 0 && ![self isLoading])
5358 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5359 initWithTitle:UCLocalize("CONFIRM")
5360 style:UIBarButtonItemStyleDone
5362 action:@selector(confirmButtonClicked)
5365 [[self navigationItem] setRightBarButtonItem:nil];
5369 - (void) cancelButtonClicked {
5370 [delegate_ cancelAndClear:YES];
5371 [self dismissModalViewControllerAnimated:YES];
5375 - (void) confirmButtonClicked {
5376 if (essential_ != nil)
5386 /* Progress Data {{{ */
5387 @interface CydiaProgressData : NSObject {
5388 _transient id delegate_;
5397 _H<NSMutableArray> events_;
5398 _H<NSString> title_;
5400 _H<NSString> status_;
5401 _H<NSString> finish_;
5406 @implementation CydiaProgressData
5408 + (NSArray *) _attributeKeys {
5409 return [NSArray arrayWithObjects:
5421 - (NSArray *) attributeKeys {
5422 return [[self class] _attributeKeys];
5425 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5426 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5430 if ((self = [super init]) != nil) {
5431 events_ = [NSMutableArray arrayWithCapacity:32];
5439 - (void) setDelegate:(id)delegate {
5440 delegate_ = delegate;
5443 - (void) setPercent:(float)value {
5447 - (NSNumber *) percent {
5448 return [NSNumber numberWithFloat:percent_];
5451 - (void) setCurrent:(float)value {
5455 - (NSNumber *) current {
5456 return [NSNumber numberWithFloat:current_];
5459 - (void) setTotal:(float)value {
5463 - (NSNumber *) total {
5464 return [NSNumber numberWithFloat:total_];
5467 - (void) setSpeed:(float)value {
5471 - (NSNumber *) speed {
5472 return [NSNumber numberWithFloat:speed_];
5475 - (NSArray *) events {
5479 - (void) removeAllEvents {
5480 [events_ removeAllObjects];
5483 - (void) addEvent:(CydiaProgressEvent *)event {
5484 [events_ addObject:event];
5487 - (void) setTitle:(NSString *)text {
5491 - (NSString *) title {
5495 - (void) setFinish:(NSString *)text {
5499 - (NSString *) finish {
5500 return (id) finish_ ?: [NSNull null];
5503 - (void) setRunning:(bool)running {
5507 - (NSNumber *) running {
5508 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5513 /* Progress Controller {{{ */
5514 @interface ProgressController : CydiaWebViewController <
5517 _transient Database *database_;
5518 _H<CydiaProgressData, 1> progress_;
5522 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5524 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5526 - (void) setTitle:(NSString *)title;
5527 - (void) setCancellable:(bool)cancellable;
5531 @implementation ProgressController
5534 [database_ setProgressDelegate:nil];
5538 - (UIBarButtonItem *) leftButton {
5539 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5540 initWithTitle:UCLocalize("CANCEL")
5541 style:UIBarButtonItemStylePlain
5543 action:@selector(cancel)
5544 ] autorelease] : nil;
5547 - (void) updateCancel {
5548 [super applyLeftButton];
5551 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5552 if ((self = [super init]) != nil) {
5553 database_ = database;
5554 delegate_ = delegate;
5556 [database_ setProgressDelegate:self];
5558 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5559 [progress_ setDelegate:self];
5561 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5563 [scroller_ setBackgroundColor:[UIColor blackColor]];
5565 [[self navigationItem] setHidesBackButton:YES];
5567 [self updateCancel];
5571 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5572 [super webView:view didClearWindowObject:window forFrame:frame];
5573 [window setValue:progress_ forKey:@"cydiaProgress"];
5576 - (void) updateProgress {
5577 [self dispatchEvent:@"CydiaProgressUpdate"];
5580 - (void) viewWillAppear:(BOOL)animated {
5581 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5582 [super viewWillAppear:animated];
5586 UpdateExternalStatus(0);
5589 [delegate_ saveState];
5593 [delegate_ returnToCydia];
5597 [delegate_ terminateWithSuccess];
5598 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5599 [delegate_ suspendWithAnimation:YES];
5601 [delegate_ suspend];*/
5613 UIProgressHUD *hud([delegate_ addProgressHUD]);
5614 [hud setText:UCLocalize("LOADING")];
5615 [delegate_ performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5621 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5622 SBReboot(SBSSpringBoardServerPort());
5624 reboot2(RB_AUTOBOOT);
5631 - (void) setTitle:(NSString *)title {
5632 [progress_ setTitle:title];
5633 [self updateProgress];
5636 - (UIBarButtonItem *) rightButton {
5637 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5638 initWithTitle:UCLocalize("CLOSE")
5639 style:UIBarButtonItemStylePlain
5641 action:@selector(close)
5645 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5646 UpdateExternalStatus(1);
5648 [progress_ setRunning:true];
5649 [self setTitle:title];
5650 // implicit updateProgress
5652 SHA1SumValue notifyconf; {
5654 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5657 MMap mmap(file, MMap::ReadOnly);
5659 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5660 notifyconf = sha1.Result();
5664 SHA1SumValue springlist; {
5666 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5669 MMap mmap(file, MMap::ReadOnly);
5671 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5672 springlist = sha1.Result();
5676 if (invocation != nil) {
5677 [invocation yieldToSelector:@selector(invoke)];
5678 [self setTitle:@"COMPLETE"];
5683 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5686 MMap mmap(file, MMap::ReadOnly);
5688 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5689 if (!(notifyconf == sha1.Result()))
5696 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5699 MMap mmap(file, MMap::ReadOnly);
5701 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5702 if (!(springlist == sha1.Result()))
5708 if (RestartSubstrate_)
5712 RestartSubstrate_ = false;
5715 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5716 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5717 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5718 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5719 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5722 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5724 [progress_ setRunning:false];
5725 [self updateProgress];
5727 [self applyRightButton];
5730 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5731 [progress_ addEvent:event];
5732 [self updateProgress];
5735 - (bool) isProgressCancelled {
5736 return cancel_ == 2;
5741 [self updateCancel];
5744 - (void) setCancellable:(bool)cancellable {
5745 unsigned cancel(cancel_);
5749 else if (cancel_ == 0)
5752 if (cancel != cancel_)
5753 [self updateCancel];
5756 - (void) setProgressCancellable:(NSNumber *)cancellable {
5757 [self setCancellable:[cancellable boolValue]];
5760 - (void) setProgressPercent:(NSNumber *)percent {
5761 [progress_ setPercent:[percent floatValue]];
5762 [self updateProgress];
5765 - (void) setProgressStatus:(NSDictionary *)status {
5766 if (status == nil) {
5767 [progress_ setCurrent:0];
5768 [progress_ setTotal:0];
5769 [progress_ setSpeed:0];
5771 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5773 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5774 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5775 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5778 [self updateProgress];
5784 /* Package Cell {{{ */
5785 @interface PackageCell : CyteTableViewCell <
5786 CyteTableViewCellDelegate
5790 _H<NSString> description_;
5792 _H<NSString> source_;
5794 _H<UIImage> placard_;
5798 - (PackageCell *) init;
5799 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5801 - (void) drawContentRect:(CGRect)rect;
5805 @implementation PackageCell
5807 - (PackageCell *) init {
5808 CGRect frame(CGRectMake(0, 0, 320, 74));
5809 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5810 UIView *content([self contentView]);
5811 CGRect bounds([content bounds]);
5813 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5814 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5815 [content addSubview:content_];
5817 [content_ setDelegate:self];
5818 [content_ setOpaque:YES];
5822 - (NSString *) accessibilityLabel {
5826 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5827 summarized_ = summary;
5837 [content_ setBackgroundColor:[UIColor whiteColor]];
5841 Source *source = [package source];
5843 icon_ = [package icon];
5845 if (NSString *name = [package name])
5846 name_ = [NSString stringWithString:name];
5848 if (NSString *description = [package shortDescription])
5849 description_ = [NSString stringWithString:description];
5851 commercial_ = [package isCommercial];
5853 NSString *label = nil;
5854 bool trusted = false;
5856 if (source != nil) {
5857 label = [source label];
5858 trusted = [source trusted];
5859 } else if ([[package id] isEqualToString:@"firmware"])
5860 label = UCLocalize("APPLE");
5862 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5864 NSString *from(label);
5866 NSString *section = [package simpleSection];
5867 if (section != nil && ![section isEqualToString:label]) {
5868 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5869 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5872 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5874 if (NSString *purpose = [package primaryPurpose])
5875 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5880 if (NSString *mode = [package mode]) {
5881 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5882 color = RemovingColor_;
5883 placard = @"removing";
5885 color = InstallingColor_;
5886 placard = @"installing";
5889 color = [UIColor whiteColor];
5891 if ([package installed] != nil)
5892 placard = @"installed";
5897 [content_ setBackgroundColor:color];
5900 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5903 [self setNeedsDisplay];
5904 [content_ setNeedsDisplay];
5907 - (void) drawSummaryContentRect:(CGRect)rect {
5908 bool highlighted(highlighted_);
5909 float width([self bounds].size.width);
5913 rect.size = [(UIImage *) icon_ size];
5915 while (rect.size.width > 16 || rect.size.height > 16) {
5916 rect.size.width /= 2;
5917 rect.size.height /= 2;
5920 rect.origin.x = 19 - rect.size.width / 2;
5921 rect.origin.y = 19 - rect.size.height / 2;
5923 [icon_ drawInRect:Retina(rect)];
5926 if (badge_ != nil) {
5928 rect.size = [(UIImage *) badge_ size];
5930 rect.size.width /= 4;
5931 rect.size.height /= 4;
5933 rect.origin.x = 25 - rect.size.width / 2;
5934 rect.origin.y = 25 - rect.size.height / 2;
5936 [badge_ drawInRect:Retina(rect)];
5939 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5943 UISetColor(commercial_ ? Purple_ : Black_);
5944 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5946 if (placard_ != nil)
5947 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5950 - (void) drawNormalContentRect:(CGRect)rect {
5951 bool highlighted(highlighted_);
5952 float width([self bounds].size.width);
5956 rect.size = [(UIImage *) icon_ size];
5958 while (rect.size.width > 32 || rect.size.height > 32) {
5959 rect.size.width /= 2;
5960 rect.size.height /= 2;
5963 rect.origin.x = 25 - rect.size.width / 2;
5964 rect.origin.y = 25 - rect.size.height / 2;
5966 [icon_ drawInRect:Retina(rect)];
5969 if (badge_ != nil) {
5971 rect.size = [(UIImage *) badge_ size];
5973 rect.size.width /= 2;
5974 rect.size.height /= 2;
5976 rect.origin.x = 36 - rect.size.width / 2;
5977 rect.origin.y = 36 - rect.size.height / 2;
5979 [badge_ drawInRect:Retina(rect)];
5982 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5986 UISetColor(commercial_ ? Purple_ : Black_);
5987 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5988 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5991 UISetColor(commercial_ ? Purplish_ : Gray_);
5992 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
5994 if (placard_ != nil)
5995 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5998 - (void) drawContentRect:(CGRect)rect {
6000 [self drawSummaryContentRect:rect];
6002 [self drawNormalContentRect:rect];
6007 /* Section Cell {{{ */
6008 @interface SectionCell : CyteTableViewCell <
6009 CyteTableViewCellDelegate
6011 _H<NSString> basic_;
6012 _H<NSString> section_;
6014 _H<NSString> count_;
6016 _H<UISwitch> switch_;
6020 - (void) setSection:(Section *)section editing:(BOOL)editing;
6024 @implementation SectionCell
6026 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6027 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6028 icon_ = [UIImage imageNamed:@"folder.png"];
6029 // XXX: this initial frame is wrong, but is fixed later
6030 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6031 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6033 UIView *content([self contentView]);
6034 CGRect bounds([content bounds]);
6036 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6037 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6038 [content addSubview:content_];
6039 [content_ setBackgroundColor:[UIColor whiteColor]];
6041 [content_ setDelegate:self];
6045 - (void) onSwitch:(id)sender {
6046 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6047 if (metadata == nil) {
6048 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6049 [Sections_ setObject:metadata forKey:basic_];
6052 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6055 - (void) setSection:(Section *)section editing:(BOOL)editing {
6056 if (editing != editing_) {
6058 [switch_ removeFromSuperview];
6060 [self addSubview:switch_];
6069 if (section == nil) {
6070 name_ = UCLocalize("ALL_PACKAGES");
6073 basic_ = [section name];
6074 section_ = [section localized];
6076 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6077 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6080 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6083 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6084 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6086 [content_ setNeedsDisplay];
6089 - (void) setFrame:(CGRect)frame {
6090 [super setFrame:frame];
6092 CGRect rect([switch_ frame]);
6093 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6096 - (NSString *) accessibilityLabel {
6100 - (void) drawContentRect:(CGRect)rect {
6101 bool highlighted(highlighted_ && !editing_);
6103 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6105 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6108 float width(rect.size.width);
6110 width -= 9 + [switch_ frame].size.width;
6114 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6116 CGSize size = [count_ sizeWithFont:Font14_];
6118 UISetColor(Folder_);
6120 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6126 /* File Table {{{ */
6127 @interface FileTable : CyteViewController <
6128 UITableViewDataSource,
6131 _transient Database *database_;
6132 _H<Package> package_;
6134 _H<NSMutableArray> files_;
6135 _H<UITableView, 2> list_;
6138 - (id) initWithDatabase:(Database *)database;
6139 - (void) setPackage:(Package *)package;
6143 @implementation FileTable
6145 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6146 return files_ == nil ? 0 : [files_ count];
6149 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6153 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6154 static NSString *reuseIdentifier = @"Cell";
6156 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6158 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6159 [cell setFont:[UIFont systemFontOfSize:16]];
6161 [cell setText:[files_ objectAtIndex:indexPath.row]];
6162 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6167 - (NSURL *) navigationURL {
6168 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6172 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6173 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6174 [list_ setRowHeight:24.0f];
6175 [(UITableView *) list_ setDataSource:self];
6176 [list_ setDelegate:self];
6177 [self setView:list_];
6180 - (void) viewDidLoad {
6181 [super viewDidLoad];
6183 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6186 - (void) releaseSubviews {
6192 [super releaseSubviews];
6195 - (id) initWithDatabase:(Database *)database {
6196 if ((self = [super init]) != nil) {
6197 database_ = database;
6201 - (void) setPackage:(Package *)package {
6205 files_ = [NSMutableArray arrayWithCapacity:32];
6207 if (package != nil) {
6209 name_ = [package id];
6211 if (NSArray *files = [package files])
6212 [files_ addObjectsFromArray:files];
6214 if ([files_ count] != 0) {
6215 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6216 [files_ removeObjectAtIndex:0];
6217 [files_ sortUsingSelector:@selector(compareByPath:)];
6219 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6220 [stack addObject:@"/"];
6222 for (int i(0), e([files_ count]); i != e; ++i) {
6223 NSString *file = [files_ objectAtIndex:i];
6224 while (![file hasPrefix:[stack lastObject]])
6225 [stack removeLastObject];
6226 NSString *directory = [stack lastObject];
6227 [stack addObject:[file stringByAppendingString:@"/"]];
6228 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6229 ([stack count] - 2) * 3, "",
6230 [file substringFromIndex:[directory length]]
6239 - (void) reloadData {
6242 [self setPackage:[database_ packageWithName:name_]];
6247 /* Package Controller {{{ */
6248 @interface CYPackageController : CydiaWebViewController <
6249 UIActionSheetDelegate
6251 _transient Database *database_;
6252 _H<Package> package_;
6255 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6256 _H<UIActionSheet> sheet_;
6257 _H<UIBarButtonItem> button_;
6260 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6264 @implementation CYPackageController
6266 - (NSURL *) navigationURL {
6267 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6270 - (void) _clickButtonWithName:(NSString *)name {
6271 if ([name isEqualToString:@"CLEAR"])
6272 [delegate_ clearPackage:package_];
6273 else if ([name isEqualToString:@"INSTALL"])
6274 [delegate_ installPackage:package_];
6275 else if ([name isEqualToString:@"REINSTALL"])
6276 [delegate_ installPackage:package_];
6277 else if ([name isEqualToString:@"REMOVE"])
6278 [delegate_ removePackage:package_];
6279 else if ([name isEqualToString:@"UPGRADE"])
6280 [delegate_ installPackage:package_];
6281 else _assert(false);
6284 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6285 NSString *context([sheet context]);
6286 if (sheet_ == sheet)
6289 if ([context isEqualToString:@"modify"]) {
6290 if (button != [sheet cancelButtonIndex]) {
6292 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6294 [self _clickButtonWithName:buttons_[button].first];
6297 [sheet dismissWithClickedButtonIndex:button animated:YES];
6301 - (bool) _allowJavaScriptPanel {
6306 - (void) _customButtonClicked {
6307 size_t count(buttons_.size());
6312 [self _clickButtonWithName:buttons_[0].first];
6314 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6315 for (const auto &button : buttons_)
6316 [buttons addObject:button.second];
6318 sheet_ = [[[UIActionSheet alloc]
6321 cancelButtonTitle:nil
6322 destructiveButtonTitle:nil
6323 otherButtonTitles:nil
6326 for (NSString *button in buttons) [sheet_ addButtonWithTitle:button];
6328 [sheet_ addButtonWithTitle:UCLocalize("CANCEL")];
6329 [sheet_ setCancelButtonIndex:[sheet_ numberOfButtons] - 1];
6331 [sheet_ setContext:@"modify"];
6333 [delegate_ showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6337 - (void) reloadButtonClicked {
6338 if (commercial_ && function_ == nil && [package_ uninstalled])
6340 [self customButtonClicked];
6343 - (void) applyLoadingTitle {
6344 // Don't show "Loading" as the title. Ever.
6347 - (UIBarButtonItem *) rightButton {
6352 - (void) setPageColor:(UIColor *)color {
6353 return [super setPageColor:nil];
6356 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6357 if ((self = [super init]) != nil) {
6358 database_ = database;
6359 name_ = name == nil ? @"" : [NSString stringWithString:name];
6360 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6364 - (void) reloadData {
6367 [sheet_ dismissWithClickedButtonIndex:[sheet_ cancelButtonIndex] animated:YES];
6370 package_ = [database_ packageWithName:name_];
6374 if (package_ != nil) {
6375 [(Package *) package_ parse];
6377 commercial_ = [package_ isCommercial];
6379 if ([package_ mode] != nil)
6380 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6381 if ([package_ source] == nil);
6382 else if ([package_ upgradableAndEssential:NO])
6383 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6384 else if ([package_ uninstalled])
6385 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6387 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6388 if (![package_ uninstalled])
6389 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6393 switch (buttons_.size()) {
6394 case 0: title = nil; break;
6395 case 1: title = buttons_[0].second; break;
6396 default: title = UCLocalize("MODIFY"); break;
6399 button_ = [[[UIBarButtonItem alloc]
6401 style:UIBarButtonItemStylePlain
6403 action:@selector(customButtonClicked)
6407 - (bool) isLoading {
6408 return commercial_ ? [super isLoading] : false;
6414 /* Package List Controller {{{ */
6415 @interface PackageListController : CyteViewController <
6416 UITableViewDataSource,
6419 _transient Database *database_;
6421 _H<NSArray> packages_;
6422 _H<NSArray> sections_;
6423 _H<UITableView, 2> list_;
6425 _H<NSArray> thumbs_;
6426 std::vector<NSInteger> offset_;
6428 _H<NSString> title_;
6429 unsigned reloading_;
6432 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6433 - (void) setDelegate:(id)delegate;
6434 - (void) resetCursor;
6437 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6441 @implementation PackageListController
6443 - (NSURL *) referrerURL {
6444 return [self navigationURL];
6447 - (bool) isSummarized {
6451 - (bool) showsSections {
6455 - (void) deselectWithAnimation:(BOOL)animated {
6456 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6459 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6460 CGRect base = [[self view] bounds];
6461 base.size.height -= bounds.size.height;
6462 base.origin = [list_ frame].origin;
6464 [UIView beginAnimations:nil context:NULL];
6465 [UIView setAnimationBeginsFromCurrentState:YES];
6466 [UIView setAnimationCurve:curve];
6467 [UIView setAnimationDuration:duration];
6468 [list_ setFrame:base];
6469 [UIView commitAnimations];
6472 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6473 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6476 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6477 [self resizeForKeyboardBounds:bounds duration:0];
6480 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6481 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6482 *curve = UIViewAnimationCurveEaseInOut;
6484 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6486 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6489 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6492 - (void) keyboardWillShow:(NSNotification *)notification {
6495 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6496 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6498 NSTimeInterval duration;
6499 UIViewAnimationCurve curve;
6500 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6502 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6503 UIViewController *base = self;
6504 while ([base parentOrPresentingViewController] != nil)
6505 base = [base parentOrPresentingViewController];
6506 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6507 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6509 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6510 intersection.size.height += CYStatusBarHeight();
6512 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6515 - (void) keyboardWillHide:(NSNotification *)notification {
6516 NSTimeInterval duration;
6517 UIViewAnimationCurve curve;
6518 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6520 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6523 - (void) viewWillAppear:(BOOL)animated {
6524 [super viewWillAppear:animated];
6526 [self resizeForKeyboardBounds:CGRectZero];
6527 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6528 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6531 - (void) viewWillDisappear:(BOOL)animated {
6532 [super viewWillDisappear:animated];
6534 [self resizeForKeyboardBounds:CGRectZero];
6535 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6536 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6539 - (void) viewDidAppear:(BOOL)animated {
6540 [super viewDidAppear:animated];
6541 [self deselectWithAnimation:animated];
6544 - (void) didSelectPackage:(Package *)package {
6545 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6546 [view setDelegate:delegate_];
6547 [[self navigationController] pushViewController:view animated:YES];
6550 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6551 NSInteger count([sections_ count]);
6552 return count == 0 ? 1 : count;
6555 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6556 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6558 return [[sections_ objectAtIndex:section] name];
6561 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6562 if ([sections_ count] == 0)
6564 return [[sections_ objectAtIndex:section] count];
6567 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6568 @synchronized (database_) {
6569 if ([database_ era] != era_)
6572 Section *section([sections_ objectAtIndex:[path section]]);
6573 NSInteger row([path row]);
6574 Package *package([packages_ objectAtIndex:([section row] + row)]);
6575 return [[package retain] autorelease];
6578 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6579 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6581 cell = [[[PackageCell alloc] init] autorelease];
6583 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6584 [cell setPackage:package asSummary:[self isSummarized]];
6588 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6589 Package *package([self packageAtIndexPath:path]);
6590 package = [database_ packageWithName:[package id]];
6591 [self didSelectPackage:package];
6594 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6598 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6599 return offset_[index];
6602 - (void) updateHeight {
6603 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6606 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6607 if ((self = [super init]) != nil) {
6608 database_ = database;
6609 title_ = [title copy];
6610 [[self navigationItem] setTitle:title_];
6615 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6616 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6617 [self setView:view];
6619 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6620 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6621 [view addSubview:list_];
6623 // XXX: is 20 the most optimal number here?
6624 [list_ setSectionIndexMinimumDisplayRowCount:20];
6626 [(UITableView *) list_ setDataSource:self];
6627 [list_ setDelegate:self];
6629 [self updateHeight];
6632 - (void) releaseSubviews {
6641 [super releaseSubviews];
6644 - (void) setDelegate:(id)delegate {
6645 delegate_ = delegate;
6648 - (bool) shouldYield {
6652 - (bool) shouldBlock {
6656 - (NSMutableArray *) _reloadPackages {
6657 @synchronized (database_) {
6658 era_ = [database_ era];
6659 NSArray *packages([database_ packages]);
6661 return [NSMutableArray arrayWithArray:packages];
6664 - (void) _reloadData {
6665 if (reloading_ != 0) {
6670 NSMutableArray *packages;
6673 if ([self shouldYield]) {
6677 if (![self shouldBlock])
6680 hud = [delegate_ addProgressHUD];
6681 [hud setText:UCLocalize("LOADING")];
6685 packages = [self yieldToSelector:@selector(_reloadPackages)];
6688 [delegate_ removeProgressHUD:hud];
6689 } while (reloading_ == 2);
6691 packages = [self _reloadPackages];
6694 @synchronized (database_) {
6695 if (era_ != [database_ era])
6702 packages_ = packages;
6704 if ([self showsSections])
6705 sections_ = [self sectionsForPackages:packages];
6707 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6708 [section setCount:[packages_ count]];
6709 sections_ = [NSArray arrayWithObject:section];
6712 [self updateHeight];
6714 _profile(PackageTable$reloadData$List)
6715 [(UITableView *) list_ setDataSource:self];
6723 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6724 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6725 size_t end([packages count]);
6727 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6728 Section *section(prefix);
6730 thumbs_ = CollationThumbs_;
6731 offset_ = CollationOffset_;
6734 size_t offsets([CollationStarts_ count]);
6736 NSString *start([CollationStarts_ objectAtIndex:offset]);
6737 size_t length([start length]);
6739 for (size_t index(0); index != end; ++index) {
6741 Package *package([packages objectAtIndex:index]);
6742 NSString *name(PackageName(package, @selector(cyname)));
6744 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6745 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6746 NSString *title([CollationTitles_ objectAtIndex:offset]);
6747 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6748 [sections addObject:section];
6750 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6753 length = [start length];
6757 [section addToCount];
6760 for (; offset != offsets; ++offset) {
6761 NSString *title([CollationTitles_ objectAtIndex:offset]);
6762 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6763 [sections addObject:section];
6766 if ([prefix count] != 0) {
6767 Section *suffix([sections lastObject]);
6768 [prefix setName:[suffix name]];
6769 [suffix setName:nil];
6770 [sections insertObject:prefix atIndex:(offsets - 1)];
6776 - (void) reloadData {
6779 if ([self shouldYield])
6780 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6785 - (void) resetCursor {
6786 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6789 - (void) clearData {
6790 [self updateHeight];
6792 [list_ setDataSource:nil];
6800 /* Filtered Package List Controller {{{ */
6801 typedef Function<bool, Package *> PackageFilter;
6802 typedef Function<void, NSMutableArray *> PackageSorter;
6803 @interface FilteredPackageListController : PackageListController {
6804 PackageFilter filter_;
6805 PackageSorter sorter_;
6808 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6810 - (void) setFilter:(PackageFilter)filter;
6811 - (void) setSorter:(PackageSorter)sorter;
6815 @implementation FilteredPackageListController
6817 - (void) setFilter:(PackageFilter)filter {
6818 @synchronized (self) {
6822 - (void) setSorter:(PackageSorter)sorter {
6823 @synchronized (self) {
6827 - (NSMutableArray *) _reloadPackages {
6828 @synchronized (database_) {
6829 era_ = [database_ era];
6831 NSArray *packages([database_ packages]);
6832 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6834 PackageFilter filter;
6835 PackageSorter sorter;
6837 @synchronized (self) {
6842 _profile(PackageTable$reloadData$Filter)
6843 for (Package *package in packages)
6844 if (filter(package))
6845 [filtered addObject:package];
6853 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6854 if ((self = [super initWithDatabase:database title:title]) != nil) {
6855 [self setFilter:filter];
6862 /* Home Controller {{{ */
6863 @interface HomeController : CydiaWebViewController {
6864 CFRunLoopRef runloop_;
6865 SCNetworkReachabilityRef reachability_;
6870 @implementation HomeController
6872 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6873 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6877 if ((self = [super init]) != nil) {
6878 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6881 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6882 if (reachability_ != NULL) {
6883 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6884 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6886 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6887 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6894 if (reachability_ != NULL && runloop_ != NULL)
6895 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6899 - (NSURL *) navigationURL {
6900 return [NSURL URLWithString:@"cydia://home"];
6903 - (void) aboutButtonClicked {
6904 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6906 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6907 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6908 [alert setCancelButtonIndex:0];
6911 @"Copyright \u00a9 2008-2015\n"
6914 "Jay Freeman (saurik)\n"
6915 "saurik@saurik.com\n"
6916 "http://www.saurik.com/"
6922 - (UIBarButtonItem *) leftButton {
6923 return [[[UIBarButtonItem alloc]
6924 initWithTitle:UCLocalize("ABOUT")
6925 style:UIBarButtonItemStylePlain
6927 action:@selector(aboutButtonClicked)
6934 /* Cydia Navigation Controller Interface {{{ */
6935 @interface UINavigationController (Cydia)
6937 - (NSArray *) navigationURLCollection;
6938 - (void) unloadData;
6943 /* Cydia Tab Bar Controller {{{ */
6944 @interface CydiaTabBarController : CyteTabBarController <
6945 UITabBarControllerDelegate,
6948 _transient Database *database_;
6950 _H<UIActivityIndicatorView> indicator_;
6953 // XXX: ok, "updatedelegate_"?...
6954 _transient NSObject<CydiaDelegate> *updatedelegate_;
6957 - (NSArray *) navigationURLCollection;
6958 - (void) beginUpdate;
6963 @implementation CydiaTabBarController
6965 - (NSArray *) navigationURLCollection {
6966 NSMutableArray *items([NSMutableArray array]);
6968 // XXX: Should this deal with transient view controllers?
6969 for (id navigation in [self viewControllers]) {
6970 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6972 [items addObject:stack];
6978 - (id) initWithDatabase:(Database *)database {
6979 if ((self = [super init]) != nil) {
6980 database_ = database;
6981 [self setDelegate:self];
6983 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6984 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6986 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6990 - (void) beginUpdate {
6994 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6995 UITabBarItem *item([controller tabBarItem]);
6997 [item setBadgeValue:@""];
6998 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
7000 [indicator_ startAnimating];
7001 [badge addSubview:indicator_];
7003 [updatedelegate_ retainNetworkActivityIndicator];
7007 detachNewThreadSelector:@selector(performUpdate)
7013 - (void) performUpdate {
7014 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7016 SourceStatus status(self, database_);
7017 [database_ updateWithStatus:status];
7020 performSelectorOnMainThread:@selector(completeUpdate)
7028 - (void) stopUpdateWithSelector:(SEL)selector {
7030 [updatedelegate_ releaseNetworkActivityIndicator];
7032 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7033 [[controller tabBarItem] setBadgeValue:nil];
7035 [indicator_ removeFromSuperview];
7036 [indicator_ stopAnimating];
7038 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7041 - (void) completeUpdate {
7044 [self stopUpdateWithSelector:@selector(reloadData)];
7047 - (void) cancelUpdate {
7048 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7051 - (void) cancelPressed {
7052 [self cancelUpdate];
7059 - (bool) isSourceCancelled {
7063 - (void) startSourceFetch:(NSString *)uri {
7066 - (void) stopSourceFetch:(NSString *)uri {
7069 - (void) setUpdateDelegate:(id)delegate {
7070 updatedelegate_ = delegate;
7076 /* Cydia Navigation Controller Implementation {{{ */
7077 @implementation UINavigationController (Cydia)
7079 - (NSArray *) navigationURLCollection {
7080 NSMutableArray *stack([NSMutableArray array]);
7082 for (CyteViewController *controller in [self viewControllers]) {
7083 NSString *url = [[controller navigationURL] absoluteString];
7085 [stack addObject:url];
7091 - (void) reloadData {
7094 UIViewController *visible([self visibleViewController]);
7096 [visible reloadData];
7098 // on the iPad, this view controller is ALSO visible. :(
7100 if (UIViewController *modal = [self modalViewController])
7101 if ([modal modalPresentationStyle] == UIModalPresentationFormSheet)
7102 if (UIViewController *top = [self topViewController])
7107 - (void) unloadData {
7108 for (CyteViewController *page in [self viewControllers])
7117 /* Cydia:// Protocol {{{ */
7118 @interface CydiaURLProtocol : NSURLProtocol {
7123 @implementation CydiaURLProtocol
7125 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7126 NSURL *url([request URL]);
7130 NSString *scheme([[url scheme] lowercaseString]);
7131 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7133 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7139 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7143 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7144 id<NSURLProtocolClient> client([self client]);
7146 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7148 NSData *data(UIImagePNGRepresentation(icon));
7150 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7151 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7152 [client URLProtocol:self didLoadData:data];
7153 [client URLProtocolDidFinishLoading:self];
7157 - (void) startLoading {
7158 id<NSURLProtocolClient> client([self client]);
7159 NSURLRequest *request([self request]);
7161 NSURL *url([request URL]);
7162 NSString *href([url absoluteString]);
7163 NSString *scheme([[url scheme] lowercaseString]);
7167 if ([scheme isEqualToString:@"cydia"])
7168 path = [href substringFromIndex:8];
7169 else if ([scheme isEqualToString:@"about"])
7170 path = [href substringFromIndex:12];
7171 else _assert(false);
7173 NSRange slash([path rangeOfString:@"/"]);
7176 if (slash.location == NSNotFound) {
7180 command = [path substringToIndex:slash.location];
7181 path = [path substringFromIndex:(slash.location + 1)];
7184 Database *database([Database sharedInstance]);
7187 else if ([command isEqualToString:@"application-icon"]) {
7190 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7194 if (icon == nil && $SBSCopyIconImagePNGDataForDisplayIdentifier != NULL) {
7195 NSData *data([$SBSCopyIconImagePNGDataForDisplayIdentifier(path) autorelease]);
7196 icon = [UIImage imageWithData:data];
7200 if (NSString *file = SBSCopyIconImagePathForDisplayIdentifier(path))
7201 icon = [UIImage imageAtPath:file];
7204 icon = [UIImage imageNamed:@"unknown.png"];
7206 [self _returnPNGWithImage:icon forRequest:request];
7207 } else if ([command isEqualToString:@"package-icon"]) {
7210 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7211 Package *package([database packageWithName:path]);
7215 UIImage *icon([package icon]);
7216 [self _returnPNGWithImage:icon forRequest:request];
7217 } else if ([command isEqualToString:@"uikit-image"]) {
7220 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7221 UIImage *icon(_UIImageWithName(path));
7222 [self _returnPNGWithImage:icon forRequest:request];
7223 } else if ([command isEqualToString:@"section-icon"]) {
7226 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7227 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7229 icon = [UIImage imageNamed:@"unknown.png"];
7230 [self _returnPNGWithImage:icon forRequest:request];
7232 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7236 - (void) stopLoading {
7242 /* Section Controller {{{ */
7243 @interface SectionController : FilteredPackageListController {
7245 _H<NSString> section_;
7248 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7252 @implementation SectionController
7254 - (NSURL *) referrerURL {
7255 NSString *name(section_);
7256 name = name ?: @"*";
7257 NSString *key(key_);
7259 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7262 - (NSURL *) navigationURL {
7263 NSString *name(section_);
7264 name = name ?: @"*";
7265 NSString *key(key_);
7267 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7270 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7273 title = UCLocalize("ALL_PACKAGES");
7274 else if (![section isEqual:@""])
7275 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7277 title = UCLocalize("NO_SECTION");
7279 if ((self = [super initWithDatabase:database title:title]) != nil) {
7280 key_ = [source key];
7285 - (void) reloadData {
7286 Source *source([database_ sourceWithKey:key_]);
7287 _H<NSString> name(section_);
7289 [self setFilter:[=](Package *package) {
7290 NSString *section([package section]);
7294 section == nil && [name length] == 0 ||
7295 [name isEqualToString:section]
7298 [package source] == source
7299 ) && [package visible];
7307 /* Sections Controller {{{ */
7308 @interface SectionsController : CyteViewController <
7309 UITableViewDataSource,
7312 _transient Database *database_;
7314 _H<NSMutableArray> sections_;
7315 _H<NSMutableArray> filtered_;
7316 _H<UITableView, 2> list_;
7319 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7320 - (void) editButtonClicked;
7324 @implementation SectionsController
7326 - (NSURL *) navigationURL {
7327 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7330 - (Source *) source {
7333 return [database_ sourceWithKey:key_];
7336 - (void) updateNavigationItem {
7337 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7338 if ([sections_ count] == 0) {
7339 [[self navigationItem] setRightBarButtonItem:nil];
7341 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7342 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7344 action:@selector(editButtonClicked)
7345 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7349 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7350 [super setEditing:editing animated:animated];
7355 [delegate_ updateData];
7357 [self updateNavigationItem];
7360 - (void) viewDidAppear:(BOOL)animated {
7361 [super viewDidAppear:animated];
7362 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7365 - (void) viewWillDisappear:(BOOL)animated {
7366 [super viewWillDisappear:animated];
7367 [self setEditing:NO];
7370 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7371 Section *section = nil;
7372 int index = [indexPath row];
7373 if (![self isEditing]) {
7376 section = [filtered_ objectAtIndex:index];
7378 section = [sections_ objectAtIndex:index];
7383 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7384 if ([self isEditing])
7385 return [sections_ count];
7387 return [filtered_ count] + 1;
7390 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7394 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7395 static NSString *reuseIdentifier = @"SectionCell";
7397 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7399 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7401 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7406 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7407 if ([self isEditing])
7410 Section *section = [self sectionAtIndexPath:indexPath];
7412 SectionController *controller = [[[SectionController alloc]
7413 initWithDatabase:database_
7414 source:[self source]
7415 section:[section name]
7417 [controller setDelegate:delegate_];
7419 [[self navigationController] pushViewController:controller animated:YES];
7423 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7424 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7425 [list_ setRowHeight:46];
7426 [(UITableView *) list_ setDataSource:self];
7427 [list_ setDelegate:self];
7428 [self setView:list_];
7431 - (void) viewDidLoad {
7432 [super viewDidLoad];
7434 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7437 - (void) releaseSubviews {
7443 [super releaseSubviews];
7446 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7447 if ((self = [super init]) != nil) {
7448 database_ = database;
7449 key_ = [source key];
7453 - (void) reloadData {
7456 NSArray *packages = [database_ packages];
7458 sections_ = [NSMutableArray arrayWithCapacity:16];
7459 filtered_ = [NSMutableArray arrayWithCapacity:16];
7461 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7463 Source *source([self source]);
7466 for (Package *package in packages) {
7467 if (source != nil && [package source] != source)
7470 NSString *name([package section]);
7471 NSString *key(name == nil ? @"" : name);
7475 _profile(SectionsView$reloadData$Section)
7476 section = [sections objectForKey:key];
7477 if (section == nil) {
7478 _profile(SectionsView$reloadData$Section$Allocate)
7479 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7480 [sections setObject:section forKey:key];
7485 [section addToCount];
7487 _profile(SectionsView$reloadData$Filter)
7488 if (![package visible])
7496 [sections_ addObjectsFromArray:[sections allValues]];
7498 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7500 for (Section *section in (id) sections_) {
7501 size_t count([section row]);
7505 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7506 [section setCount:count];
7507 [filtered_ addObject:section];
7510 [self updateNavigationItem];
7515 - (void) editButtonClicked {
7516 [self setEditing:![self isEditing] animated:YES];
7522 /* Changes Controller {{{ */
7523 @interface ChangesController : FilteredPackageListController {
7527 - (id) initWithDatabase:(Database *)database;
7531 @implementation ChangesController
7533 - (NSURL *) referrerURL {
7534 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7537 - (NSURL *) navigationURL {
7538 return [NSURL URLWithString:@"cydia://changes"];
7541 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7542 @synchronized (database_) {
7543 if ([database_ era] != era_)
7546 NSUInteger sectionIndex([path section]);
7547 if (sectionIndex >= [sections_ count])
7549 Section *section([sections_ objectAtIndex:sectionIndex]);
7550 NSInteger row([path row]);
7551 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7554 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7555 NSString *context([alert context]);
7557 if ([context isEqualToString:@"norefresh"])
7558 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7561 - (void) setLeftBarButtonItem {
7562 if ([delegate_ updating])
7563 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7564 initWithTitle:UCLocalize("CANCEL")
7565 style:UIBarButtonItemStyleDone
7567 action:@selector(cancelButtonClicked)
7568 ] autorelease] animated:YES];
7570 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7571 initWithTitle:UCLocalize("REFRESH")
7572 style:UIBarButtonItemStylePlain
7574 action:@selector(refreshButtonClicked)
7575 ] autorelease] animated:YES];
7578 - (void) refreshButtonClicked {
7579 if ([delegate_ requestUpdate])
7580 [self setLeftBarButtonItem];
7583 - (void) cancelButtonClicked {
7584 [delegate_ cancelUpdate];
7587 - (void) upgradeButtonClicked {
7588 [delegate_ distUpgrade];
7589 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7592 - (bool) shouldYield {
7596 - (bool) shouldBlock {
7600 - (void) useFilter {
7601 @synchronized (self) {
7602 [self setFilter:[](Package *package) {
7603 return [package upgradableAndEssential:YES] || [package visible];
7606 [self setSorter:[](NSMutableArray *packages) {
7607 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7611 - (id) initWithDatabase:(Database *)database {
7612 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7617 - (void) viewDidLoad {
7618 [super viewDidLoad];
7619 [self setLeftBarButtonItem];
7622 - (void) viewWillAppear:(BOOL)animated {
7623 [super viewWillAppear:animated];
7624 [self setLeftBarButtonItem];
7627 - (void) reloadData {
7628 [self setLeftBarButtonItem];
7632 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7633 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7635 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7636 Section *ignored = nil;
7637 Section *section = nil;
7641 bool unseens = false;
7643 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7645 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7646 Package *package = [packages objectAtIndex:offset];
7648 BOOL uae = [package upgradableAndEssential:YES];
7652 time_t seen([package seen]);
7654 if (section == nil || last != seen) {
7658 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7661 _profile(ChangesController$reloadData$Allocate)
7662 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7663 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7664 [sections addObject:section];
7668 [section addToCount];
7669 } else if ([package ignored]) {
7670 if (ignored == nil) {
7671 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7673 [ignored addToCount];
7676 [upgradable addToCount];
7681 CFRelease(formatter);
7684 Section *last = [sections lastObject];
7685 size_t count = [last count];
7686 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7687 [sections removeLastObject];
7690 if ([ignored count] != 0)
7691 [sections insertObject:ignored atIndex:0];
7693 [sections insertObject:upgradable atIndex:0];
7697 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7698 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7699 style:UIBarButtonItemStylePlain
7701 action:@selector(upgradeButtonClicked)
7702 ] autorelease]) animated:YES];
7709 /* Search Controller {{{ */
7710 @interface SearchController : FilteredPackageListController <
7713 _H<UISearchBar, 1> search_;
7718 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7719 - (void) reloadData;
7723 @implementation SearchController
7725 - (NSURL *) referrerURL {
7726 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7729 - (NSURL *) navigationURL {
7730 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7731 return [NSURL URLWithString:@"cydia://search"];
7733 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7736 - (NSArray *) termsForQuery:(NSString *)query {
7737 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7738 for (NSString *component in [query componentsSeparatedByString:@" "])
7739 if ([component length] != 0)
7740 [terms addObject:component];
7745 - (void) useSearch {
7746 _H<NSArray> query([self termsForQuery:[search_ text]]);
7749 @synchronized (self) {
7750 [self setFilter:[=](Package *package) {
7751 if (![package unfiltered])
7753 if (![package matches:query])
7758 [self setSorter:[](NSMutableArray *packages) {
7759 [packages radixSortUsingSelector:@selector(rank)];
7767 - (void) usePrefix:(NSString *)prefix {
7768 _H<NSString> query(prefix);
7771 @synchronized (self) {
7772 [self setFilter:[=](Package *package) {
7773 if ([query length] == 0)
7775 if (![package unfiltered])
7777 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7782 [self setSorter:nullptr];
7788 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7790 [self usePrefix:[search_ text]];
7793 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7794 [search_ resignFirstResponder];
7798 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7799 [search_ setText:@""];
7800 [self searchBarButtonClicked:searchBar];
7803 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7804 [self searchBarButtonClicked:searchBar];
7807 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7808 [self usePrefix:text];
7811 - (bool) shouldYield {
7815 - (bool) shouldBlock {
7819 - (bool) isSummarized {
7823 - (bool) showsSections {
7827 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7828 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7829 search_ = [[[UISearchBar alloc] init] autorelease];
7830 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7831 [search_ setDelegate:self];
7833 UITextField *textField;
7834 if ([search_ respondsToSelector:@selector(searchField)])
7835 textField = [search_ searchField];
7837 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7839 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7840 [textField setEnablesReturnKeyAutomatically:NO];
7841 [[self navigationItem] setTitleView:textField];
7844 [search_ setText:query];
7849 - (void) viewDidAppear:(BOOL)animated {
7850 [super viewDidAppear:animated];
7852 if (!searchloaded_) {
7853 searchloaded_ = YES;
7854 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7855 [search_ layoutSubviews];
7858 if ([self isSummarized])
7859 [search_ becomeFirstResponder];
7862 - (void) reloadData {
7867 - (void) didSelectPackage:(Package *)package {
7868 [search_ resignFirstResponder];
7869 [super didSelectPackage:package];
7874 /* Package Settings Controller {{{ */
7875 @interface PackageSettingsController : CyteViewController <
7876 UITableViewDataSource,
7879 _transient Database *database_;
7881 _H<Package> package_;
7882 _H<UITableView, 2> table_;
7883 _H<UISwitch> subscribedSwitch_;
7884 _H<UISwitch> ignoredSwitch_;
7885 _H<UITableViewCell> subscribedCell_;
7886 _H<UITableViewCell> ignoredCell_;
7889 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7893 @implementation PackageSettingsController
7895 - (NSURL *) navigationURL {
7896 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7899 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7900 if (package_ == nil)
7903 if ([package_ installed] == nil)
7909 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7910 if (package_ == nil)
7913 // both sections contain just one item right now.
7917 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7921 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7923 return UCLocalize("SHOW_ALL_CHANGES_EX");
7925 return UCLocalize("IGNORE_UPGRADES_EX");
7928 - (void) onSubscribed:(id)control {
7929 bool value([control isOn]);
7930 if (package_ == nil)
7932 if ([package_ setSubscribed:value])
7933 [delegate_ updateData];
7936 - (void) _updateIgnored {
7937 const char *package([name_ UTF8String]);
7938 bool on([ignoredSwitch_ isOn]);
7940 FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w"));
7941 fwrite(package, strlen(package), 1, dpkg);
7944 fwrite(" hold\n", 6, 1, dpkg);
7946 fwrite(" install\n", 9, 1, dpkg);
7951 - (void) onIgnored:(id)control {
7952 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7953 [invocation setTarget:self];
7954 [invocation setSelector:@selector(_updateIgnored)];
7956 [delegate_ reloadDataWithInvocation:invocation];
7959 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7960 if (package_ == nil)
7963 switch ([indexPath section]) {
7964 case 0: return subscribedCell_;
7965 case 1: return ignoredCell_;
7974 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7975 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7976 [self setView:view];
7978 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7979 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7980 [(UITableView *) table_ setDataSource:self];
7981 [table_ setDelegate:self];
7982 [view addSubview:table_];
7984 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7985 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7986 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7988 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7989 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7990 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7992 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7993 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7994 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7995 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7997 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7998 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7999 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8000 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8003 - (void) viewDidLoad {
8004 [super viewDidLoad];
8006 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8009 - (void) releaseSubviews {
8011 subscribedCell_ = nil;
8013 ignoredSwitch_ = nil;
8014 subscribedSwitch_ = nil;
8016 [super releaseSubviews];
8019 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8020 if ((self = [super init]) != nil) {
8021 database_ = database;
8026 - (void) reloadData {
8029 package_ = [database_ packageWithName:name_];
8031 if (package_ != nil) {
8032 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8033 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8034 } // XXX: what now, G?
8036 [table_ reloadData];
8042 /* Installed Controller {{{ */
8043 @interface InstalledController : FilteredPackageListController {
8047 - (id) initWithDatabase:(Database *)database;
8048 - (void) queueStatusDidChange;
8052 @implementation InstalledController
8054 - (NSURL *) referrerURL {
8055 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8058 - (NSURL *) navigationURL {
8059 return [NSURL URLWithString:@"cydia://installed"];
8062 - (void) useRecent {
8065 @synchronized (self) {
8066 [self setFilter:[](Package *package) {
8067 return ![package uninstalled] && package->role_ < 7;
8070 [self setSorter:[](NSMutableArray *packages) {
8071 [packages radixSortUsingSelector:@selector(recent)];
8075 - (void) useFilter:(UISegmentedControl *)segmented {
8076 NSInteger selected([segmented selectedSegmentIndex]);
8078 return [self useRecent];
8079 bool simple(selected == 0);
8082 @synchronized (self) {
8083 [self setFilter:[=](Package *package) {
8084 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8087 [self setSorter:nullptr];
8090 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8092 return [super sectionsForPackages:packages];
8094 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8096 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8097 Section *section(nil);
8100 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8101 Package *package([packages objectAtIndex:offset]);
8103 time_t upgraded([package upgraded]);
8104 if (upgraded < 1168364520)
8107 upgraded -= upgraded % (60 * 60 * 24);
8109 if (section == nil || upgraded != last) {
8114 continue; // XXX: name = UCLocalize("...");
8116 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8120 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8121 [sections addObject:section];
8124 [section addToCount];
8127 CFRelease(formatter);
8131 - (id) initWithDatabase:(Database *)database {
8132 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8133 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8134 [segmented setSelectedSegmentIndex:0];
8135 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8136 [[self navigationItem] setTitleView:segmented];
8138 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8139 [self useFilter:segmented];
8141 [self queueStatusDidChange];
8146 - (void) queueButtonClicked {
8151 - (void) queueStatusDidChange {
8154 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8155 initWithTitle:UCLocalize("QUEUE")
8156 style:UIBarButtonItemStyleDone
8158 action:@selector(queueButtonClicked)
8161 [[self navigationItem] setRightBarButtonItem:nil];
8166 - (void) modeChanged:(UISegmentedControl *)segmented {
8167 [self useFilter:segmented];
8174 /* Source Cell {{{ */
8175 @interface SourceCell : CyteTableViewCell <
8176 CyteTableViewCellDelegate,
8179 _H<Source, 1> source_;
8182 _H<NSString> origin_;
8183 _H<NSString> label_;
8184 _H<UIActivityIndicatorView> indicator_;
8187 - (void) setSource:(Source *)source;
8188 - (void) setFetch:(NSNumber *)fetch;
8192 @implementation SourceCell
8194 - (void) _setImage:(NSArray *)data {
8195 if ([url_ isEqual:[data objectAtIndex:0]]) {
8196 icon_ = [data objectAtIndex:1];
8197 [content_ setNeedsDisplay];
8201 - (void) _setSource:(NSURL *) url {
8202 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8204 if (NSData *data = [NSURLConnection
8205 sendSynchronousRequest:[NSURLRequest
8207 cachePolicy:NSURLRequestUseProtocolCachePolicy
8211 returningResponse:NULL
8214 if (UIImage *image = [UIImage imageWithData:data])
8215 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8220 - (void) setSource:(Source *)source {
8222 [source_ setDelegate:self];
8224 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8226 icon_ = [UIImage imageNamed:@"unknown.png"];
8228 origin_ = [source name];
8229 label_ = [source rooturi];
8231 [content_ setNeedsDisplay];
8233 url_ = [source iconURL];
8234 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8237 - (void) setAllSource {
8239 [indicator_ stopAnimating];
8241 icon_ = [UIImage imageNamed:@"folder.png"];
8242 origin_ = UCLocalize("ALL_SOURCES");
8243 label_ = UCLocalize("ALL_SOURCES_EX");
8244 [content_ setNeedsDisplay];
8247 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8248 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8249 UIView *content([self contentView]);
8250 CGRect bounds([content bounds]);
8252 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8253 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8254 [content_ setBackgroundColor:[UIColor whiteColor]];
8255 [content addSubview:content_];
8257 [content_ setDelegate:self];
8258 [content_ setOpaque:YES];
8260 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8261 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8262 [content addSubview:indicator_];
8264 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8268 - (void) layoutSubviews {
8269 [super layoutSubviews];
8271 UIView *content([self contentView]);
8272 CGRect bounds([content bounds]);
8274 CGRect frame([indicator_ frame]);
8275 frame.origin.x = bounds.size.width - frame.size.width;
8276 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8278 if (kCFCoreFoundationVersionNumber < 800)
8279 frame.origin.x -= 8;
8280 [indicator_ setFrame:frame];
8283 - (NSString *) accessibilityLabel {
8287 - (void) drawContentRect:(CGRect)rect {
8288 bool highlighted(highlighted_);
8289 float width(rect.size.width);
8293 rect.size = [(UIImage *) icon_ size];
8295 while (rect.size.width > 32 || rect.size.height > 32) {
8296 rect.size.width /= 2;
8297 rect.size.height /= 2;
8300 rect.origin.x = 26 - rect.size.width / 2;
8301 rect.origin.y = 26 - rect.size.height / 2;
8303 [icon_ drawInRect:Retina(rect)];
8306 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8311 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8315 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8318 - (void) setFetch:(NSNumber *)fetch {
8319 if ([fetch boolValue])
8320 [indicator_ startAnimating];
8322 [indicator_ stopAnimating];
8327 /* Sources Controller {{{ */
8328 @interface SourcesController : CyteViewController <
8329 UITableViewDataSource,
8332 _transient Database *database_;
8335 _H<UITableView, 2> list_;
8336 _H<NSMutableArray> sources_;
8340 _H<UIProgressHUD> hud_;
8343 NSURLConnection *trivial_bz2_;
8344 NSURLConnection *trivial_gz_;
8349 - (id) initWithDatabase:(Database *)database;
8350 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8354 @implementation SourcesController
8356 - (void) _releaseConnection:(NSURLConnection *)connection {
8357 if (connection != nil) {
8358 [connection cancel];
8359 //[connection setDelegate:nil];
8360 [connection release];
8365 [self _releaseConnection:trivial_gz_];
8366 [self _releaseConnection:trivial_bz2_];
8371 - (NSURL *) navigationURL {
8372 return [NSURL URLWithString:@"cydia://sources"];
8375 - (void) viewDidAppear:(BOOL)animated {
8376 [super viewDidAppear:animated];
8377 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8380 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8384 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8386 return UCLocalize("INDIVIDUAL_SOURCES");
8390 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8393 case 1: return [sources_ count];
8398 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8399 @synchronized (database_) {
8400 if ([database_ era] != era_)
8402 if ([indexPath section] != 1)
8404 NSUInteger index([indexPath row]);
8405 if (index >= [sources_ count])
8407 return [sources_ objectAtIndex:index];
8410 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8411 static NSString *cellIdentifier = @"SourceCell";
8413 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8414 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8415 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8417 Source *source([self sourceAtIndexPath:indexPath]);
8419 [cell setAllSource];
8421 [cell setSource:source];
8426 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8427 SectionsController *controller([[[SectionsController alloc]
8428 initWithDatabase:database_
8429 source:[self sourceAtIndexPath:indexPath]
8432 [controller setDelegate:delegate_];
8433 [[self navigationController] pushViewController:controller animated:YES];
8436 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8437 if ([indexPath section] != 1)
8439 Source *source = [self sourceAtIndexPath:indexPath];
8440 return [source record] != nil;
8443 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8444 _assert([indexPath section] == 1);
8445 if (editingStyle == UITableViewCellEditingStyleDelete) {
8446 Source *source = [self sourceAtIndexPath:indexPath];
8447 if (source == nil) return;
8449 [Sources_ removeObjectForKey:[source key]];
8451 [delegate_ _saveConfig];
8452 [delegate_ reloadDataWithInvocation:nil];
8456 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8457 [self updateButtonsForEditingStatusAnimated:YES];
8461 [delegate_ addTrivialSource:href_];
8464 [delegate_ syncData];
8467 - (NSString *) getWarning {
8468 NSString *href(href_);
8469 NSRange colon([href rangeOfString:@"://"]);
8470 if (colon.location != NSNotFound)
8471 href = [href substringFromIndex:(colon.location + 3)];
8472 href = [href stringByAddingPercentEscapes];
8473 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8475 NSURL *url([NSURL URLWithString:href]);
8477 NSStringEncoding encoding;
8478 NSError *error(nil);
8480 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8481 return [warning length] == 0 ? nil : warning;
8485 - (void) _endConnection:(NSURLConnection *)connection {
8486 // XXX: the memory management in this method is horribly awkward
8488 NSURLConnection **field = NULL;
8489 if (connection == trivial_bz2_)
8490 field = &trivial_bz2_;
8491 else if (connection == trivial_gz_)
8492 field = &trivial_gz_;
8493 _assert(field != NULL);
8494 [connection release];
8498 trivial_bz2_ == nil &&
8501 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8503 [delegate_ releaseNetworkActivityIndicator];
8505 [delegate_ removeProgressHUD:hud_];
8509 if (warning != nil) {
8510 UIAlertView *alert = [[[UIAlertView alloc]
8511 initWithTitle:UCLocalize("SOURCE_WARNING")
8514 cancelButtonTitle:UCLocalize("CANCEL")
8516 UCLocalize("ADD_ANYWAY"),
8520 [alert setContext:@"warning"];
8521 [alert setNumberOfRows:1];
8524 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8530 } else if (error_ != nil) {
8531 UIAlertView *alert = [[[UIAlertView alloc]
8532 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8533 message:[error_ localizedDescription]
8535 cancelButtonTitle:UCLocalize("OK")
8536 otherButtonTitles:nil
8539 [alert setContext:@"urlerror"];
8544 UIAlertView *alert = [[[UIAlertView alloc]
8545 initWithTitle:UCLocalize("NOT_REPOSITORY")
8546 message:UCLocalize("NOT_REPOSITORY_EX")
8548 cancelButtonTitle:UCLocalize("OK")
8549 otherButtonTitles:nil
8552 [alert setContext:@"trivial"];
8562 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8563 switch ([response statusCode]) {
8569 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8570 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8572 [self _endConnection:connection];
8575 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8576 [self _endConnection:connection];
8579 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8580 NSURL *url([NSURL URLWithString:href]);
8582 NSMutableURLRequest *request = [NSMutableURLRequest
8584 cachePolicy:NSURLRequestUseProtocolCachePolicy
8588 [request setHTTPMethod:method];
8590 if (Machine_ != NULL)
8591 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8593 if (UniqueID_ != nil)
8594 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8596 if ([url isCydiaSecure]) {
8597 if (UniqueID_ != nil)
8598 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8601 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8604 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8605 NSString *context([alert context]);
8607 if ([context isEqualToString:@"source"]) {
8610 NSString *href = [[alert textField] text];
8611 href = VerifySource(href);
8616 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8617 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8621 // XXX: this is stupid
8622 hud_ = [delegate_ addProgressHUD];
8623 [hud_ setText:UCLocalize("VERIFYING_URL")];
8624 [delegate_ retainNetworkActivityIndicator];
8633 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8634 } else if ([context isEqualToString:@"trivial"])
8635 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8636 else if ([context isEqualToString:@"urlerror"])
8637 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8638 else if ([context isEqualToString:@"warning"]) {
8641 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8650 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8654 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8655 BOOL editing([list_ isEditing]);
8658 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8659 initWithTitle:UCLocalize("ADD")
8660 style:UIBarButtonItemStylePlain
8662 action:@selector(addButtonClicked)
8663 ] autorelease] animated:animated];
8664 else if ([delegate_ updating])
8665 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8666 initWithTitle:UCLocalize("CANCEL")
8667 style:UIBarButtonItemStyleDone
8669 action:@selector(cancelButtonClicked)
8670 ] autorelease] animated:animated];
8672 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8673 initWithTitle:UCLocalize("REFRESH")
8674 style:UIBarButtonItemStylePlain
8676 action:@selector(refreshButtonClicked)
8677 ] autorelease] animated:animated];
8679 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8680 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8681 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8683 action:@selector(editButtonClicked)
8684 ] autorelease] animated:animated];
8688 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8689 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8690 [list_ setRowHeight:53];
8691 [(UITableView *) list_ setDataSource:self];
8692 [list_ setDelegate:self];
8693 [self setView:list_];
8696 - (void) viewDidLoad {
8697 [super viewDidLoad];
8699 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8700 [self updateButtonsForEditingStatusAnimated:NO];
8703 - (void) viewWillAppear:(BOOL)animated {
8704 [super viewWillAppear:animated];
8706 [list_ setEditing:NO];
8707 [self updateButtonsForEditingStatusAnimated:NO];
8710 - (void) releaseSubviews {
8715 [super releaseSubviews];
8718 - (id) initWithDatabase:(Database *)database {
8719 if ((self = [super init]) != nil) {
8720 database_ = database;
8724 - (void) reloadData {
8726 [self updateButtonsForEditingStatusAnimated:YES];
8728 @synchronized (database_) {
8729 era_ = [database_ era];
8731 sources_ = [NSMutableArray arrayWithCapacity:16];
8732 [sources_ addObjectsFromArray:[database_ sources]];
8734 [sources_ sortUsingSelector:@selector(compareByName:)];
8737 int count([sources_ count]);
8739 for (int i = 0; i != count; i++) {
8740 if ([[sources_ objectAtIndex:i] record] == nil)
8748 - (void) showAddSourcePrompt {
8749 UIAlertView *alert = [[[UIAlertView alloc]
8750 initWithTitle:UCLocalize("ENTER_APT_URL")
8753 cancelButtonTitle:UCLocalize("CANCEL")
8755 UCLocalize("ADD_SOURCE"),
8759 [alert setContext:@"source"];
8761 [alert setNumberOfRows:1];
8762 [alert addTextFieldWithValue:@"http://" label:@""];
8764 UITextInputTraits *traits = [[alert textField] textInputTraits];
8765 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8766 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8767 [traits setKeyboardType:UIKeyboardTypeURL];
8768 // XXX: UIReturnKeyDone
8769 [traits setReturnKeyType:UIReturnKeyNext];
8774 - (void) addButtonClicked {
8775 [self showAddSourcePrompt];
8778 - (void) refreshButtonClicked {
8779 if ([delegate_ requestUpdate])
8780 [self updateButtonsForEditingStatusAnimated:YES];
8783 - (void) cancelButtonClicked {
8784 [delegate_ cancelUpdate];
8787 - (void) editButtonClicked {
8788 [list_ setEditing:![list_ isEditing] animated:YES];
8789 [self updateButtonsForEditingStatusAnimated:YES];
8795 /* Stash Controller {{{ */
8796 @interface StashController : CyteViewController {
8797 _H<UIActivityIndicatorView> spinner_;
8798 _H<UILabel> status_;
8799 _H<UILabel> caption_;
8804 @implementation StashController
8807 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8808 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8809 [self setView:view];
8811 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8813 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8814 CGRect spinrect = [spinner_ frame];
8815 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8816 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8817 [spinner_ setFrame:spinrect];
8818 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8819 [view addSubview:spinner_];
8820 [spinner_ startAnimating];
8823 captrect.size.width = [[self view] frame].size.width;
8824 captrect.size.height = 40.0f;
8825 captrect.origin.x = 0;
8826 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8827 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8828 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8829 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8830 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8831 [caption_ setTextColor:[UIColor whiteColor]];
8832 [caption_ setBackgroundColor:[UIColor clearColor]];
8833 [caption_ setShadowColor:[UIColor blackColor]];
8834 [caption_ setTextAlignment:NSTextAlignmentCenter];
8835 [view addSubview:caption_];
8838 statusrect.size.width = [[self view] frame].size.width;
8839 statusrect.size.height = 30.0f;
8840 statusrect.origin.x = 0;
8841 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8842 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8843 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8844 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8845 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8846 [status_ setTextColor:[UIColor whiteColor]];
8847 [status_ setBackgroundColor:[UIColor clearColor]];
8848 [status_ setShadowColor:[UIColor blackColor]];
8849 [status_ setTextAlignment:NSTextAlignmentCenter];
8850 [view addSubview:status_];
8853 - (void) releaseSubviews {
8858 [super releaseSubviews];
8864 @interface CYURLCache : SDURLCache {
8869 @implementation CYURLCache
8871 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8874 else if ([event isEqualToString:@"no-cache"])
8876 else if ([event isEqualToString:@"store"])
8878 else if ([event isEqualToString:@"invalid"])
8880 else if ([event isEqualToString:@"memory"])
8882 else if ([event isEqualToString:@"disk"])
8884 else if ([event isEqualToString:@"miss"])
8887 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8891 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8892 if (NSURLResponse *response = [cached response])
8893 if (NSString *mime = [response MIMEType])
8894 if ([mime isEqualToString:@"text/cache-manifest"]) {
8895 NSURL *url([response URL]);
8898 NSLog(@"###: %@", [url absoluteString]);
8901 @synchronized (HostConfig_) {
8902 [CachedURLs_ addObject:url];
8906 [super storeCachedResponse:cached forRequest:request];
8909 - (void) createDiskCachePath {
8910 [super createDiskCachePath];
8915 @interface Cydia : UIApplication <
8916 ConfirmationControllerDelegate,
8920 _H<UIWindow> window_;
8921 _H<CydiaTabBarController> tabbar_;
8922 _H<CyteTabBarController> emulated_;
8923 _H<AppCacheController> appcache_;
8925 _H<NSMutableArray> essential_;
8926 _H<NSMutableArray> broken_;
8928 Database *database_;
8930 _H<NSURL> starturl_;
8935 _H<StashController> stash_;
8944 @implementation Cydia
8946 - (void) lockSuspend {
8947 if (locked_++ == 0) {
8948 if ($SBSSetInterceptsMenuButtonForever != NULL)
8949 (*$SBSSetInterceptsMenuButtonForever)(true);
8951 [self setIdleTimerDisabled:YES];
8955 - (void) unlockSuspend {
8956 if (--locked_ == 0) {
8957 [self setIdleTimerDisabled:NO];
8959 if ($SBSSetInterceptsMenuButtonForever != NULL)
8960 (*$SBSSetInterceptsMenuButtonForever)(false);
8964 - (void) beginUpdate {
8965 [tabbar_ beginUpdate];
8968 - (void) cancelUpdate {
8969 [tabbar_ cancelUpdate];
8972 - (bool) requestUpdate {
8973 if (IsReachable("cydia.saurik.com")) {
8977 UIAlertView *alert = [[[UIAlertView alloc]
8978 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8979 message:@"Host Unreachable" // XXX: Localize
8981 cancelButtonTitle:UCLocalize("OK")
8982 otherButtonTitles:nil
8985 [alert setContext:@"norefresh"];
8993 return [tabbar_ updating];
8997 if ([broken_ count] != 0) {
8998 int count = [broken_ count];
9000 UIAlertView *alert = [[[UIAlertView alloc]
9001 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9002 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9004 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9006 UCLocalize("TEMPORARY_IGNORE"),
9010 [alert setContext:@"fixhalf"];
9011 [alert setNumberOfRows:2];
9013 } else if (!Ignored_ && [essential_ count] != 0) {
9014 int count = [essential_ count];
9016 UIAlertView *alert = [[[UIAlertView alloc]
9017 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9018 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9020 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9022 UCLocalize("UPGRADE_ESSENTIAL"),
9023 UCLocalize("COMPLETE_UPGRADE"),
9027 [alert setContext:@"upgrade"];
9032 - (void) returnToCydia {
9036 - (void) reloadSpringBoard {
9037 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
9038 system("/bin/launchctl stop com.apple.backboardd");
9040 system("/bin/launchctl stop com.apple.SpringBoard");
9042 system("/usr/bin/killall backboardd SpringBoard");
9045 - (void) _saveConfig {
9046 SaveConfig(database_);
9049 // Navigation controller for the queuing badge.
9050 - (UINavigationController *) queueNavigationController {
9051 NSArray *controllers = [tabbar_ viewControllers];
9052 return [controllers objectAtIndex:3];
9055 - (void) unloadData {
9056 [tabbar_ unloadData];
9059 - (void) _updateData {
9063 UINavigationController *navigation = [self queueNavigationController];
9065 id queuedelegate = nil;
9066 if ([[navigation viewControllers] count] > 0)
9067 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9069 [queuedelegate queueStatusDidChange];
9070 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9073 - (void) _refreshIfPossible {
9074 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9076 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:@ CacheState_] objectForKey:@"LastUpdate"]);
9078 bool recently = false;
9079 if (update != nil) {
9080 NSTimeInterval interval([update timeIntervalSinceNow]);
9081 if (interval > -(15*60))
9085 // Don't automatic refresh if:
9086 // - We already refreshed recently.
9087 // - We already auto-refreshed this launch.
9088 // - Auto-refresh is disabled.
9089 // - Cydia's server is not reachable
9090 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9091 // If we are cancelling, we need to make sure it knows it's already loaded.
9094 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9096 // We are going to load, so remember that.
9099 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
9105 - (void) refreshIfPossible {
9106 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
9109 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9110 _profile(reloadDataWithInvocation)
9111 @synchronized (self) {
9112 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9114 [hud setText:UCLocalize("RELOADING_DATA")];
9116 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9120 [essential_ removeAllObjects];
9121 [broken_ removeAllObjects];
9123 _profile(reloadDataWithInvocation$Essential)
9124 NSArray *packages([database_ packages]);
9125 for (Package *package in packages) {
9127 [broken_ addObject:package];
9128 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9129 if ([package essential] && [package installed] != nil)
9130 [essential_ addObject:package];
9136 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9139 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9140 [changesItem setBadgeValue:badge];
9141 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9142 [self setApplicationIconBadgeNumber:changes];
9145 [changesItem setBadgeValue:nil];
9146 [changesItem setAnimatedBadge:NO];
9147 [self setApplicationIconBadgeNumber:0];
9154 [self removeProgressHUD:hud];
9161 - (void) updateData {
9165 - (void) updateDataAndLoad {
9167 if ([database_ progressDelegate] == nil)
9173 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9176 - (void) disemulate {
9177 if (emulated_ == nil)
9180 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9181 [window_ setRootViewController:tabbar_];
9183 [window_ addSubview:[tabbar_ view]];
9184 [[emulated_ view] removeFromSuperview];
9188 [window_ setUserInteractionEnabled:YES];
9191 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9192 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9194 UIViewController *parent;
9195 if (emulated_ == nil)
9205 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9206 [parent presentModalViewController:navigation animated:YES];
9209 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9210 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9212 if (navigation != nil)
9213 [navigation pushViewController:progress animated:YES];
9215 [self presentModalViewController:progress force:YES];
9217 [progress invoke:invocation withTitle:title];
9221 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9222 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9225 - (void) repairWithInvocation:(NSInvocation *)invocation {
9227 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9231 - (void) repairWithSelector:(SEL)selector {
9232 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9235 - (void) reloadData {
9236 [self reloadDataWithInvocation:nil];
9237 if ([database_ progressDelegate] == nil)
9243 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9246 - (void) addSource:(NSDictionary *) source {
9247 CydiaAddSource(source);
9250 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9251 CydiaAddSource(href, distribution, sections);
9254 // XXX: this method should not return anything
9255 - (BOOL) addTrivialSource:(NSString *)href {
9256 CydiaAddSource(href, @"./");
9261 pkgProblemResolver *resolver = [database_ resolver];
9263 resolver->InstallProtect();
9264 if (!resolver->Resolve(true))
9269 // XXX: this is a really crappy way of doing this.
9270 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9271 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9272 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9273 if ([tabbar_ updating])
9274 [tabbar_ cancelUpdate];
9276 if (![database_ prepare])
9279 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9280 [page setDelegate:self];
9281 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9284 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9285 [tabbar_ presentModalViewController:confirm_ animated:YES];
9291 @synchronized (self) {
9296 - (void) clearPackage:(Package *)package {
9297 @synchronized (self) {
9304 - (void) installPackages:(NSArray *)packages {
9305 @synchronized (self) {
9306 for (Package *package in packages)
9313 - (void) installPackage:(Package *)package {
9314 @synchronized (self) {
9321 - (void) removePackage:(Package *)package {
9322 @synchronized (self) {
9329 - (void) distUpgrade {
9330 @synchronized (self) {
9331 if (![database_ upgrade])
9339 system("/usr/bin/uicache");
9344 UIProgressHUD *hud([self addProgressHUD]);
9345 [hud setText:UCLocalize("LOADING")];
9346 [self yieldToSelector:@selector(_uicache)];
9347 [self removeProgressHUD:hud];
9351 [database_ perform];
9352 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9353 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9356 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9359 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9360 [self unlockSuspend];
9363 - (void) retainNetworkActivityIndicator {
9364 if (activity_++ == 0)
9365 [self setNetworkActivityIndicatorVisible:YES];
9368 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9372 - (void) releaseNetworkActivityIndicator {
9373 if (--activity_ == 0)
9374 [self setNetworkActivityIndicatorVisible:NO];
9377 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9382 - (void) cancelAndClear:(bool)clear {
9383 @synchronized (self) {
9395 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9396 NSString *context([alert context]);
9398 if ([context isEqualToString:@"conffile"]) {
9399 FILE *input = [database_ input];
9400 if (button == [alert cancelButtonIndex])
9401 fprintf(input, "N\n");
9402 else if (button == [alert firstOtherButtonIndex])
9403 fprintf(input, "Y\n");
9406 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9407 } else if ([context isEqualToString:@"fixhalf"]) {
9408 if (button == [alert cancelButtonIndex]) {
9409 @synchronized (self) {
9410 for (Package *broken in (id) broken_) {
9412 NSString *id(ShellEscape([broken id]));
9413 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
9414 " /var/lib/dpkg/info/%@.prerm"
9415 " /var/lib/dpkg/info/%@.postrm"
9416 " /var/lib/dpkg/info/%@.preinst"
9417 " /var/lib/dpkg/info/%@.postinst"
9418 " /var/lib/dpkg/info/%@.extrainst_"
9419 "", id, id, id, id, id] UTF8String]);
9425 } else if (button == [alert firstOtherButtonIndex]) {
9426 [broken_ removeAllObjects];
9430 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9431 } else if ([context isEqualToString:@"upgrade"]) {
9432 if (button == [alert firstOtherButtonIndex]) {
9433 @synchronized (self) {
9434 for (Package *essential in (id) essential_)
9435 [essential install];
9440 } else if (button == [alert firstOtherButtonIndex] + 1) {
9442 } else if (button == [alert cancelButtonIndex]) {
9446 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9450 - (void) system:(NSString *)command {
9451 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9454 system([command UTF8String]);
9460 - (void) applicationWillSuspend {
9462 [super applicationWillSuspend];
9465 - (BOOL) isSafeToSuspend {
9468 NSLog(@"isSafeToSuspend: locked_ != 0");
9473 if ([tabbar_ modalViewController] != nil)
9476 // Use external process status API internally.
9477 // This is probably a really bad idea.
9478 // XXX: what is the point of this? does this solve anything at all?
9479 uint64_t status = 0;
9481 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9482 notify_get_state(notify_token, &status);
9483 notify_cancel(notify_token);
9488 NSLog(@"isSafeToSuspend: status != 0");
9494 NSLog(@"isSafeToSuspend: -> true");
9499 - (void) suspendReturningToLastApp:(BOOL)returning {
9500 if ([self isSafeToSuspend])
9501 [super suspendReturningToLastApp:returning];
9505 if ([self isSafeToSuspend])
9509 - (void) applicationSuspend {
9510 if ([self isSafeToSuspend])
9511 [super applicationSuspend];
9514 - (void) applicationSuspend:(__GSEvent *)event {
9515 if ([self isSafeToSuspend])
9516 [super applicationSuspend:event];
9519 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9520 if ([self isSafeToSuspend])
9521 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9524 - (void) _setSuspended:(BOOL)value {
9525 if ([self isSafeToSuspend])
9526 [super _setSuspended:value];
9529 - (UIProgressHUD *) addProgressHUD {
9530 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9531 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9533 [window_ setUserInteractionEnabled:NO];
9535 UIViewController *target(tabbar_);
9536 if (UIViewController *modal = [target modalViewController])
9539 [hud showInView:[target view]];
9545 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9546 [self unlockSuspend];
9548 [hud removeFromSuperview];
9549 [window_ setUserInteractionEnabled:YES];
9552 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9553 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9556 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9557 NSString *scheme([[url scheme] lowercaseString]);
9558 if ([[url absoluteString] length] <= [scheme length] + 3)
9560 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9561 NSArray *components([path componentsSeparatedByString:@"/"]);
9563 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9564 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9565 if (controller != nil)
9566 [controller setDelegate:self];
9570 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9573 NSString *base([components objectAtIndex:0]);
9575 CyteViewController *controller = nil;
9577 if ([base isEqualToString:@"url"]) {
9578 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9579 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9580 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9581 } else if (!external && [components count] == 1) {
9582 if ([base isEqualToString:@"sources"]) {
9583 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9586 if ([base isEqualToString:@"home"]) {
9587 controller = [[[HomeController alloc] init] autorelease];
9590 if ([base isEqualToString:@"sections"]) {
9591 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9594 if ([base isEqualToString:@"search"]) {
9595 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9598 if ([base isEqualToString:@"changes"]) {
9599 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9602 if ([base isEqualToString:@"installed"]) {
9603 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9605 } else if ([components count] == 2) {
9606 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9608 if ([base isEqualToString:@"package"]) {
9609 controller = [self pageForPackage:argument withReferrer:referrer];
9612 if (!external && [base isEqualToString:@"search"]) {
9613 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9616 if (!external && [base isEqualToString:@"sections"]) {
9617 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9619 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9622 if ([base isEqualToString:@"sources"]) {
9623 if ([argument isEqualToString:@"add"]) {
9624 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9625 [(SourcesController *)controller showAddSourcePrompt];
9627 Source *source([database_ sourceWithKey:argument]);
9628 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9632 if (!external && [base isEqualToString:@"launch"]) {
9633 [self launchApplicationWithIdentifier:argument suspended:NO];
9636 } else if (!external && [components count] == 3) {
9637 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9638 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9640 if ([base isEqualToString:@"package"]) {
9641 if ([arg2 isEqualToString:@"settings"]) {
9642 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9643 } else if ([arg2 isEqualToString:@"files"]) {
9644 if (Package *package = [database_ packageWithName:arg1]) {
9645 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9646 [(FileTable *)controller setPackage:package];
9651 if ([base isEqualToString:@"sections"]) {
9652 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9653 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9654 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9658 [controller setDelegate:self];
9662 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9663 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9666 [tabbar_ setUnselectedViewController:page];
9671 - (void) applicationOpenURL:(NSURL *)url {
9672 [super applicationOpenURL:url];
9677 [self openCydiaURL:url forExternal:YES];
9680 - (void) applicationWillResignActive:(UIApplication *)application {
9681 // Stop refreshing if you get a phone call or lock the device.
9682 if ([tabbar_ updating])
9683 [tabbar_ cancelUpdate];
9685 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9686 [super applicationWillResignActive:application];
9689 - (void) saveState {
9690 [[NSDictionary dictionaryWithObjectsAndKeys:
9691 @"InterfaceState", [tabbar_ navigationURLCollection],
9692 @"LastClosed", [NSDate date],
9693 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
9694 nil] writeToFile:@ SavedState_ atomically:YES];
9699 - (void) applicationWillTerminate:(UIApplication *)application {
9703 - (void) applicationDidEnterBackground:(UIApplication *)application {
9704 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9705 return [self terminateWithSuccess];
9706 Backgrounded_ = [NSDate date];
9710 - (void) applicationWillEnterForeground:(UIApplication *)application {
9711 if (Backgrounded_ == nil)
9714 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
9716 if (interval <= -(30*60)) {
9717 [tabbar_ setSelectedIndex:0];
9718 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9721 if (interval <= -(15*60)) {
9722 if (IsReachable("cydia.saurik.com")) {
9723 [tabbar_ beginUpdate];
9724 [appcache_ reloadURLWithCache:YES];
9728 if ([database_ delocked])
9732 - (void) setConfigurationData:(NSString *)data {
9733 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9735 if (!conffile_r(data)) {
9736 lprintf("E:invalid conffile\n");
9740 NSString *ofile = conffile_r[1];
9741 //NSString *nfile = conffile_r[2];
9743 UIAlertView *alert = [[[UIAlertView alloc]
9744 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9745 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9747 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9749 UCLocalize("ACCEPT_NEW_COPY"),
9750 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9754 [alert setContext:@"conffile"];
9755 [alert setNumberOfRows:2];
9759 - (void) addStashController {
9761 stash_ = [[[StashController alloc] init] autorelease];
9762 [window_ addSubview:[stash_ view]];
9765 - (void) removeStashController {
9766 [[stash_ view] removeFromSuperview];
9768 [self unlockSuspend];
9772 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9773 UpdateExternalStatus(1);
9774 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9775 UpdateExternalStatus(0);
9777 [self removeStashController];
9778 [self reloadSpringBoard];
9781 - (void) setupViewControllers {
9782 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9784 NSMutableArray *items;
9785 if (kCFCoreFoundationVersionNumber < 800) {
9786 items = [NSMutableArray arrayWithObjects:
9787 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9788 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9789 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9790 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9791 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9794 items = [NSMutableArray arrayWithObjects:
9795 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9796 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9797 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9798 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9799 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9803 NSMutableArray *controllers([NSMutableArray array]);
9804 for (UITabBarItem *item in items) {
9805 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9806 [controller setTabBarItem:item];
9807 [controllers addObject:controller];
9809 [tabbar_ setViewControllers:controllers];
9811 [tabbar_ setUpdateDelegate:self];
9814 - (void) _sendMemoryWarningNotification {
9815 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9816 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9818 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9821 - (void) _sendMemoryWarningNotifications {
9823 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9829 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9831 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9834 - (void) applicationDidFinishLaunching:(id)unused {
9835 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9838 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9839 [self setApplicationSupportsShakeToEdit:NO];
9841 @synchronized (HostConfig_) {
9842 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9845 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9846 initWithMemoryCapacity:524288
9847 diskCapacity:10485760
9848 diskPath:Cache("SDURLCache")
9851 [CydiaWebViewController _initialize];
9853 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9855 // this would disallow http{,s} URLs from accessing this data
9856 //[WebView registerURLSchemeAsLocal:@"cydia"];
9858 Font12_ = [UIFont systemFontOfSize:12];
9859 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9860 Font14_ = [UIFont systemFontOfSize:14];
9861 Font18_ = [UIFont systemFontOfSize:18];
9862 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9863 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9865 essential_ = [NSMutableArray arrayWithCapacity:4];
9866 broken_ = [NSMutableArray arrayWithCapacity:4];
9868 // XXX: I really need this thing... like, seriously... I'm sorry
9869 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9870 [appcache_ reloadData];
9872 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9873 [window_ orderFront:self];
9874 [window_ makeKey:self];
9875 [window_ setHidden:NO];
9877 if (access("/.cydia_no_stash", F_OK) == 0);
9881 [self addStashController];
9882 // XXX: this would be much cleaner as a yieldToSelector:
9883 // that way the removeStashController could happen right here inline
9884 // we also could no longer require the useless stash_ field anymore
9885 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9890 int error(stat("/", &root));
9891 _assert(error != -1);
9893 #define Stash_(path) do { \
9894 struct stat folder; \
9895 int error(lstat((path), &folder)); \
9896 if (error != -1 && ( \
9897 folder.st_dev == root.st_dev && \
9898 S_ISDIR(folder.st_mode) \
9899 ) || error == -1 && ( \
9900 errno == ENOENT || \
9905 Stash_("/Applications");
9906 Stash_("/Library/Ringtones");
9907 Stash_("/Library/Wallpaper");
9908 //Stash_("/usr/bin");
9909 Stash_("/usr/include");
9910 Stash_("/usr/share");
9911 //Stash_("/var/lib");
9915 database_ = [Database sharedInstance];
9916 [database_ setDelegate:self];
9918 [window_ setUserInteractionEnabled:NO];
9919 [self setupViewControllers];
9921 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9922 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9923 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9925 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9926 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9927 [emulated_ setSelectedIndex:0];
9929 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9930 [emulated_ concealTabBarSelection];
9932 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9933 [window_ setRootViewController:emulated_];
9935 [window_ addSubview:[emulated_ view]];
9937 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9941 - (NSArray *) defaultStartPages {
9942 NSMutableArray *standard = [NSMutableArray array];
9943 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9944 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9945 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9946 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9947 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9953 if ([emulated_ modalViewController] != nil)
9954 [emulated_ dismissModalViewControllerAnimated:YES];
9955 [window_ setUserInteractionEnabled:NO];
9957 [self reloadDataWithInvocation:nil];
9958 [self refreshIfPossible];
9961 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
9963 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
9964 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9965 int standardIndex = 0;
9966 NSArray *standard = [self defaultStartPages];
9973 NSDate *closed = [state objectForKey:@"LastClosed"];
9974 if (valid && closed != nil) {
9975 NSTimeInterval interval([closed timeIntervalSinceNow]);
9976 if (interval <= -(30*60))
9980 if (valid && [saved count] != [standard count])
9984 for (unsigned int i = 0; i < [standard count]; i++) {
9985 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9986 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9987 // but it's good enough for now.
9988 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9995 NSArray *items = nil;
9997 [tabbar_ setSelectedIndex:savedIndex];
10000 [tabbar_ setSelectedIndex:standardIndex];
10004 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10005 NSArray *stack = [items objectAtIndex:tab];
10006 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10007 NSMutableArray *current = [NSMutableArray array];
10009 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10010 NSString *addr = [stack objectAtIndex:nav];
10011 NSURL *url = [NSURL URLWithString:addr];
10012 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10014 [current addObject:page];
10017 [navigation setViewControllers:current];
10020 // (Try to) show the startup URL.
10021 if (starturl_ != nil) {
10022 [self openCydiaURL:starturl_ forExternal:YES];
10027 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10028 if (item != nil && IsWildcat_) {
10029 [sheet showFromBarButtonItem:item animated:YES];
10031 [sheet showInView:window_];
10035 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10036 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10037 [progress setTitle:task];
10038 [progress addProgressEvent:event];
10041 - (void) addProgressEventForTask:(NSArray *)data {
10042 CydiaProgressEvent *event([data objectAtIndex:0]);
10043 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10044 [self addProgressEvent:event forTask:task];
10047 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10048 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10054 id Alloc_(id self, SEL selector) {
10055 id object = alloc_(self, selector);
10056 lprintf("[%s]A-%p\n", self->isa->name, object);
10061 id Dealloc_(id self, SEL selector) {
10062 id object = dealloc_(self, selector);
10063 lprintf("[%s]D-%p\n", self->isa->name, object);
10067 Class $NSURLConnection;
10069 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10070 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10072 NSURL *url([copy URL]);
10074 NSString *host([url host]);
10075 NSString *scheme([[url scheme] lowercaseString]);
10077 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10079 @synchronized (HostConfig_) {
10080 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10081 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10082 [copy setHTTPShouldUsePipelining:YES];
10084 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10085 if ([control isEqualToString:@"max-age=0"])
10086 if ([CachedURLs_ containsObject:url]) {
10088 NSLog(@"~~~: %@", url);
10091 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10093 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10094 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10095 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10099 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10105 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10106 CGSize size([[UIScreen mainScreen] bounds].size);
10107 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10108 if ([$WAKWindow hasLandscapeOrientation])
10109 std::swap(size.width, size.height);*/
10113 Class $NSUserDefaults;
10115 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10116 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10117 return Cache("LocalStorage");
10118 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10121 static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) {
10124 if (CFGetTypeID(type) != CFDictionaryGetTypeID())
10126 CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers));
10128 return [(NSMutableDictionary *) copy autorelease];
10131 int main(int argc, char *argv[]) {
10132 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
10136 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10140 UpdateExternalStatus(0);
10142 UIScreen *screen([UIScreen mainScreen]);
10143 if ([screen respondsToSelector:@selector(scale)])
10144 ScreenScale_ = [screen scale];
10148 UIDevice *device([UIDevice currentDevice]);
10149 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10150 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10151 if (idiom == UIUserInterfaceIdiomPad)
10155 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10157 RegEx pattern("([0-9]+\\.[0-9]+).*");
10159 if (pattern([device systemVersion]))
10160 Firmware_ = pattern[1];
10161 if (pattern(Cydia_))
10162 Major_ = pattern[1];
10164 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10166 HostConfig_ = [[[NSObject alloc] init] autorelease];
10167 @synchronized (HostConfig_) {
10168 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10169 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10170 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10171 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10174 NSString *ui(@"ui/ios");
10176 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10177 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10178 UI_ = CydiaURL(ui);
10180 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10182 /* Library Hacks {{{ */
10183 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10185 $WAKWindow = objc_getClass("WAKWindow");
10186 if ($WAKWindow != NULL)
10187 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10188 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10190 $NSURLConnection = objc_getClass("NSURLConnection");
10191 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10192 if (NSURLConnection$init$ != NULL) {
10193 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10194 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10197 $NSUserDefaults = objc_getClass("NSUserDefaults");
10198 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10199 if (NSUserDefaults$objectForKey$ != NULL) {
10200 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10201 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10204 /* Set Locale {{{ */
10205 Locale_ = CFLocaleCopyCurrent();
10206 Languages_ = [NSLocale preferredLanguages];
10208 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10209 //NSLog(@"%@", [Languages_ description]);
10212 if (Locale_ != NULL)
10213 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10214 else if (Languages_ != nil && [Languages_ count] != 0)
10215 lang = [[Languages_ objectAtIndex:0] UTF8String];
10217 // XXX: consider just setting to C and then falling through?
10220 if (lang != NULL) {
10221 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
10222 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10225 NSLog(@"Setting Language: %s", lang);
10227 if (lang != NULL) {
10228 setenv("LANG", lang, true);
10229 std::setlocale(LC_ALL, lang);
10232 /* Index Collation {{{ */
10233 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10234 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10235 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10236 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10237 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10238 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10240 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10242 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10243 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10244 for (NSInteger offset : (NSInteger[]) {0,1,3,4,6,7,9,10,12,13,15,16,18,25,26,29,30,33,34,37,38,42,43,46,47,50,51})
10245 CollationOffset_.push_back(offset);
10246 CollationTitles_ = [NSArray arrayWithObjects:@"1 畫",@"2 畫",@"3 畫",@"4 畫",@"5 畫",@"6 畫",@"7 畫",@"8 畫",@"9 畫",@"10 畫",@"11 畫",@"12 畫",@"13 畫",@"14 畫",@"15 畫",@"16 畫",@"17 畫",@"18 畫",@"19 畫",@"20 畫",@"21 畫",@"22 畫",@"23 畫",@"24 畫",@"25 畫以上",@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#",nil];
10247 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];
10250 CollationThumbs_ = [collation sectionIndexTitles];
10251 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10252 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10254 CollationTitles_ = [collation sectionTitles];
10255 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10257 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10258 if (&transform != NULL && transform != nil) {
10259 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10260 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10261 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10262 UErrorCode code(U_ZERO_ERROR);
10263 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10264 if (!U_SUCCESS(code))
10265 NSLog(@"%s", u_errorName(code));
10269 } @catch (NSException *e) {
10273 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10275 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];
10276 for (NSInteger offset(0); offset != 28; ++offset)
10277 CollationOffset_.push_back(offset);
10279 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];
10280 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];
10283 /* Parse Arguments {{{ */
10284 bool substrate(false);
10290 for (int argi(1); argi != argc; ++argi)
10291 if (strcmp(argv[argi], "--") == 0) {
10293 argv[argi] = argv[0];
10299 for (int argi(1); argi != arge; ++argi)
10300 if (strcmp(args[argi], "--substrate") == 0)
10303 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10307 App_ = [[NSBundle mainBundle] bundlePath];
10310 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10311 mkdir([Cache_ UTF8String], 0755);
10313 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10314 alloc_ = alloc->method_imp;
10315 alloc->method_imp = (IMP) &Alloc_;*/
10317 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10318 dealloc_ = dealloc->method_imp;
10319 dealloc->method_imp = (IMP) &Dealloc_;*/
10321 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10322 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10324 /* System Information {{{ */
10328 size = sizeof(maxproc);
10329 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10330 perror("sysctlbyname(\"kern.maxproc\", ?)");
10331 else if (maxproc < 64) {
10333 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10334 perror("sysctlbyname(\"kern.maxproc\", #)");
10337 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10338 char *osversion = new char[size];
10339 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10340 perror("sysctlbyname(\"kern.osversion\", ?)");
10342 System_ = [NSString stringWithUTF8String:osversion];
10344 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10345 char *machine = new char[size];
10346 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10347 perror("sysctlbyname(\"hw.machine\", ?)");
10349 Machine_ = machine;
10351 int64_t usermem(0);
10352 size = sizeof(usermem);
10353 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10356 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10357 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10358 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10360 UniqueID_ = UniqueIdentifier(device);
10362 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10363 Product_ = [info objectForKey:@"SafariProductVersion"];
10364 Safari_ = [info objectForKey:@"CFBundleVersion"];
10367 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10369 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Safari_))
10370 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[1], agent];
10371 if (RegEx match = RegEx("([0-9]+[A-Z][0-9]+[a-z]?).*", System_))
10372 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[1], agent];
10373 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Product_))
10374 agent = [NSString stringWithFormat:@"Version/%@ %@", match[1], agent];
10376 UserAgent_ = agent;
10378 /* Load Database {{{ */
10379 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10382 mkdir("/var/mobile/Library/Cydia", 0755);
10383 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
10386 Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")));
10387 Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")));
10388 Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")));
10389 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
10392 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
10394 if (Values_ == nil)
10395 Values_ = [metadata objectForKey:@"Values"];
10396 if (Values_ == nil)
10397 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10399 if (Sections_ == nil)
10400 Sections_ = [metadata objectForKey:@"Sections"];
10401 if (Sections_ == nil)
10402 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10404 if (Sources_ == nil)
10405 Sources_ = [metadata objectForKey:@"Sources"];
10406 if (Sources_ == nil)
10407 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10409 // XXX: this wrong, but in a way that doesn't matter :/
10410 if (Version_ == nil)
10411 Version_ = [metadata objectForKey:@"Version"];
10412 if (Version_ == nil)
10413 Version_ = [NSNumber numberWithUnsignedInt:0];
10415 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
10417 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
10420 NSLog(@"unable to import package preferences... from 2010? oh well :/");
10423 if ([Version_ unsignedIntValue] == 0) {
10424 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10425 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10426 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10427 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10429 Version_ = [NSNumber numberWithUnsignedInt:1];
10431 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:@ CacheState_]) {
10432 [cache removeObjectForKey:@"LastUpdate"];
10433 [cache writeToFile:@ CacheState_ atomically:YES];
10437 _H<NSMutableArray> broken([NSMutableArray array]);
10438 for (NSString *key in (id) Sources_)
10439 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound || ![([[Sources_ objectForKey:key] objectForKey:@"URI"] ?: @"/") hasSuffix:@"/"])
10440 [broken addObject:key];
10441 if ([broken count] != 0)
10442 for (NSString *key in (id) broken)
10443 [Sources_ removeObjectForKey:key];
10447 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
10450 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10452 if (kCFCoreFoundationVersionNumber > 1000)
10453 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
10455 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10457 if (access("/User", F_OK) != 0 || version != 6) {
10459 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
10463 if (access("/tmp/cydia.chk", F_OK) == 0) {
10464 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10465 _assert(errno == ENOENT);
10466 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10467 _assert(errno == ENOENT);
10470 system("/usr/libexec/cydia/cydo /bin/ln -sf /var/mobile/Library/Caches/com.saurik.Cydia/sources.list /etc/apt/sources.list.d/cydia.list");
10472 /* APT Initialization {{{ */
10473 _assert(pkgInitConfig(*_config));
10474 _assert(pkgInitSystem(*_config, _system));
10477 _config->Set("APT::Acquire::Translation", lang);
10479 // XXX: this timeout might be important :(
10480 //_config->Set("Acquire::http::Timeout", 15);
10482 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10484 mkdir([Cache("archives") UTF8String], 0755);
10485 mkdir([Cache("archives/partial") UTF8String], 0755);
10486 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10488 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
10489 _config->Set("Dir::State", [Cache_ UTF8String]);
10491 mkdir([Cache("lists") UTF8String], 0755);
10492 mkdir([Cache("lists/partial") UTF8String], 0755);
10493 mkdir([Cache("periodic") UTF8String], 0755);
10494 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10496 std::string logs("/var/mobile/Library/Logs/Cydia");
10497 mkdir(logs.c_str(), 0755);
10498 _config->Set("Dir::Log::Terminal", logs + "/apt.log");
10500 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
10502 /* Color Choices {{{ */
10503 space_ = CGColorSpaceCreateDeviceRGB();
10505 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10506 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10507 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10508 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10509 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10510 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10511 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10512 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10513 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10514 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10516 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10517 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10519 /* UIKit Configuration {{{ */
10520 // XXX: I have a feeling this was important
10521 //UIKeyboardDisableAutomaticAppearance();
10524 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10525 $SBSCopyIconImagePNGDataForDisplayIdentifier = reinterpret_cast<NSData *(*)(NSString *)>(dlsym(RTLD_DEFAULT, "SBSCopyIconImagePNGDataForDisplayIdentifier"));
10527 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10528 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10529 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10531 PulseInterval_ = fast ? 50000 : 500000;
10533 Colon_ = UCLocalize("COLON_DELIMITED");
10534 Elision_ = UCLocalize("ELISION");
10535 Error_ = UCLocalize("ERROR");
10536 Warning_ = UCLocalize("WARNING");
10539 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10541 CGColorSpaceRelease(space_);
10542 CFRelease(Locale_);