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 - (NSArray *) downgrades {
2739 NSMutableArray *versions([NSMutableArray arrayWithCapacity:4]);
2741 for (auto version(iterator_.VersionList()); !version.end(); ++version) {
2742 if (version == version_)
2744 Package *package([[[Package allocWithZone:NULL] initWithVersion:version withZone:NULL inPool:NULL database:database_] autorelease]);
2745 if ([package source] == nil)
2747 [versions addObject:package];
2753 - (NSString *) section {
2754 if (section$_ == nil) {
2755 if (section_ == NULL)
2758 _profile(Package$section$mappedSectionForPointer)
2759 section$_ = [database_ mappedSectionForPointer:section_];
2764 - (NSString *) simpleSection {
2765 if (NSString *section = [self section])
2766 return Simplify(section);
2771 - (NSString *) longSection {
2772 if (NSString *section = [self section])
2773 return LocalizeSection(section);
2778 - (NSString *) shortSection {
2779 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2782 - (NSString *) uri {
2785 pkgIndexFile *index;
2786 pkgCache::PkgFileIterator file(file_.File());
2787 if (![database_ list].FindIndex(file, index))
2789 return [NSString stringWithUTF8String:iterator_->Path];
2790 //return [NSString stringWithUTF8String:file.Site()];
2791 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2795 - (MIMEAddress *) maintainer {
2796 @synchronized (database_) {
2797 if ([database_ era] != era_ || file_.end())
2800 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2801 const std::string &maintainer(parser->Maintainer());
2802 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2805 - (NSString *) md5sum {
2806 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2810 @synchronized (database_) {
2811 if ([database_ era] != era_ || version_.end())
2814 return version_->InstalledSize;
2817 - (NSString *) longDescription {
2818 @synchronized (database_) {
2819 if ([database_ era] != era_ || file_.end())
2822 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2823 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2825 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2826 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2827 if ([lines count] < 2)
2830 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2831 for (size_t i(1), e([lines count]); i != e; ++i) {
2832 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2833 [trimmed addObject:trim];
2836 return [trimmed componentsJoinedByString:@"\n"];
2839 - (NSString *) shortDescription {
2840 if (parsed_ != NULL)
2841 return static_cast<NSString *>(parsed_->tagline_);
2843 @synchronized (database_) {
2844 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2846 const char *start, *end;
2847 if (!parser.ShortDesc(start, end))
2850 if (end - start > 200)
2854 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2857 while (end != start && end[-1] == '\r')
2861 return [(id) CYStringCreate(start, end - start) autorelease];
2865 _profile(Package$index)
2866 CFStringRef name((CFStringRef) [self name]);
2867 if (CFStringGetLength(name) == 0)
2869 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2870 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2872 return toupper(character);
2876 - (PackageValue *) metadata {
2881 PackageValue *metadata([self metadata]);
2882 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2885 - (bool) subscribed {
2886 return [self metadata]->subscribed_;
2889 - (bool) setSubscribed:(bool)subscribed {
2890 PackageValue *metadata([self metadata]);
2891 if (metadata->subscribed_ == subscribed)
2893 metadata->subscribed_ = subscribed;
2901 - (NSString *) latest {
2905 - (NSString *) installed {
2909 - (BOOL) uninstalled {
2910 return installed_.empty();
2913 - (BOOL) upgradableAndEssential:(BOOL)essential {
2914 _profile(Package$upgradableAndEssential)
2915 pkgCache::VerIterator current(iterator_.CurrentVer());
2917 return essential && essential_;
2919 return version_ != current;
2923 - (BOOL) essential {
2928 return [database_ cache][iterator_].InstBroken();
2931 - (BOOL) unfiltered {
2932 _profile(Package$unfiltered$obsolete)
2933 if (_unlikely(obsolete_))
2937 _profile(Package$unfiltered$role)
2938 if (_unlikely(role_ > 3))
2946 if (![self unfiltered])
2951 _profile(Package$visible$section)
2952 section = [self section];
2955 _profile(Package$visible$isSectionVisible)
2956 if (!isSectionVisible(section))
2964 unsigned char current(iterator_->CurrentState);
2965 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2968 - (BOOL) halfConfigured {
2969 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2972 - (BOOL) halfInstalled {
2973 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2977 @synchronized (database_) {
2978 if ([database_ era] != era_ || iterator_.end())
2981 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2982 return state.Mode != pkgDepCache::ModeKeep;
2985 - (NSString *) mode {
2986 @synchronized (database_) {
2987 if ([database_ era] != era_ || iterator_.end())
2990 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2992 switch (state.Mode) {
2993 case pkgDepCache::ModeDelete:
2994 if ((state.iFlags & pkgDepCache::Purge) != 0)
2998 case pkgDepCache::ModeKeep:
2999 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3000 return @"REINSTALL";
3001 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
3005 case pkgDepCache::ModeInstall:
3006 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3007 return @"REINSTALL";
3008 else*/ switch (state.Status) {
3010 return @"DOWNGRADE";
3016 return @"NEW_INSTALL";
3027 - (NSString *) name {
3028 return name_.empty() ? id_ : name_;
3031 - (UIImage *) icon {
3032 NSString *section = [self simpleSection];
3035 if (parsed_ != NULL)
3036 if (NSString *href = parsed_->icon_)
3037 if ([href hasPrefix:@"file:///"])
3038 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3039 if (icon == nil) if (section != nil)
3040 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
3041 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
3042 if ([dicon hasPrefix:@"file:///"])
3043 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3045 icon = [UIImage imageNamed:@"unknown.png"];
3049 - (NSString *) homepage {
3050 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
3053 - (NSString *) depiction {
3054 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
3057 - (MIMEAddress *) author {
3058 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
3061 - (NSString *) support {
3062 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
3065 - (NSArray *) files {
3066 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
3067 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
3070 fin.open([path UTF8String]);
3075 while (std::getline(fin, line))
3076 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
3081 - (NSString *) state {
3082 @synchronized (database_) {
3083 if ([database_ era] != era_ || file_.end())
3086 switch (iterator_->CurrentState) {
3087 case pkgCache::State::NotInstalled:
3088 return @"NotInstalled";
3089 case pkgCache::State::UnPacked:
3091 case pkgCache::State::HalfConfigured:
3092 return @"HalfConfigured";
3093 case pkgCache::State::HalfInstalled:
3094 return @"HalfInstalled";
3095 case pkgCache::State::ConfigFiles:
3096 return @"ConfigFiles";
3097 case pkgCache::State::Installed:
3098 return @"Installed";
3099 case pkgCache::State::TriggersAwaited:
3100 return @"TriggersAwaited";
3101 case pkgCache::State::TriggersPending:
3102 return @"TriggersPending";
3105 return (NSString *) [NSNull null];
3108 - (NSString *) selection {
3109 @synchronized (database_) {
3110 if ([database_ era] != era_ || file_.end())
3113 switch (iterator_->SelectedState) {
3114 case pkgCache::State::Unknown:
3116 case pkgCache::State::Install:
3118 case pkgCache::State::Hold:
3120 case pkgCache::State::DeInstall:
3121 return @"DeInstall";
3122 case pkgCache::State::Purge:
3126 return (NSString *) [NSNull null];
3129 - (NSArray *) warnings {
3130 @synchronized (database_) {
3131 if ([database_ era] != era_ || file_.end())
3134 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3135 const char *name(iterator_.Name());
3137 size_t length(strlen(name));
3138 if (length < 2) invalid:
3139 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3140 else for (size_t i(0); i != length; ++i)
3142 /* XXX: technically this is not allowed */
3143 (name[i] < 'A' || name[i] > 'Z') &&
3144 (name[i] < 'a' || name[i] > 'z') &&
3145 (name[i] < '0' || name[i] > '9') &&
3146 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3149 if (strcmp(name, "cydia") != 0) {
3152 bool _private = false;
3154 bool dbstash = false;
3155 bool dsstore = false;
3157 bool repository = [[self section] isEqualToString:@"Repositories"];
3159 if (NSArray *files = [self files])
3160 for (NSString *file in files)
3161 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3163 else if (!user && [file isEqualToString:@"/User"])
3165 else if (!_private && [file isEqualToString:@"/private"])
3167 else if (!stash && [file isEqualToString:@"/var/stash"])
3169 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3171 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3174 /* XXX: this is not sensitive enough. only some folders are valid. */
3175 if (cydia && !repository)
3176 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3178 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3180 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3182 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3184 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3186 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3189 return [warnings count] == 0 ? nil : warnings;
3192 - (NSArray *) applications {
3193 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3195 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3197 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3198 if (NSArray *files = [self files])
3199 for (NSString *file in files)
3200 if (application_r(file)) {
3201 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3204 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3205 if (id == nil || [id isEqualToString:me])
3208 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3210 display = application_r[1];
3212 NSString *bundle([file stringByDeletingLastPathComponent]);
3213 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3214 // XXX: maybe this should check if this is really a string, not just for length
3215 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3217 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3219 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3220 [applications addObject:application];
3222 [application addObject:id];
3223 [application addObject:display];
3224 [application addObject:url];
3227 return [applications count] == 0 ? nil : applications;
3230 - (Source *) source {
3231 if (source_ == nil) {
3232 @synchronized (database_) {
3233 if ([database_ era] != era_ || file_.end())
3234 source_ = (Source *) [NSNull null];
3236 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3240 return source_ == (Source *) [NSNull null] ? nil : source_;
3243 - (time_t) upgraded {
3247 - (uint32_t) recent {
3248 return std::numeric_limits<uint32_t>::max() - upgraded_;
3255 - (BOOL) matches:(NSArray *)query {
3256 if (query == nil || [query count] == 0)
3265 string = [self name];
3266 length = [string length];
3269 for (NSString *term in query) {
3270 range = [string rangeOfString:term options:MatchCompareOptions_];
3271 if (range.location != NSNotFound)
3272 rank_ -= 6 * 1000000 / length;
3277 length = [string length];
3280 for (NSString *term in query) {
3281 range = [string rangeOfString:term options:MatchCompareOptions_];
3282 if (range.location != NSNotFound)
3283 rank_ -= 6 * 1000000 / length;
3287 string = [self shortDescription];
3288 length = [string length];
3289 NSUInteger stop(std::min<NSUInteger>(length, 200));
3292 for (NSString *term in query) {
3293 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3294 if (range.location != NSNotFound)
3295 rank_ -= 2 * 100000;
3301 - (NSArray *) tags {
3305 - (BOOL) hasTag:(NSString *)tag {
3306 return tags_ == nil ? NO : [tags_ containsObject:tag];
3309 - (NSString *) primaryPurpose {
3310 for (NSString *tag in (NSArray *) tags_)
3311 if ([tag hasPrefix:@"purpose::"])
3312 return [tag substringFromIndex:9];
3316 - (NSArray *) purposes {
3317 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3318 for (NSString *tag in (NSArray *) tags_)
3319 if ([tag hasPrefix:@"purpose::"])
3320 [purposes addObject:[tag substringFromIndex:9]];
3321 return [purposes count] == 0 ? nil : purposes;
3324 - (bool) isCommercial {
3325 return [self hasTag:@"cydia::commercial"];
3328 - (void) setIndex:(size_t)index {
3329 if (metadata_->index_ != index)
3330 metadata_->index_ = index;
3333 - (CYString &) cyname {
3334 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3337 - (uint32_t) compareBySection:(NSArray *)sections {
3338 NSString *section([self section]);
3339 for (size_t i(0), e([sections count]); i != e; ++i) {
3340 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3344 return _not(uint32_t);
3348 @synchronized (database_) {
3349 if ([database_ era] != era_ || file_.end())
3352 pkgProblemResolver *resolver = [database_ resolver];
3353 resolver->Clear(iterator_);
3355 pkgCacheFile &cache([database_ cache]);
3356 cache->SetReInstall(iterator_, false);
3357 cache->MarkKeep(iterator_, false);
3361 @synchronized (database_) {
3362 if ([database_ era] != era_ || file_.end())
3365 pkgProblemResolver *resolver = [database_ resolver];
3366 resolver->Clear(iterator_);
3367 resolver->Protect(iterator_);
3369 pkgCacheFile &cache([database_ cache]);
3370 cache->SetCandidateVersion(version_);
3371 cache->SetReInstall(iterator_, false);
3372 cache->MarkInstall(iterator_, false);
3374 pkgDepCache::StateCache &state((*cache)[iterator_]);
3375 if (!state.Install())
3376 cache->SetReInstall(iterator_, true);
3380 @synchronized (database_) {
3381 if ([database_ era] != era_ || file_.end())
3384 pkgProblemResolver *resolver = [database_ resolver];
3385 resolver->Clear(iterator_);
3386 resolver->Remove(iterator_);
3387 resolver->Protect(iterator_);
3389 pkgCacheFile &cache([database_ cache]);
3390 cache->SetReInstall(iterator_, false);
3391 cache->MarkDelete(iterator_, true);
3396 /* Section Class {{{ */
3397 @interface Section : NSObject {
3401 _H<NSString> localized_;
3404 - (NSComparisonResult) compareByLocalized:(Section *)section;
3405 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3406 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3407 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3409 - (NSString *) name;
3410 - (void) setName:(NSString *)name;
3416 - (void) addToCount;
3418 - (void) setCount:(size_t)count;
3419 - (NSString *) localized;
3423 @implementation Section
3425 - (NSComparisonResult) compareByLocalized:(Section *)section {
3426 NSString *lhs(localized_);
3427 NSString *rhs([section localized]);
3429 /*if ([lhs length] != 0 && [rhs length] != 0) {
3430 unichar lhc = [lhs characterAtIndex:0];
3431 unichar rhc = [rhs characterAtIndex:0];
3433 if (isalpha(lhc) && !isalpha(rhc))
3434 return NSOrderedAscending;
3435 else if (!isalpha(lhc) && isalpha(rhc))
3436 return NSOrderedDescending;
3439 return [lhs compare:rhs options:LaxCompareOptions_];
3442 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3443 if ((self = [self initWithName:name localize:NO]) != nil) {
3444 if (localized != nil)
3445 localized_ = localized;
3449 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3450 return [self initWithName:name row:0 localize:localize];
3453 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3454 if ((self = [super init]) != nil) {
3458 localized_ = LocalizeSection(name_);
3462 - (NSString *) name {
3466 - (void) setName:(NSString *)name {
3482 - (void) addToCount {
3486 - (void) setCount:(size_t)count {
3490 - (NSString *) localized {
3497 class CydiaLogCleaner :
3498 public pkgArchiveCleaner
3501 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3506 /* Database Implementation {{{ */
3507 @implementation Database
3509 + (Database *) sharedInstance {
3510 static _H<Database> instance;
3511 if (instance == nil)
3512 instance = [[[Database alloc] init] autorelease];
3520 - (void) releasePackages {
3521 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3522 CFArrayRemoveAllValues(packages_);
3526 // XXX: actually implement this thing
3528 [self releasePackages];
3529 NSRecycleZone(zone_);
3533 - (void) _readCydia:(NSNumber *)fd {
3534 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3535 std::istream is(&ib);
3538 static RegEx finish_r("finish:([^:]*)");
3540 while (std::getline(is, line)) {
3541 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3543 const char *data(line.c_str());
3544 size_t size = line.size();
3545 lprintf("C:%s\n", data);
3547 if (finish_r(data, size)) {
3548 NSString *finish = finish_r[1];
3549 int index = [Finishes_ indexOfObject:finish];
3550 if (index != INT_MAX && index > Finish_)
3560 - (void) _readStatus:(NSNumber *)fd {
3561 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3562 std::istream is(&ib);
3565 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3566 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3568 while (std::getline(is, line)) {
3569 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3571 const char *data(line.c_str());
3572 size_t size(line.size());
3573 lprintf("S:%s\n", data);
3575 if (conffile_r(data, size)) {
3576 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3577 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3578 } else if (strncmp(data, "status: ", 8) == 0) {
3579 // status: <package>: {unpacked,half-configured,installed}
3580 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3581 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3582 } else if (strncmp(data, "processing: ", 12) == 0) {
3583 // processing: configure: config-test
3584 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3585 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3586 } else if (pmstatus_r(data, size)) {
3587 std::string type([pmstatus_r[1] UTF8String]);
3589 NSString *package = pmstatus_r[2];
3590 if ([package isEqualToString:@"dpkg-exec"])
3593 float percent([pmstatus_r[3] floatValue]);
3594 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3596 NSString *string = pmstatus_r[4];
3598 if (type == "pmerror") {
3599 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3600 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3601 } else if (type == "pmstatus") {
3602 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3603 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3604 } else if (type == "pmconffile")
3605 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3607 lprintf("E:unknown pmstatus\n");
3609 lprintf("E:unknown status\n");
3617 - (void) _readOutput:(NSNumber *)fd {
3618 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3619 std::istream is(&ib);
3622 while (std::getline(is, line)) {
3623 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3625 lprintf("O:%s\n", line.c_str());
3627 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3628 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3640 - (Package *) packageWithName:(NSString *)name {
3643 @synchronized (self) {
3644 if (static_cast<pkgDepCache *>(cache_) == NULL)
3646 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3647 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3651 if ((self = [super init]) != nil) {
3658 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3660 size_t capacity(MetaFile_->active_);
3666 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3667 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3671 _assert(pipe(fds) != -1);
3674 _config->Set("APT::Keep-Fds::", cydiafd_);
3675 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3678 detachNewThreadSelector:@selector(_readCydia:)
3680 withObject:[NSNumber numberWithInt:fds[0]]
3683 _assert(pipe(fds) != -1);
3687 detachNewThreadSelector:@selector(_readStatus:)
3689 withObject:[NSNumber numberWithInt:fds[0]]
3692 _assert(pipe(fds) != -1);
3693 _assert(dup2(fds[0], 0) != -1);
3694 _assert(close(fds[0]) != -1);
3696 input_ = fdopen(fds[1], "a");
3698 _assert(pipe(fds) != -1);
3699 _assert(dup2(fds[1], 1) != -1);
3700 _assert(close(fds[1]) != -1);
3703 detachNewThreadSelector:@selector(_readOutput:)
3705 withObject:[NSNumber numberWithInt:fds[0]]
3710 - (pkgCacheFile &) cache {
3714 - (pkgDepCache::Policy *) policy {
3718 - (pkgRecords *) records {
3722 - (pkgProblemResolver *) resolver {
3726 - (pkgAcquire &) fetcher {
3730 - (pkgSourceList &) list {
3734 - (NSArray *) packages {
3735 return (NSArray *) packages_;
3738 - (NSArray *) sources {
3742 - (Source *) sourceWithKey:(NSString *)key {
3743 for (Source *source in [self sources]) {
3744 if ([[source key] isEqualToString:key])
3749 - (bool) popErrorWithTitle:(NSString *)title {
3752 while (!_error->empty()) {
3754 bool warning(!_error->PopMessage(error));
3759 size_t size(error.size());
3760 if (size == 0 || error[size - 1] != '\n')
3762 error.resize(size - 1);
3765 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3767 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3768 if (warning && no_pubkey(error.c_str()))
3771 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3777 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3778 return [self popErrorWithTitle:title] || !success;
3781 - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3782 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3790 if (access("/etc/apt/sources.list", F_OK) == 0)
3791 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend("/etc/apt/sources.list")];
3793 std::string base("/etc/apt/sources.list.d");
3794 if (DIR *sources = opendir(base.c_str())) {
3795 while (dirent *source = readdir(sources))
3796 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)
3797 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend((base + "/" + source->d_name).c_str())];
3801 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend(SOURCES_LIST)];
3806 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3807 @synchronized (self) {
3810 [self releasePackages];
3813 [sourceList_ removeAllObjects];
3834 new (&pool_) CYPool();
3836 NSRecycleZone(zone_);
3837 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3839 int chk(creat("/tmp/cydia.chk", 0644));
3843 if (invocation != nil)
3844 [invocation invoke];
3846 NSString *title(UCLocalize("DATABASE"));
3848 list_ = new pkgSourceList();
3849 _profile(reloadDataWithInvocation$ReadMainList)
3850 if ([self popErrorWithTitle:title forReadList:*list_])
3854 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3855 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3856 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3857 [sourceList_ addObject:object];
3862 OpProgress progress;
3865 delock_ = GetStatusDate();
3866 _profile(reloadDataWithInvocation$pkgCacheFile)
3867 opened = cache_.Open(progress, false);
3870 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3871 while (!_error->empty()) {
3873 bool warning(!_error->PopMessage(error));
3875 lprintf("cache_.Open():[%s]\n", error.c_str());
3877 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3881 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3882 repair = @selector(configure);
3883 //else if (error == "The package lists or status file could not be parsed or opened.")
3884 // repair = @selector(update);
3885 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3886 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3887 // else if (error == "Malformed Status line")
3888 // else if (error == "The list of sources could not be read.")
3890 if (repair != NULL) {
3892 [delegate_ repairWithSelector:repair];
3901 unlink("/tmp/cydia.chk");
3903 now_ = [[NSDate date] timeIntervalSince1970];
3905 policy_ = new pkgDepCache::Policy();
3906 records_ = new pkgRecords(cache_);
3907 resolver_ = new pkgProblemResolver(cache_);
3908 fetcher_ = new pkgAcquire(&status_);
3911 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3912 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3916 _profile(reloadDataWithInvocation$pkgApplyStatus)
3917 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3921 if (cache_->BrokenCount() != 0) {
3922 _profile(pkgApplyStatus$pkgFixBroken)
3923 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3927 if (cache_->BrokenCount() != 0) {
3928 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3932 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3933 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3938 for (Source *object in (id) sourceList_) {
3939 metaIndex *source([object metaIndex]);
3940 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3941 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3942 // XXX: this could be more intelligent
3943 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3944 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3946 sourceMap_[cached->ID] = object;
3951 /*std::vector<Package *> packages;
3952 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3955 _profile(reloadDataWithInvocation$packageWithIterator)
3956 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3957 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self])
3958 //packages.push_back(package);
3959 CFArrayAppendValue(packages_, CFRetain(package));
3963 /*if (packages.empty())
3964 packages_ = [[NSArray alloc] init];
3966 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3969 _profile(reloadDataWithInvocation$radix$8)
3970 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3973 _profile(reloadDataWithInvocation$radix$4)
3974 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3977 _profile(reloadDataWithInvocation$radix$0)
3978 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3981 _profile(reloadDataWithInvocation$insertion)
3982 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3985 /*_profile(reloadDataWithInvocation$CFQSortArray)
3986 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3989 /*_profile(reloadDataWithInvocation$stdsort)
3990 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3993 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3994 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3997 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3998 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
4002 size_t count(CFArrayGetCount(packages_));
4003 MetaFile_->active_ = count;
4004 for (size_t index(0); index != count; ++index)
4005 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
4010 @synchronized (self) {
4012 resolver_ = new pkgProblemResolver(cache_);
4014 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
4015 if (!cache_[iterator].Keep())
4016 cache_->MarkKeep(iterator, false);
4017 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
4018 cache_->SetReInstall(iterator, false);
4021 - (void) configure {
4022 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
4024 system([dpkg UTF8String]);
4029 @synchronized (self) {
4030 // XXX: I don't remember this condition
4035 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4037 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
4039 if ([self popErrorWithTitle:title])
4043 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4045 CydiaLogCleaner cleaner;
4046 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4053 fetcher_->Shutdown();
4055 pkgRecords records(cache_);
4057 lock_ = new FileFd();
4058 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4060 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4062 if ([self popErrorWithTitle:title])
4066 if ([self popErrorWithTitle:title forReadList:list])
4069 manager_ = (_system->CreatePM(cache_));
4070 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4077 bool substrate(RestartSubstrate_);
4078 RestartSubstrate_ = false;
4080 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4082 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4084 if ([self popErrorWithTitle:title forReadList:list])
4086 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4087 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4090 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4092 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4094 [self popErrorWithTitle:title];
4098 bool failed = false;
4099 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4100 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4102 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4105 std::string uri = (*item)->DescURI();
4106 std::string error = (*item)->ErrorText;
4108 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4111 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4112 [delegate_ addProgressEventOnMainThread:event forTask:title];
4115 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4123 RestartSubstrate_ = true;
4125 if (![delock_ isEqual:GetStatusDate()]) {
4126 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title];
4132 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4134 NSString *oextended(@"/var/lib/apt/extended_states");
4135 NSString *nextended(Cache("extended_states"));
4138 if (stat([nextended UTF8String], &info) != -1 && (info.st_mode & S_IFMT) == S_IFREG)
4139 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/cp --remove-destination %@ %@", ShellEscape(nextended), ShellEscape(oextended)] UTF8String]);
4141 unlink([nextended UTF8String]);
4142 symlink([oextended UTF8String], [nextended UTF8String]);
4144 if ([self popErrorWithTitle:title])
4147 if (result == pkgPackageManager::Failed) {
4152 if (result != pkgPackageManager::Completed) {
4157 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4159 if ([self popErrorWithTitle:title forReadList:list])
4161 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4162 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4165 if (![before isEqualToArray:after])
4170 return ![delock_ isEqual:GetStatusDate()];
4174 NSString *title(UCLocalize("UPGRADE"));
4175 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4181 [self updateWithStatus:status_];
4184 - (void) updateWithStatus:(CancelStatus &)status {
4185 NSString *title(UCLocalize("REFRESHING_DATA"));
4188 if ([self popErrorWithTitle:title forReadList:list])
4192 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4193 if ([self popErrorWithTitle:title])
4196 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4198 bool success(ListUpdate(status, list, PulseInterval_));
4199 if (status.WasCancelled())
4202 [self popErrorWithTitle:title forOperation:success];
4204 [[NSDictionary dictionaryWithObjectsAndKeys:
4205 [NSDate date], @"LastUpdate",
4206 nil] writeToFile:@ CacheState_ atomically:YES];
4209 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4212 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4213 delegate_ = delegate;
4216 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4217 progress_ = delegate;
4218 status_.setDelegate(delegate);
4221 - (NSObject<ProgressDelegate> *) progressDelegate {
4225 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4226 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4227 return i == sourceMap_.end() ? nil : i->second;
4230 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4231 for (Source *source in (id) sourceList_)
4232 [source setFetch:fetch forURI:uri];
4235 - (void) resetFetch {
4236 for (Source *source in (id) sourceList_)
4237 [source resetFetch];
4240 - (NSString *) mappedSectionForPointer:(const char *)section {
4241 _H<NSString> *mapped;
4243 _profile(Database$mappedSectionForPointer$Cache)
4244 mapped = §ions_[section];
4247 if (*mapped == NULL) {
4248 size_t length(strlen(section));
4249 char spaced[length + 1];
4251 _profile(Database$mappedSectionForPointer$Replace)
4252 for (size_t index(0); index != length; ++index)
4253 spaced[index] = section[index] == '_' ? ' ' : section[index];
4254 spaced[length] = '\0';
4259 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4260 string = [NSString stringWithUTF8String:spaced];
4263 _profile(Database$mappedSectionForPointer$Map)
4264 string = [SectionMap_ objectForKey:string] ?: string;
4274 static _H<NSMutableSet> Diversions_;
4276 @interface Diversion : NSObject {
4279 _H<NSString> format_;
4284 @implementation Diversion
4286 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4287 if ((self = [super init]) != nil) {
4288 pattern_ = [from UTF8String];
4294 - (NSString *) divert:(NSString *)url {
4295 return !pattern_(url) ? nil : pattern_->*format_;
4298 + (NSURL *) divertURL:(NSURL *)url {
4300 NSString *href([url absoluteString]);
4302 for (Diversion *diversion in (id) Diversions_)
4303 if (NSString *diverted = [diversion divert:href]) {
4305 NSLog(@"div: %@", diverted);
4307 url = [NSURL URLWithString:diverted];
4314 - (NSString *) key {
4318 - (NSUInteger) hash {
4322 - (BOOL) isEqual:(Diversion *)object {
4323 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4328 @interface CydiaObject : NSObject {
4329 _H<CyteWebViewController> indirect_;
4330 _transient id delegate_;
4333 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4339 @interface CydiaWebViewController : CyteWebViewController {
4340 _H<CydiaObject> cydia_;
4343 + (void) addDiversion:(Diversion *)diversion;
4344 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4345 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4346 - (void) setDelegate:(id)delegate;
4350 /* Web Scripting {{{ */
4351 @implementation CydiaObject
4353 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4354 if ((self = [super init]) != nil) {
4355 indirect_ = (CyteWebViewController *) indirect;
4359 - (void) setDelegate:(id)delegate {
4360 delegate_ = delegate;
4363 + (NSArray *) _attributeKeys {
4364 return [NSArray arrayWithObjects:
4367 @"coreFoundationVersionNumber",
4383 - (NSArray *) attributeKeys {
4384 return [[self class] _attributeKeys];
4387 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4388 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4391 - (NSString *) version {
4395 - (NSString *) build {
4399 - (NSString *) coreFoundationVersionNumber {
4400 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4403 - (NSString *) device {
4404 return UniqueIdentifier();
4407 - (NSString *) firmware {
4408 return [[UIDevice currentDevice] systemVersion];
4411 - (NSString *) hostname {
4412 return [[UIDevice currentDevice] name];
4415 - (NSString *) idiom {
4416 return (id) Idiom_ ?: [NSNull null];
4419 - (NSString *) mcc {
4420 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4421 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4425 - (NSString *) mnc {
4426 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4427 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4431 - (NSString *) operator {
4432 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4433 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4437 - (NSString *) bbsnum {
4438 return (id) BBSNum_ ?: [NSNull null];
4441 - (NSString *) ecid {
4442 return (id) ChipID_ ?: [NSNull null];
4445 - (NSString *) serial {
4446 return SerialNumber_;
4449 - (NSString *) role {
4450 return (id) [NSNull null];
4453 - (NSString *) model {
4454 return [NSString stringWithUTF8String:Machine_];
4457 + (NSString *) webScriptNameForSelector:(SEL)selector {
4459 else if (selector == @selector(addBridgedHost:))
4460 return @"addBridgedHost";
4461 else if (selector == @selector(addInsecureHost:))
4462 return @"addInsecureHost";
4463 else if (selector == @selector(addInternalRedirect::))
4464 return @"addInternalRedirect";
4465 else if (selector == @selector(addPipelinedHost:scheme:))
4466 return @"addPipelinedHost";
4467 else if (selector == @selector(addSource:::))
4468 return @"addSource";
4469 else if (selector == @selector(addTrivialSource:))
4470 return @"addTrivialSource";
4471 else if (selector == @selector(close))
4473 else if (selector == @selector(du:))
4475 else if (selector == @selector(stringWithFormat:arguments:))
4477 else if (selector == @selector(getAllSources))
4478 return @"getAllSources";
4479 else if (selector == @selector(getApplicationInfo:value:))
4480 return @"getApplicationInfoValue";
4481 else if (selector == @selector(getDisplayIdentifiers))
4482 return @"getDisplayIdentifiers";
4483 else if (selector == @selector(getLocalizedNameForDisplayIdentifier:))
4484 return @"getLocalizedNameForDisplayIdentifier";
4485 else if (selector == @selector(getKernelNumber:))
4486 return @"getKernelNumber";
4487 else if (selector == @selector(getKernelString:))
4488 return @"getKernelString";
4489 else if (selector == @selector(getInstalledPackages))
4490 return @"getInstalledPackages";
4491 else if (selector == @selector(getIORegistryEntry::))
4492 return @"getIORegistryEntry";
4493 else if (selector == @selector(getLocaleIdentifier))
4494 return @"getLocaleIdentifier";
4495 else if (selector == @selector(getPreferredLanguages))
4496 return @"getPreferredLanguages";
4497 else if (selector == @selector(getPackageById:))
4498 return @"getPackageById";
4499 else if (selector == @selector(getMetadataKeys))
4500 return @"getMetadataKeys";
4501 else if (selector == @selector(getMetadataValue:))
4502 return @"getMetadataValue";
4503 else if (selector == @selector(getSessionValue:))
4504 return @"getSessionValue";
4505 else if (selector == @selector(installPackages:))
4506 return @"installPackages";
4507 else if (selector == @selector(isReachable:))
4508 return @"isReachable";
4509 else if (selector == @selector(localizedStringForKey:value:table:))
4511 else if (selector == @selector(popViewController:))
4512 return @"popViewController";
4513 else if (selector == @selector(refreshSources))
4514 return @"refreshSources";
4515 else if (selector == @selector(registerFrame:))
4516 return @"registerFrame";
4517 else if (selector == @selector(removeButton))
4518 return @"removeButton";
4519 else if (selector == @selector(saveConfig))
4520 return @"saveConfig";
4521 else if (selector == @selector(setMetadataValue::))
4522 return @"setMetadataValue";
4523 else if (selector == @selector(setSessionValue::))
4524 return @"setSessionValue";
4525 else if (selector == @selector(substitutePackageNames:))
4526 return @"substitutePackageNames";
4527 else if (selector == @selector(scrollToBottom:))
4528 return @"scrollToBottom";
4529 else if (selector == @selector(setAllowsNavigationAction:))
4530 return @"setAllowsNavigationAction";
4531 else if (selector == @selector(setBadgeValue:))
4532 return @"setBadgeValue";
4533 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4534 return @"setButtonImage";
4535 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4536 return @"setButtonTitle";
4537 else if (selector == @selector(setHidesBackButton:))
4538 return @"setHidesBackButton";
4539 else if (selector == @selector(setHidesNavigationBar:))
4540 return @"setHidesNavigationBar";
4541 else if (selector == @selector(setNavigationBarStyle:))
4542 return @"setNavigationBarStyle";
4543 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4544 return @"setNavigationBarTintColor";
4545 else if (selector == @selector(setPasteboardString:))
4546 return @"setPasteboardString";
4547 else if (selector == @selector(setPasteboardURL:))
4548 return @"setPasteboardURL";
4549 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4550 return @"setScrollAlwaysBounceVertical";
4551 else if (selector == @selector(setScrollIndicatorStyle:))
4552 return @"setScrollIndicatorStyle";
4553 else if (selector == @selector(setToken:))
4555 else if (selector == @selector(setViewportWidth:))
4556 return @"setViewportWidth";
4557 else if (selector == @selector(statfs:))
4559 else if (selector == @selector(supports:))
4561 else if (selector == @selector(unload))
4567 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4568 return [self webScriptNameForSelector:selector] == nil;
4571 - (BOOL) supports:(NSString *)feature {
4572 return [feature isEqualToString:@"window.open"];
4576 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4579 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4580 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4583 - (void) setScrollIndicatorStyle:(NSString *)style {
4584 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4587 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4588 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4591 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4593 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4594 return (id) [NSNull null];
4595 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4597 return (id) [NSNull null];
4598 return [info objectForKey:key];
4601 - (NSArray *) getDisplayIdentifiers {
4602 NSSet *set([SBSCopyApplicationDisplayIdentifiers() autorelease]);
4603 if (set == nil || ![set isKindOfClass:[NSSet class]])
4604 return [NSArray array];
4605 return [set allObjects];
4608 - (NSString *) getLocalizedNameForDisplayIdentifier:(NSString *)identifier {
4609 return [SBSCopyLocalizedApplicationNameForDisplayIdentifier(identifier) autorelease] ?: (id) [NSNull null];
4612 - (NSNumber *) getKernelNumber:(NSString *)name {
4613 const char *string([name UTF8String]);
4616 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4617 return (id) [NSNull null];
4619 if (size != sizeof(int))
4620 return (id) [NSNull null];
4623 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4624 return (id) [NSNull null];
4626 return [NSNumber numberWithInt:value];
4629 - (NSString *) getKernelString:(NSString *)name {
4630 const char *string([name UTF8String]);
4633 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4634 return (id) [NSNull null];
4636 char value[size + 1];
4637 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4638 return (id) [NSNull null];
4640 // XXX: just in case you request something ludicrous
4643 return [NSString stringWithCString:value];
4646 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4647 NSObject *value(CYIOGetValue([path UTF8String], entry));
4650 if ([value isKindOfClass:[NSData class]])
4651 value = CYHex((NSData *) value);
4656 - (NSArray *) getMetadataKeys {
4657 @synchronized (Values_) {
4658 return [Values_ allKeys];
4661 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4662 WebFrame *frame([iframe contentFrame]);
4663 [indirect_ registerFrame:frame];
4666 - (id) getMetadataValue:(NSString *)key {
4667 @synchronized (Values_) {
4668 return [Values_ objectForKey:key];
4671 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4672 @synchronized (Values_) {
4673 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4674 [Values_ removeObjectForKey:key];
4676 [Values_ setObject:value forKey:key];
4679 - (id) getSessionValue:(NSString *)key {
4680 @synchronized (SessionData_) {
4681 return [SessionData_ objectForKey:key];
4684 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4685 @synchronized (SessionData_) {
4686 if (value == (id) [WebUndefined undefined])
4687 [SessionData_ removeObjectForKey:key];
4689 [SessionData_ setObject:value forKey:key];
4692 - (void) addBridgedHost:(NSString *)host {
4693 @synchronized (HostConfig_) {
4694 [BridgedHosts_ addObject:host];
4697 - (void) addInsecureHost:(NSString *)host {
4698 @synchronized (HostConfig_) {
4699 [InsecureHosts_ addObject:host];
4702 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4703 @synchronized (HostConfig_) {
4704 if (scheme != (id) [WebUndefined undefined])
4705 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4707 [PipelinedHosts_ addObject:host];
4710 - (void) popViewController:(NSNumber *)value {
4711 if (value == (id) [WebUndefined undefined])
4712 value = [NSNumber numberWithBool:YES];
4713 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4716 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4717 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4719 for (NSString *section in sections)
4720 [array addObject:section];
4722 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4725 distribution, @"Distribution",
4727 nil] waitUntilDone:NO];
4730 - (BOOL) addTrivialSource:(NSString *)href {
4731 href = VerifySource(href);
4734 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4738 - (void) refreshSources {
4739 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4742 - (void) saveConfig {
4743 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4746 - (NSArray *) getAllSources {
4747 return [[Database sharedInstance] sources];
4750 - (NSArray *) getInstalledPackages {
4751 Database *database([Database sharedInstance]);
4752 @synchronized (database) {
4753 NSArray *packages([database packages]);
4754 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4755 for (Package *package in packages)
4756 if (![package uninstalled])
4757 [installed addObject:package];
4761 - (Package *) getPackageById:(NSString *)id {
4762 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4766 return (Package *) [NSNull null];
4769 - (NSString *) getLocaleIdentifier {
4770 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4773 - (NSArray *) getPreferredLanguages {
4777 - (NSArray *) statfs:(NSString *)path {
4780 if (path == nil || statfs([path UTF8String], &stat) == -1)
4783 return [NSArray arrayWithObjects:
4784 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4785 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4786 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4790 - (NSNumber *) du:(NSString *)path {
4791 NSNumber *value(nil);
4793 FILE *du(popen([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/du -ks %@", ShellEscape(path)] UTF8String], "r"));
4796 while (fgets(line, sizeof(line), du) != NULL) {
4797 size_t length(strlen(line));
4798 while (length != 0 && line[length - 1] == '\n')
4799 line[--length] = '\0';
4800 if (char *tab = strchr(line, '\t')) {
4802 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4812 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4815 - (NSNumber *) isReachable:(NSString *)name {
4816 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4819 - (void) installPackages:(NSArray *)packages {
4820 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4823 - (NSString *) substitutePackageNames:(NSString *)message {
4824 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4825 for (size_t i(0), e([words count]); i != e; ++i) {
4826 NSString *word([words objectAtIndex:i]);
4827 if (Package *package = [[Database sharedInstance] packageWithName:word])
4828 [words replaceObjectAtIndex:i withObject:[package name]];
4831 return [words componentsJoinedByString:@" "];
4834 - (void) removeButton {
4835 [indirect_ removeButton];
4838 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4839 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4842 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4843 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4846 - (void) setBadgeValue:(id)value {
4847 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4850 - (void) setAllowsNavigationAction:(NSString *)value {
4851 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4854 - (void) setHidesBackButton:(NSString *)value {
4855 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4858 - (void) setHidesNavigationBar:(NSString *)value {
4859 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4862 - (void) setNavigationBarStyle:(NSString *)value {
4863 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4866 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4867 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4868 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4869 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4872 - (void) setPasteboardString:(NSString *)value {
4873 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4876 - (void) setPasteboardURL:(NSString *)value {
4877 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4880 - (void) setToken:(NSString *)token {
4881 // XXX: the website expects this :/
4884 - (void) scrollToBottom:(NSNumber *)animated {
4885 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4888 - (void) setViewportWidth:(float)width {
4889 [indirect_ setViewportWidthOnMainThread:width];
4892 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4893 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4894 unsigned count([arguments count]);
4896 for (unsigned i(0); i != count; ++i)
4897 values[i] = [arguments objectAtIndex:i];
4898 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4901 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4902 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4904 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4906 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4912 @interface NSURL (CydiaSecure)
4915 @implementation NSURL (CydiaSecure)
4917 - (bool) isCydiaSecure {
4918 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4921 @synchronized (HostConfig_) {
4922 if ([InsecureHosts_ containsObject:[self host]])
4931 /* Cydia Browser Controller {{{ */
4932 @implementation CydiaWebViewController
4934 - (NSURL *) navigationURL {
4935 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4938 + (void) _initialize {
4939 [super _initialize];
4941 Diversions_ = [NSMutableSet setWithCapacity:0];
4944 + (void) addDiversion:(Diversion *)diversion {
4945 [Diversions_ addObject:diversion];
4948 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4949 [super webView:view didClearWindowObject:window forFrame:frame];
4950 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4953 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4954 WebDataSource *source([frame dataSource]);
4955 NSURLResponse *response([source response]);
4956 NSURL *url([response URL]);
4957 NSString *scheme([[url scheme] lowercaseString]);
4959 bool bridged(false);
4961 @synchronized (HostConfig_) {
4962 if ([scheme isEqualToString:@"file"])
4964 else if ([scheme isEqualToString:@"https"])
4965 if ([BridgedHosts_ containsObject:[url host]])
4970 [window setValue:cydia forKey:@"cydia"];
4973 - (void) _setupMail:(MFMailComposeViewController *)controller {
4974 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4976 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4977 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4980 - (NSURL *) URLWithURL:(NSURL *)url {
4981 return [Diversion divertURL:url];
4984 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4985 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4988 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4989 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4992 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4993 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4995 NSURL *url([copy URL]);
4996 NSString *href([url absoluteString]);
4997 NSString *host([url host]);
4999 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
5000 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
5001 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
5002 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
5005 [copy setValue:nil forHTTPHeaderField:@"Referer"];
5006 [copy setValue:nil forHTTPHeaderField:@"Origin"];
5008 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
5012 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
5013 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
5014 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
5015 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5017 bool bridged; @synchronized (HostConfig_) {
5018 bridged = [BridgedHosts_ containsObject:host];
5021 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
5022 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
5027 - (void) setDelegate:(id)delegate {
5028 [super setDelegate:delegate];
5029 [cydia_ setDelegate:delegate];
5032 - (NSString *) applicationNameForUserAgent {
5037 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
5038 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
5044 @interface AppCacheController : CydiaWebViewController {
5049 @implementation AppCacheController
5051 - (void) didReceiveMemoryWarning {
5052 // XXX: this doesn't work
5055 - (bool) retainsNetworkActivityIndicator {
5063 @interface NSObject (CydiaScript)
5064 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
5067 @implementation NSObject (CydiaScript)
5069 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5075 @implementation NSArray (CydiaScript)
5077 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5078 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5079 for (size_t i(0), e([self count]); i != e; ++i)
5080 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5086 @implementation NSDictionary (CydiaScript)
5088 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5089 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5091 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5098 /* Confirmation Controller {{{ */
5099 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5100 if (!iterator.end())
5101 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5102 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5104 pkgCache::PkgIterator package(dep.TargetPkg());
5107 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5114 @protocol ConfirmationControllerDelegate
5115 - (void) cancelAndClear:(bool)clear;
5116 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5120 @interface ConfirmationController : CydiaWebViewController {
5121 _transient Database *database_;
5123 _H<UIAlertView> essential_;
5125 _H<NSDictionary> changes_;
5126 _H<NSMutableArray> issues_;
5127 _H<NSDictionary> sizes_;
5132 - (id) initWithDatabase:(Database *)database;
5136 @implementation ConfirmationController
5140 RestartSubstrate_ = true;
5141 [delegate_ confirmWithNavigationController:[self navigationController]];
5144 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5145 NSString *context([alert context]);
5147 if ([context isEqualToString:@"remove"]) {
5148 if (button == [alert cancelButtonIndex])
5150 else if (button == [alert firstOtherButtonIndex]) {
5151 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5154 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5155 } else if ([context isEqualToString:@"unable"]) {
5156 [self dismissModalViewControllerAnimated:YES];
5157 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5159 [super alertView:alert clickedButtonAtIndex:button];
5163 - (void) _doContinue {
5164 [delegate_ cancelAndClear:NO];
5165 [self dismissModalViewControllerAnimated:YES];
5168 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5169 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5173 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5174 [super webView:view didClearWindowObject:window forFrame:frame];
5176 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5177 (id) changes_, @"changes",
5178 (id) issues_, @"issues",
5179 (id) sizes_, @"sizes",
5181 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5184 - (id) initWithDatabase:(Database *)database {
5185 if ((self = [super init]) != nil) {
5186 database_ = database;
5188 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5189 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5190 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5191 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5192 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5196 pkgCacheFile &cache([database_ cache]);
5197 NSArray *packages([database_ packages]);
5198 pkgDepCache::Policy *policy([database_ policy]);
5200 issues_ = [NSMutableArray arrayWithCapacity:4];
5202 for (Package *package in packages) {
5203 pkgCache::PkgIterator iterator([package iterator]);
5204 NSString *name([package id]);
5206 if ([package broken]) {
5207 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5209 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5211 reasons, @"reasons",
5214 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5218 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5219 pkgCache::DepIterator start;
5220 pkgCache::DepIterator end;
5221 dep.GlobOr(start, end); // ++dep
5223 if (!cache->IsImportantDep(end))
5225 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5228 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5230 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5231 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5232 clauses, @"clauses",
5236 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5238 pkgCache::PkgIterator target(start.TargetPkg());
5239 if (target->ProvidesList != 0)
5240 reason = @"missing";
5242 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5244 reason = @"installed";
5245 installed = [NSString stringWithUTF8String:ver.VerStr()];
5246 } else if (!cache[target].CandidateVerIter(cache).end())
5247 reason = @"uninstalled";
5248 else if (target->ProvidesList == 0)
5249 reason = @"uninstallable";
5251 reason = @"virtual";
5254 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5255 [NSString stringWithUTF8String:start.CompType()], @"operator",
5256 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5259 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5260 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5261 version, @"version",
5263 installed, @"installed",
5266 // yes, seriously. (wtf?)
5274 pkgDepCache::StateCache &state(cache[iterator]);
5276 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
5278 if (state.NewInstall())
5279 [installs addObject:name];
5280 // XXX: else if (state.Install())
5281 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5282 [reinstalls addObject:name];
5283 // XXX: move before previous if
5284 else if (state.Upgrade())
5285 [upgrades addObject:name];
5286 else if (state.Downgrade())
5287 [downgrades addObject:name];
5288 else if (!state.Delete())
5289 // XXX: _assert(state.Keep());
5291 else if (special_r(name))
5292 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5293 [NSNull null], @"package",
5294 [NSArray arrayWithObjects:
5295 [NSDictionary dictionaryWithObjectsAndKeys:
5296 @"Conflicts", @"relationship",
5297 [NSArray arrayWithObjects:
5298 [NSDictionary dictionaryWithObjectsAndKeys:
5300 [NSNull null], @"version",
5301 @"installed", @"reason",
5308 if ([package essential])
5310 [removes addObject:name];
5313 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5314 substrate_ |= DepSubstrate(iterator.CurrentVer());
5319 else if (Advanced_) {
5320 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5322 essential_ = [[[UIAlertView alloc]
5323 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5324 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5326 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5328 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5332 [essential_ setContext:@"remove"];
5333 [essential_ setNumberOfRows:2];
5335 essential_ = [[[UIAlertView alloc]
5336 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5337 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5339 cancelButtonTitle:UCLocalize("OKAY")
5340 otherButtonTitles:nil
5343 [essential_ setContext:@"unable"];
5346 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5347 installs, @"installs",
5348 reinstalls, @"reinstalls",
5349 upgrades, @"upgrades",
5350 downgrades, @"downgrades",
5351 removes, @"removes",
5354 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5355 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5356 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5359 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5363 - (UIBarButtonItem *) leftButton {
5364 return [[[UIBarButtonItem alloc]
5365 initWithTitle:UCLocalize("CANCEL")
5366 style:UIBarButtonItemStylePlain
5368 action:@selector(cancelButtonClicked)
5373 - (void) applyRightButton {
5374 if ([issues_ count] == 0 && ![self isLoading])
5375 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5376 initWithTitle:UCLocalize("CONFIRM")
5377 style:UIBarButtonItemStyleDone
5379 action:@selector(confirmButtonClicked)
5382 [[self navigationItem] setRightBarButtonItem:nil];
5386 - (void) cancelButtonClicked {
5387 [delegate_ cancelAndClear:YES];
5388 [self dismissModalViewControllerAnimated:YES];
5392 - (void) confirmButtonClicked {
5393 if (essential_ != nil)
5403 /* Progress Data {{{ */
5404 @interface CydiaProgressData : NSObject {
5405 _transient id delegate_;
5414 _H<NSMutableArray> events_;
5415 _H<NSString> title_;
5417 _H<NSString> status_;
5418 _H<NSString> finish_;
5423 @implementation CydiaProgressData
5425 + (NSArray *) _attributeKeys {
5426 return [NSArray arrayWithObjects:
5438 - (NSArray *) attributeKeys {
5439 return [[self class] _attributeKeys];
5442 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5443 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5447 if ((self = [super init]) != nil) {
5448 events_ = [NSMutableArray arrayWithCapacity:32];
5456 - (void) setDelegate:(id)delegate {
5457 delegate_ = delegate;
5460 - (void) setPercent:(float)value {
5464 - (NSNumber *) percent {
5465 return [NSNumber numberWithFloat:percent_];
5468 - (void) setCurrent:(float)value {
5472 - (NSNumber *) current {
5473 return [NSNumber numberWithFloat:current_];
5476 - (void) setTotal:(float)value {
5480 - (NSNumber *) total {
5481 return [NSNumber numberWithFloat:total_];
5484 - (void) setSpeed:(float)value {
5488 - (NSNumber *) speed {
5489 return [NSNumber numberWithFloat:speed_];
5492 - (NSArray *) events {
5496 - (void) removeAllEvents {
5497 [events_ removeAllObjects];
5500 - (void) addEvent:(CydiaProgressEvent *)event {
5501 [events_ addObject:event];
5504 - (void) setTitle:(NSString *)text {
5508 - (NSString *) title {
5512 - (void) setFinish:(NSString *)text {
5516 - (NSString *) finish {
5517 return (id) finish_ ?: [NSNull null];
5520 - (void) setRunning:(bool)running {
5524 - (NSNumber *) running {
5525 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5530 /* Progress Controller {{{ */
5531 @interface ProgressController : CydiaWebViewController <
5534 _transient Database *database_;
5535 _H<CydiaProgressData, 1> progress_;
5539 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5541 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5543 - (void) setTitle:(NSString *)title;
5544 - (void) setCancellable:(bool)cancellable;
5548 @implementation ProgressController
5551 [database_ setProgressDelegate:nil];
5555 - (UIBarButtonItem *) leftButton {
5556 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5557 initWithTitle:UCLocalize("CANCEL")
5558 style:UIBarButtonItemStylePlain
5560 action:@selector(cancel)
5561 ] autorelease] : nil;
5564 - (void) updateCancel {
5565 [super applyLeftButton];
5568 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5569 if ((self = [super init]) != nil) {
5570 database_ = database;
5571 delegate_ = delegate;
5573 [database_ setProgressDelegate:self];
5575 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5576 [progress_ setDelegate:self];
5578 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5580 [scroller_ setBackgroundColor:[UIColor blackColor]];
5582 [[self navigationItem] setHidesBackButton:YES];
5584 [self updateCancel];
5588 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5589 [super webView:view didClearWindowObject:window forFrame:frame];
5590 [window setValue:progress_ forKey:@"cydiaProgress"];
5593 - (void) updateProgress {
5594 [self dispatchEvent:@"CydiaProgressUpdate"];
5597 - (void) viewWillAppear:(BOOL)animated {
5598 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5599 [super viewWillAppear:animated];
5603 UpdateExternalStatus(0);
5606 [delegate_ saveState];
5610 [delegate_ returnToCydia];
5614 [delegate_ terminateWithSuccess];
5615 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5616 [delegate_ suspendWithAnimation:YES];
5618 [delegate_ suspend];*/
5630 UIProgressHUD *hud([delegate_ addProgressHUD]);
5631 [hud setText:UCLocalize("LOADING")];
5632 [delegate_ performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5638 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5639 SBReboot(SBSSpringBoardServerPort());
5641 reboot2(RB_AUTOBOOT);
5648 - (void) setTitle:(NSString *)title {
5649 [progress_ setTitle:title];
5650 [self updateProgress];
5653 - (UIBarButtonItem *) rightButton {
5654 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5655 initWithTitle:UCLocalize("CLOSE")
5656 style:UIBarButtonItemStylePlain
5658 action:@selector(close)
5662 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5663 UpdateExternalStatus(1);
5665 [progress_ setRunning:true];
5666 [self setTitle:title];
5667 // implicit updateProgress
5669 SHA1SumValue notifyconf; {
5671 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5674 MMap mmap(file, MMap::ReadOnly);
5676 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5677 notifyconf = sha1.Result();
5681 SHA1SumValue springlist; {
5683 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5686 MMap mmap(file, MMap::ReadOnly);
5688 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5689 springlist = sha1.Result();
5693 if (invocation != nil) {
5694 [invocation yieldToSelector:@selector(invoke)];
5695 [self setTitle:@"COMPLETE"];
5700 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5703 MMap mmap(file, MMap::ReadOnly);
5705 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5706 if (!(notifyconf == sha1.Result()))
5713 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5716 MMap mmap(file, MMap::ReadOnly);
5718 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5719 if (!(springlist == sha1.Result()))
5725 if (RestartSubstrate_)
5729 RestartSubstrate_ = false;
5732 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5733 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5734 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5735 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5736 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5739 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5741 [progress_ setRunning:false];
5742 [self updateProgress];
5744 [self applyRightButton];
5747 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5748 [progress_ addEvent:event];
5749 [self updateProgress];
5752 - (bool) isProgressCancelled {
5753 return cancel_ == 2;
5758 [self updateCancel];
5761 - (void) setCancellable:(bool)cancellable {
5762 unsigned cancel(cancel_);
5766 else if (cancel_ == 0)
5769 if (cancel != cancel_)
5770 [self updateCancel];
5773 - (void) setProgressCancellable:(NSNumber *)cancellable {
5774 [self setCancellable:[cancellable boolValue]];
5777 - (void) setProgressPercent:(NSNumber *)percent {
5778 [progress_ setPercent:[percent floatValue]];
5779 [self updateProgress];
5782 - (void) setProgressStatus:(NSDictionary *)status {
5783 if (status == nil) {
5784 [progress_ setCurrent:0];
5785 [progress_ setTotal:0];
5786 [progress_ setSpeed:0];
5788 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5790 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5791 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5792 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5795 [self updateProgress];
5801 /* Package Cell {{{ */
5802 @interface PackageCell : CyteTableViewCell <
5803 CyteTableViewCellDelegate
5807 _H<NSString> description_;
5809 _H<NSString> source_;
5811 _H<UIImage> placard_;
5815 - (PackageCell *) init;
5816 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5818 - (void) drawContentRect:(CGRect)rect;
5822 @implementation PackageCell
5824 - (PackageCell *) init {
5825 CGRect frame(CGRectMake(0, 0, 320, 74));
5826 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5827 UIView *content([self contentView]);
5828 CGRect bounds([content bounds]);
5830 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5831 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5832 [content addSubview:content_];
5834 [content_ setDelegate:self];
5835 [content_ setOpaque:YES];
5839 - (NSString *) accessibilityLabel {
5843 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5844 summarized_ = summary;
5854 [content_ setBackgroundColor:[UIColor whiteColor]];
5858 Source *source = [package source];
5860 icon_ = [package icon];
5862 if (NSString *name = [package name])
5863 name_ = [NSString stringWithString:name];
5865 if (NSString *description = [package shortDescription])
5866 description_ = [NSString stringWithString:description];
5868 commercial_ = [package isCommercial];
5870 NSString *label = nil;
5871 bool trusted = false;
5873 if (source != nil) {
5874 label = [source label];
5875 trusted = [source trusted];
5876 } else if ([[package id] isEqualToString:@"firmware"])
5877 label = UCLocalize("APPLE");
5879 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5881 NSString *from(label);
5883 NSString *section = [package simpleSection];
5884 if (section != nil && ![section isEqualToString:label]) {
5885 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5886 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5889 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5891 if (NSString *purpose = [package primaryPurpose])
5892 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5897 if (NSString *mode = [package mode]) {
5898 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5899 color = RemovingColor_;
5900 placard = @"removing";
5902 color = InstallingColor_;
5903 placard = @"installing";
5906 color = [UIColor whiteColor];
5908 if ([package installed] != nil)
5909 placard = @"installed";
5914 [content_ setBackgroundColor:color];
5917 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5920 [self setNeedsDisplay];
5921 [content_ setNeedsDisplay];
5924 - (void) drawSummaryContentRect:(CGRect)rect {
5925 bool highlighted(highlighted_);
5926 float width([self bounds].size.width);
5930 rect.size = [(UIImage *) icon_ size];
5932 while (rect.size.width > 16 || rect.size.height > 16) {
5933 rect.size.width /= 2;
5934 rect.size.height /= 2;
5937 rect.origin.x = 19 - rect.size.width / 2;
5938 rect.origin.y = 19 - rect.size.height / 2;
5940 [icon_ drawInRect:Retina(rect)];
5943 if (badge_ != nil) {
5945 rect.size = [(UIImage *) badge_ size];
5947 rect.size.width /= 4;
5948 rect.size.height /= 4;
5950 rect.origin.x = 25 - rect.size.width / 2;
5951 rect.origin.y = 25 - rect.size.height / 2;
5953 [badge_ drawInRect:Retina(rect)];
5956 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5960 UISetColor(commercial_ ? Purple_ : Black_);
5961 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5963 if (placard_ != nil)
5964 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5967 - (void) drawNormalContentRect:(CGRect)rect {
5968 bool highlighted(highlighted_);
5969 float width([self bounds].size.width);
5973 rect.size = [(UIImage *) icon_ size];
5975 while (rect.size.width > 32 || rect.size.height > 32) {
5976 rect.size.width /= 2;
5977 rect.size.height /= 2;
5980 rect.origin.x = 25 - rect.size.width / 2;
5981 rect.origin.y = 25 - rect.size.height / 2;
5983 [icon_ drawInRect:Retina(rect)];
5986 if (badge_ != nil) {
5988 rect.size = [(UIImage *) badge_ size];
5990 rect.size.width /= 2;
5991 rect.size.height /= 2;
5993 rect.origin.x = 36 - rect.size.width / 2;
5994 rect.origin.y = 36 - rect.size.height / 2;
5996 [badge_ drawInRect:Retina(rect)];
5999 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6003 UISetColor(commercial_ ? Purple_ : Black_);
6004 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
6005 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
6008 UISetColor(commercial_ ? Purplish_ : Gray_);
6009 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
6011 if (placard_ != nil)
6012 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
6015 - (void) drawContentRect:(CGRect)rect {
6017 [self drawSummaryContentRect:rect];
6019 [self drawNormalContentRect:rect];
6024 /* Section Cell {{{ */
6025 @interface SectionCell : CyteTableViewCell <
6026 CyteTableViewCellDelegate
6028 _H<NSString> basic_;
6029 _H<NSString> section_;
6031 _H<NSString> count_;
6033 _H<UISwitch> switch_;
6037 - (void) setSection:(Section *)section editing:(BOOL)editing;
6041 @implementation SectionCell
6043 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6044 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6045 icon_ = [UIImage imageNamed:@"folder.png"];
6046 // XXX: this initial frame is wrong, but is fixed later
6047 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6048 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6050 UIView *content([self contentView]);
6051 CGRect bounds([content bounds]);
6053 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6054 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6055 [content addSubview:content_];
6056 [content_ setBackgroundColor:[UIColor whiteColor]];
6058 [content_ setDelegate:self];
6062 - (void) onSwitch:(id)sender {
6063 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6064 if (metadata == nil) {
6065 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6066 [Sections_ setObject:metadata forKey:basic_];
6069 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6072 - (void) setSection:(Section *)section editing:(BOOL)editing {
6073 if (editing != editing_) {
6075 [switch_ removeFromSuperview];
6077 [self addSubview:switch_];
6086 if (section == nil) {
6087 name_ = UCLocalize("ALL_PACKAGES");
6090 basic_ = [section name];
6091 section_ = [section localized];
6093 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6094 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6097 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6100 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6101 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6103 [content_ setNeedsDisplay];
6106 - (void) setFrame:(CGRect)frame {
6107 [super setFrame:frame];
6109 CGRect rect([switch_ frame]);
6110 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6113 - (NSString *) accessibilityLabel {
6117 - (void) drawContentRect:(CGRect)rect {
6118 bool highlighted(highlighted_ && !editing_);
6120 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6122 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6125 float width(rect.size.width);
6127 width -= 9 + [switch_ frame].size.width;
6131 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6133 CGSize size = [count_ sizeWithFont:Font14_];
6135 UISetColor(Folder_);
6137 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6143 /* File Table {{{ */
6144 @interface FileTable : CyteViewController <
6145 UITableViewDataSource,
6148 _transient Database *database_;
6149 _H<Package> package_;
6151 _H<NSMutableArray> files_;
6152 _H<UITableView, 2> list_;
6155 - (id) initWithDatabase:(Database *)database;
6156 - (void) setPackage:(Package *)package;
6160 @implementation FileTable
6162 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6163 return files_ == nil ? 0 : [files_ count];
6166 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6170 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6171 static NSString *reuseIdentifier = @"Cell";
6173 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6175 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6176 [cell setFont:[UIFont systemFontOfSize:16]];
6178 [cell setText:[files_ objectAtIndex:indexPath.row]];
6179 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6184 - (NSURL *) navigationURL {
6185 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6189 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6190 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6191 [list_ setRowHeight:24.0f];
6192 [(UITableView *) list_ setDataSource:self];
6193 [list_ setDelegate:self];
6194 [self setView:list_];
6197 - (void) viewDidLoad {
6198 [super viewDidLoad];
6200 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6203 - (void) releaseSubviews {
6209 [super releaseSubviews];
6212 - (id) initWithDatabase:(Database *)database {
6213 if ((self = [super init]) != nil) {
6214 database_ = database;
6218 - (void) setPackage:(Package *)package {
6222 files_ = [NSMutableArray arrayWithCapacity:32];
6224 if (package != nil) {
6226 name_ = [package id];
6228 if (NSArray *files = [package files])
6229 [files_ addObjectsFromArray:files];
6231 if ([files_ count] != 0) {
6232 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6233 [files_ removeObjectAtIndex:0];
6234 [files_ sortUsingSelector:@selector(compareByPath:)];
6236 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6237 [stack addObject:@"/"];
6239 for (int i(0), e([files_ count]); i != e; ++i) {
6240 NSString *file = [files_ objectAtIndex:i];
6241 while (![file hasPrefix:[stack lastObject]])
6242 [stack removeLastObject];
6243 NSString *directory = [stack lastObject];
6244 [stack addObject:[file stringByAppendingString:@"/"]];
6245 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6246 ([stack count] - 2) * 3, "",
6247 [file substringFromIndex:[directory length]]
6256 - (void) reloadData {
6259 [self setPackage:[database_ packageWithName:name_]];
6264 /* Package Controller {{{ */
6265 @interface CYPackageController : CydiaWebViewController <
6266 UIActionSheetDelegate
6268 _transient Database *database_;
6269 _H<Package> package_;
6272 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6273 _H<UIActionSheet> sheet_;
6274 _H<UIBarButtonItem> button_;
6275 _H<NSArray> versions_;
6278 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6282 @implementation CYPackageController
6284 - (NSURL *) navigationURL {
6285 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6288 - (void) _clickButtonWithPackage:(Package *)package {
6289 [delegate_ installPackage:package];
6292 - (void) _clickButtonWithName:(NSString *)name {
6293 if ([name isEqualToString:@"CLEAR"])
6294 return [delegate_ clearPackage:package_];
6295 else if ([name isEqualToString:@"REMOVE"])
6296 return [delegate_ removePackage:package_];
6297 else if ([name isEqualToString:@"DOWNGRADE"]) {
6298 sheet_ = [[[UIActionSheet alloc]
6301 cancelButtonTitle:nil
6302 destructiveButtonTitle:nil
6303 otherButtonTitles:nil
6306 for (Package *version in (id) versions_)
6307 [sheet_ addButtonWithTitle:[version latest]];
6308 [sheet_ setContext:@"version"];
6310 [delegate_ showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6314 else if ([name isEqualToString:@"INSTALL"]);
6315 else if ([name isEqualToString:@"REINSTALL"]);
6316 else if ([name isEqualToString:@"UPGRADE"]);
6317 else _assert(false);
6319 [delegate_ installPackage:package_];
6322 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6323 NSString *context([sheet context]);
6324 if (sheet_ == sheet)
6327 if ([context isEqualToString:@"modify"]) {
6328 if (button != [sheet cancelButtonIndex]) {
6330 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6332 [self _clickButtonWithName:buttons_[button].first];
6335 [sheet dismissWithClickedButtonIndex:button animated:YES];
6336 } else if ([context isEqualToString:@"version"]) {
6337 if (button != [sheet cancelButtonIndex]) {
6338 Package *version([versions_ objectAtIndex:button]);
6340 [self performSelector:@selector(_clickButtonWithPackage:) withObject:version afterDelay:0];
6342 [self _clickButtonWithPackage:version];
6345 [sheet dismissWithClickedButtonIndex:button animated:YES];
6349 - (bool) _allowJavaScriptPanel {
6354 - (void) _customButtonClicked {
6355 size_t count(buttons_.size());
6360 [self _clickButtonWithName:buttons_[0].first];
6362 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6363 for (const auto &button : buttons_)
6364 [buttons addObject:button.second];
6366 sheet_ = [[[UIActionSheet alloc]
6369 cancelButtonTitle:nil
6370 destructiveButtonTitle:nil
6371 otherButtonTitles:nil
6374 for (NSString *button in buttons)
6375 [sheet_ addButtonWithTitle:button];
6376 [sheet_ setContext:@"modify"];
6378 [delegate_ showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6382 - (void) reloadButtonClicked {
6383 if (commercial_ && function_ == nil && [package_ uninstalled])
6385 [self customButtonClicked];
6388 - (void) applyLoadingTitle {
6389 // Don't show "Loading" as the title. Ever.
6392 - (UIBarButtonItem *) rightButton {
6397 - (void) setPageColor:(UIColor *)color {
6398 return [super setPageColor:nil];
6401 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6402 if ((self = [super init]) != nil) {
6403 database_ = database;
6404 name_ = name == nil ? @"" : [NSString stringWithString:name];
6405 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6409 - (void) reloadData {
6412 [sheet_ dismissWithClickedButtonIndex:[sheet_ cancelButtonIndex] animated:YES];
6415 package_ = [database_ packageWithName:name_];
6416 versions_ = [package_ downgrades];
6420 if (package_ != nil) {
6421 [(Package *) package_ parse];
6423 commercial_ = [package_ isCommercial];
6425 if ([package_ mode] != nil)
6426 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6427 if ([package_ source] == nil);
6428 else if ([package_ upgradableAndEssential:NO])
6429 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6430 else if ([package_ uninstalled])
6431 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6433 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6434 if (![package_ uninstalled])
6435 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6436 if ([versions_ count] != 0)
6437 buttons_.push_back(std::make_pair(@"DOWNGRADE", UCLocalize("DOWNGRADE")));
6441 switch (buttons_.size()) {
6442 case 0: title = nil; break;
6443 case 1: title = buttons_[0].second; break;
6444 default: title = UCLocalize("MODIFY"); break;
6447 button_ = [[[UIBarButtonItem alloc]
6449 style:UIBarButtonItemStylePlain
6451 action:@selector(customButtonClicked)
6455 - (bool) isLoading {
6456 return commercial_ ? [super isLoading] : false;
6462 /* Package List Controller {{{ */
6463 @interface PackageListController : CyteViewController <
6464 UITableViewDataSource,
6467 _transient Database *database_;
6469 _H<NSArray> packages_;
6470 _H<NSArray> sections_;
6471 _H<UITableView, 2> list_;
6473 _H<NSArray> thumbs_;
6474 std::vector<NSInteger> offset_;
6476 _H<NSString> title_;
6477 unsigned reloading_;
6480 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6481 - (void) setDelegate:(id)delegate;
6482 - (void) resetCursor;
6485 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6489 @implementation PackageListController
6491 - (NSURL *) referrerURL {
6492 return [self navigationURL];
6495 - (bool) isSummarized {
6499 - (bool) showsSections {
6503 - (void) deselectWithAnimation:(BOOL)animated {
6504 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6507 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6508 CGRect base = [[self view] bounds];
6509 base.size.height -= bounds.size.height;
6510 base.origin = [list_ frame].origin;
6512 [UIView beginAnimations:nil context:NULL];
6513 [UIView setAnimationBeginsFromCurrentState:YES];
6514 [UIView setAnimationCurve:curve];
6515 [UIView setAnimationDuration:duration];
6516 [list_ setFrame:base];
6517 [UIView commitAnimations];
6520 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6521 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6524 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6525 [self resizeForKeyboardBounds:bounds duration:0];
6528 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6529 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6530 *curve = UIViewAnimationCurveEaseInOut;
6532 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6534 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6537 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6540 - (void) keyboardWillShow:(NSNotification *)notification {
6543 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6544 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6546 NSTimeInterval duration;
6547 UIViewAnimationCurve curve;
6548 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6550 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6551 UIViewController *base = self;
6552 while ([base parentOrPresentingViewController] != nil)
6553 base = [base parentOrPresentingViewController];
6554 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6555 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6557 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6558 intersection.size.height += CYStatusBarHeight();
6560 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6563 - (void) keyboardWillHide:(NSNotification *)notification {
6564 NSTimeInterval duration;
6565 UIViewAnimationCurve curve;
6566 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6568 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6571 - (void) viewWillAppear:(BOOL)animated {
6572 [super viewWillAppear:animated];
6574 [self resizeForKeyboardBounds:CGRectZero];
6575 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6576 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6579 - (void) viewWillDisappear:(BOOL)animated {
6580 [super viewWillDisappear:animated];
6582 [self resizeForKeyboardBounds:CGRectZero];
6583 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6584 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6587 - (void) viewDidAppear:(BOOL)animated {
6588 [super viewDidAppear:animated];
6589 [self deselectWithAnimation:animated];
6592 - (void) didSelectPackage:(Package *)package {
6593 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6594 [view setDelegate:delegate_];
6595 [[self navigationController] pushViewController:view animated:YES];
6598 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6599 NSInteger count([sections_ count]);
6600 return count == 0 ? 1 : count;
6603 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6604 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6606 return [[sections_ objectAtIndex:section] name];
6609 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6610 if ([sections_ count] == 0)
6612 return [[sections_ objectAtIndex:section] count];
6615 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6616 @synchronized (database_) {
6617 if ([database_ era] != era_)
6620 Section *section([sections_ objectAtIndex:[path section]]);
6621 NSInteger row([path row]);
6622 Package *package([packages_ objectAtIndex:([section row] + row)]);
6623 return [[package retain] autorelease];
6626 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6627 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6629 cell = [[[PackageCell alloc] init] autorelease];
6631 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6632 [cell setPackage:package asSummary:[self isSummarized]];
6636 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6637 Package *package([self packageAtIndexPath:path]);
6638 package = [database_ packageWithName:[package id]];
6639 [self didSelectPackage:package];
6642 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6646 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6647 return offset_[index];
6650 - (void) updateHeight {
6651 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6654 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6655 if ((self = [super init]) != nil) {
6656 database_ = database;
6657 title_ = [title copy];
6658 [[self navigationItem] setTitle:title_];
6663 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6664 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6665 [self setView:view];
6667 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6668 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6669 [view addSubview:list_];
6671 // XXX: is 20 the most optimal number here?
6672 [list_ setSectionIndexMinimumDisplayRowCount:20];
6674 [(UITableView *) list_ setDataSource:self];
6675 [list_ setDelegate:self];
6677 [self updateHeight];
6680 - (void) releaseSubviews {
6689 [super releaseSubviews];
6692 - (void) setDelegate:(id)delegate {
6693 delegate_ = delegate;
6696 - (bool) shouldYield {
6700 - (bool) shouldBlock {
6704 - (NSMutableArray *) _reloadPackages {
6705 @synchronized (database_) {
6706 era_ = [database_ era];
6707 NSArray *packages([database_ packages]);
6709 return [NSMutableArray arrayWithArray:packages];
6712 - (void) _reloadData {
6713 if (reloading_ != 0) {
6718 NSMutableArray *packages;
6721 if ([self shouldYield]) {
6725 if (![self shouldBlock])
6728 hud = [delegate_ addProgressHUD];
6729 [hud setText:UCLocalize("LOADING")];
6733 packages = [self yieldToSelector:@selector(_reloadPackages)];
6736 [delegate_ removeProgressHUD:hud];
6737 } while (reloading_ == 2);
6739 packages = [self _reloadPackages];
6742 @synchronized (database_) {
6743 if (era_ != [database_ era])
6750 packages_ = packages;
6752 if ([self showsSections])
6753 sections_ = [self sectionsForPackages:packages];
6755 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6756 [section setCount:[packages_ count]];
6757 sections_ = [NSArray arrayWithObject:section];
6760 [self updateHeight];
6762 _profile(PackageTable$reloadData$List)
6763 [(UITableView *) list_ setDataSource:self];
6771 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6772 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6773 size_t end([packages count]);
6775 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6776 Section *section(prefix);
6778 thumbs_ = CollationThumbs_;
6779 offset_ = CollationOffset_;
6782 size_t offsets([CollationStarts_ count]);
6784 NSString *start([CollationStarts_ objectAtIndex:offset]);
6785 size_t length([start length]);
6787 for (size_t index(0); index != end; ++index) {
6789 Package *package([packages objectAtIndex:index]);
6790 NSString *name(PackageName(package, @selector(cyname)));
6792 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6793 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6794 NSString *title([CollationTitles_ objectAtIndex:offset]);
6795 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6796 [sections addObject:section];
6798 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6801 length = [start length];
6805 [section addToCount];
6808 for (; offset != offsets; ++offset) {
6809 NSString *title([CollationTitles_ objectAtIndex:offset]);
6810 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6811 [sections addObject:section];
6814 if ([prefix count] != 0) {
6815 Section *suffix([sections lastObject]);
6816 [prefix setName:[suffix name]];
6817 [suffix setName:nil];
6818 [sections insertObject:prefix atIndex:(offsets - 1)];
6824 - (void) reloadData {
6827 if ([self shouldYield])
6828 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6833 - (void) resetCursor {
6834 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6837 - (void) clearData {
6838 [self updateHeight];
6840 [list_ setDataSource:nil];
6848 /* Filtered Package List Controller {{{ */
6849 typedef Function<bool, Package *> PackageFilter;
6850 typedef Function<void, NSMutableArray *> PackageSorter;
6851 @interface FilteredPackageListController : PackageListController {
6852 PackageFilter filter_;
6853 PackageSorter sorter_;
6856 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6858 - (void) setFilter:(PackageFilter)filter;
6859 - (void) setSorter:(PackageSorter)sorter;
6863 @implementation FilteredPackageListController
6865 - (void) setFilter:(PackageFilter)filter {
6866 @synchronized (self) {
6870 - (void) setSorter:(PackageSorter)sorter {
6871 @synchronized (self) {
6875 - (NSMutableArray *) _reloadPackages {
6876 @synchronized (database_) {
6877 era_ = [database_ era];
6879 NSArray *packages([database_ packages]);
6880 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6882 PackageFilter filter;
6883 PackageSorter sorter;
6885 @synchronized (self) {
6890 _profile(PackageTable$reloadData$Filter)
6891 for (Package *package in packages)
6892 if (filter(package))
6893 [filtered addObject:package];
6901 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6902 if ((self = [super initWithDatabase:database title:title]) != nil) {
6903 [self setFilter:filter];
6910 /* Home Controller {{{ */
6911 @interface HomeController : CydiaWebViewController {
6912 CFRunLoopRef runloop_;
6913 SCNetworkReachabilityRef reachability_;
6918 @implementation HomeController
6920 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6921 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6925 if ((self = [super init]) != nil) {
6926 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6929 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6930 if (reachability_ != NULL) {
6931 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6932 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6934 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6935 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6942 if (reachability_ != NULL && runloop_ != NULL)
6943 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6947 - (NSURL *) navigationURL {
6948 return [NSURL URLWithString:@"cydia://home"];
6951 - (void) aboutButtonClicked {
6952 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6954 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6955 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6956 [alert setCancelButtonIndex:0];
6959 @"Copyright \u00a9 2008-2015\n"
6962 "Jay Freeman (saurik)\n"
6963 "saurik@saurik.com\n"
6964 "http://www.saurik.com/"
6970 - (UIBarButtonItem *) leftButton {
6971 return [[[UIBarButtonItem alloc]
6972 initWithTitle:UCLocalize("ABOUT")
6973 style:UIBarButtonItemStylePlain
6975 action:@selector(aboutButtonClicked)
6982 /* Cydia Navigation Controller Interface {{{ */
6983 @interface UINavigationController (Cydia)
6985 - (NSArray *) navigationURLCollection;
6986 - (void) unloadData;
6991 /* Cydia Tab Bar Controller {{{ */
6992 @interface CydiaTabBarController : CyteTabBarController <
6993 UITabBarControllerDelegate,
6996 _transient Database *database_;
6998 _H<UIActivityIndicatorView> indicator_;
7001 // XXX: ok, "updatedelegate_"?...
7002 _transient NSObject<CydiaDelegate> *updatedelegate_;
7005 - (NSArray *) navigationURLCollection;
7006 - (void) beginUpdate;
7011 @implementation CydiaTabBarController
7013 - (NSArray *) navigationURLCollection {
7014 NSMutableArray *items([NSMutableArray array]);
7016 // XXX: Should this deal with transient view controllers?
7017 for (id navigation in [self viewControllers]) {
7018 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
7020 [items addObject:stack];
7026 - (id) initWithDatabase:(Database *)database {
7027 if ((self = [super init]) != nil) {
7028 database_ = database;
7029 [self setDelegate:self];
7031 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
7032 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
7034 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7038 - (void) beginUpdate {
7042 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7043 UITabBarItem *item([controller tabBarItem]);
7045 [item setBadgeValue:@""];
7046 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
7048 [indicator_ startAnimating];
7049 [badge addSubview:indicator_];
7051 [updatedelegate_ retainNetworkActivityIndicator];
7055 detachNewThreadSelector:@selector(performUpdate)
7061 - (void) performUpdate {
7062 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7064 SourceStatus status(self, database_);
7065 [database_ updateWithStatus:status];
7068 performSelectorOnMainThread:@selector(completeUpdate)
7076 - (void) stopUpdateWithSelector:(SEL)selector {
7078 [updatedelegate_ releaseNetworkActivityIndicator];
7080 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7081 [[controller tabBarItem] setBadgeValue:nil];
7083 [indicator_ removeFromSuperview];
7084 [indicator_ stopAnimating];
7086 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7089 - (void) completeUpdate {
7092 [self stopUpdateWithSelector:@selector(reloadData)];
7095 - (void) cancelUpdate {
7096 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7099 - (void) cancelPressed {
7100 [self cancelUpdate];
7107 - (bool) isSourceCancelled {
7111 - (void) startSourceFetch:(NSString *)uri {
7114 - (void) stopSourceFetch:(NSString *)uri {
7117 - (void) setUpdateDelegate:(id)delegate {
7118 updatedelegate_ = delegate;
7124 /* Cydia Navigation Controller Implementation {{{ */
7125 @implementation UINavigationController (Cydia)
7127 - (NSArray *) navigationURLCollection {
7128 NSMutableArray *stack([NSMutableArray array]);
7130 for (CyteViewController *controller in [self viewControllers]) {
7131 NSString *url = [[controller navigationURL] absoluteString];
7133 [stack addObject:url];
7139 - (void) reloadData {
7142 UIViewController *visible([self visibleViewController]);
7144 [visible reloadData];
7146 // on the iPad, this view controller is ALSO visible. :(
7148 if (UIViewController *modal = [self modalViewController])
7149 if ([modal modalPresentationStyle] == UIModalPresentationFormSheet)
7150 if (UIViewController *top = [self topViewController])
7155 - (void) unloadData {
7156 for (CyteViewController *page in [self viewControllers])
7165 /* Cydia:// Protocol {{{ */
7166 @interface CydiaURLProtocol : NSURLProtocol {
7171 @implementation CydiaURLProtocol
7173 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7174 NSURL *url([request URL]);
7178 NSString *scheme([[url scheme] lowercaseString]);
7179 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7181 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7187 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7191 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7192 id<NSURLProtocolClient> client([self client]);
7194 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7196 NSData *data(UIImagePNGRepresentation(icon));
7198 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7199 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7200 [client URLProtocol:self didLoadData:data];
7201 [client URLProtocolDidFinishLoading:self];
7205 - (void) startLoading {
7206 id<NSURLProtocolClient> client([self client]);
7207 NSURLRequest *request([self request]);
7209 NSURL *url([request URL]);
7210 NSString *href([url absoluteString]);
7211 NSString *scheme([[url scheme] lowercaseString]);
7215 if ([scheme isEqualToString:@"cydia"])
7216 path = [href substringFromIndex:8];
7217 else if ([scheme isEqualToString:@"about"])
7218 path = [href substringFromIndex:12];
7219 else _assert(false);
7221 NSRange slash([path rangeOfString:@"/"]);
7224 if (slash.location == NSNotFound) {
7228 command = [path substringToIndex:slash.location];
7229 path = [path substringFromIndex:(slash.location + 1)];
7232 Database *database([Database sharedInstance]);
7235 else if ([command isEqualToString:@"application-icon"]) {
7238 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7242 if (icon == nil && $SBSCopyIconImagePNGDataForDisplayIdentifier != NULL) {
7243 NSData *data([$SBSCopyIconImagePNGDataForDisplayIdentifier(path) autorelease]);
7244 icon = [UIImage imageWithData:data];
7248 if (NSString *file = SBSCopyIconImagePathForDisplayIdentifier(path))
7249 icon = [UIImage imageAtPath:file];
7252 icon = [UIImage imageNamed:@"unknown.png"];
7254 [self _returnPNGWithImage:icon forRequest:request];
7255 } else if ([command isEqualToString:@"package-icon"]) {
7258 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7259 Package *package([database packageWithName:path]);
7263 UIImage *icon([package icon]);
7264 [self _returnPNGWithImage:icon forRequest:request];
7265 } else if ([command isEqualToString:@"uikit-image"]) {
7268 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7269 UIImage *icon(_UIImageWithName(path));
7270 [self _returnPNGWithImage:icon forRequest:request];
7271 } else if ([command isEqualToString:@"section-icon"]) {
7274 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7275 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7277 icon = [UIImage imageNamed:@"unknown.png"];
7278 [self _returnPNGWithImage:icon forRequest:request];
7280 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7284 - (void) stopLoading {
7290 /* Section Controller {{{ */
7291 @interface SectionController : FilteredPackageListController {
7293 _H<NSString> section_;
7296 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7300 @implementation SectionController
7302 - (NSURL *) referrerURL {
7303 NSString *name(section_);
7304 name = name ?: @"*";
7305 NSString *key(key_);
7307 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7310 - (NSURL *) navigationURL {
7311 NSString *name(section_);
7312 name = name ?: @"*";
7313 NSString *key(key_);
7315 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7318 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7321 title = UCLocalize("ALL_PACKAGES");
7322 else if (![section isEqual:@""])
7323 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7325 title = UCLocalize("NO_SECTION");
7327 if ((self = [super initWithDatabase:database title:title]) != nil) {
7328 key_ = [source key];
7333 - (void) reloadData {
7334 Source *source([database_ sourceWithKey:key_]);
7335 _H<NSString> name(section_);
7337 [self setFilter:[=](Package *package) {
7338 NSString *section([package section]);
7342 section == nil && [name length] == 0 ||
7343 [name isEqualToString:section]
7346 [package source] == source
7347 ) && [package visible];
7355 /* Sections Controller {{{ */
7356 @interface SectionsController : CyteViewController <
7357 UITableViewDataSource,
7360 _transient Database *database_;
7362 _H<NSMutableArray> sections_;
7363 _H<NSMutableArray> filtered_;
7364 _H<UITableView, 2> list_;
7367 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7368 - (void) editButtonClicked;
7372 @implementation SectionsController
7374 - (NSURL *) navigationURL {
7375 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7378 - (Source *) source {
7381 return [database_ sourceWithKey:key_];
7384 - (void) updateNavigationItem {
7385 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7386 if ([sections_ count] == 0) {
7387 [[self navigationItem] setRightBarButtonItem:nil];
7389 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7390 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7392 action:@selector(editButtonClicked)
7393 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7397 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7398 [super setEditing:editing animated:animated];
7403 [delegate_ updateData];
7405 [self updateNavigationItem];
7408 - (void) viewDidAppear:(BOOL)animated {
7409 [super viewDidAppear:animated];
7410 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7413 - (void) viewWillDisappear:(BOOL)animated {
7414 [super viewWillDisappear:animated];
7415 [self setEditing:NO];
7418 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7419 Section *section = nil;
7420 int index = [indexPath row];
7421 if (![self isEditing]) {
7424 section = [filtered_ objectAtIndex:index];
7426 section = [sections_ objectAtIndex:index];
7431 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7432 if ([self isEditing])
7433 return [sections_ count];
7435 return [filtered_ count] + 1;
7438 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7442 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7443 static NSString *reuseIdentifier = @"SectionCell";
7445 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7447 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7449 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7454 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7455 if ([self isEditing])
7458 Section *section = [self sectionAtIndexPath:indexPath];
7460 SectionController *controller = [[[SectionController alloc]
7461 initWithDatabase:database_
7462 source:[self source]
7463 section:[section name]
7465 [controller setDelegate:delegate_];
7467 [[self navigationController] pushViewController:controller animated:YES];
7471 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7472 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7473 [list_ setRowHeight:46];
7474 [(UITableView *) list_ setDataSource:self];
7475 [list_ setDelegate:self];
7476 [self setView:list_];
7479 - (void) viewDidLoad {
7480 [super viewDidLoad];
7482 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7485 - (void) releaseSubviews {
7491 [super releaseSubviews];
7494 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7495 if ((self = [super init]) != nil) {
7496 database_ = database;
7497 key_ = [source key];
7501 - (void) reloadData {
7504 NSArray *packages = [database_ packages];
7506 sections_ = [NSMutableArray arrayWithCapacity:16];
7507 filtered_ = [NSMutableArray arrayWithCapacity:16];
7509 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7511 Source *source([self source]);
7514 for (Package *package in packages) {
7515 if (source != nil && [package source] != source)
7518 NSString *name([package section]);
7519 NSString *key(name == nil ? @"" : name);
7523 _profile(SectionsView$reloadData$Section)
7524 section = [sections objectForKey:key];
7525 if (section == nil) {
7526 _profile(SectionsView$reloadData$Section$Allocate)
7527 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7528 [sections setObject:section forKey:key];
7533 [section addToCount];
7535 _profile(SectionsView$reloadData$Filter)
7536 if (![package visible])
7544 [sections_ addObjectsFromArray:[sections allValues]];
7546 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7548 for (Section *section in (id) sections_) {
7549 size_t count([section row]);
7553 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7554 [section setCount:count];
7555 [filtered_ addObject:section];
7558 [self updateNavigationItem];
7563 - (void) editButtonClicked {
7564 [self setEditing:![self isEditing] animated:YES];
7570 /* Changes Controller {{{ */
7571 @interface ChangesController : FilteredPackageListController {
7575 - (id) initWithDatabase:(Database *)database;
7579 @implementation ChangesController
7581 - (NSURL *) referrerURL {
7582 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7585 - (NSURL *) navigationURL {
7586 return [NSURL URLWithString:@"cydia://changes"];
7589 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7590 @synchronized (database_) {
7591 if ([database_ era] != era_)
7594 NSUInteger sectionIndex([path section]);
7595 if (sectionIndex >= [sections_ count])
7597 Section *section([sections_ objectAtIndex:sectionIndex]);
7598 NSInteger row([path row]);
7599 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7602 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7603 NSString *context([alert context]);
7605 if ([context isEqualToString:@"norefresh"])
7606 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7609 - (void) setLeftBarButtonItem {
7610 if ([delegate_ updating])
7611 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7612 initWithTitle:UCLocalize("CANCEL")
7613 style:UIBarButtonItemStyleDone
7615 action:@selector(cancelButtonClicked)
7616 ] autorelease] animated:YES];
7618 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7619 initWithTitle:UCLocalize("REFRESH")
7620 style:UIBarButtonItemStylePlain
7622 action:@selector(refreshButtonClicked)
7623 ] autorelease] animated:YES];
7626 - (void) refreshButtonClicked {
7627 if ([delegate_ requestUpdate])
7628 [self setLeftBarButtonItem];
7631 - (void) cancelButtonClicked {
7632 [delegate_ cancelUpdate];
7635 - (void) upgradeButtonClicked {
7636 [delegate_ distUpgrade];
7637 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7640 - (bool) shouldYield {
7644 - (bool) shouldBlock {
7648 - (void) useFilter {
7649 @synchronized (self) {
7650 [self setFilter:[](Package *package) {
7651 return [package upgradableAndEssential:YES] || [package visible];
7654 [self setSorter:[](NSMutableArray *packages) {
7655 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7659 - (id) initWithDatabase:(Database *)database {
7660 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7665 - (void) viewDidLoad {
7666 [super viewDidLoad];
7667 [self setLeftBarButtonItem];
7670 - (void) viewWillAppear:(BOOL)animated {
7671 [super viewWillAppear:animated];
7672 [self setLeftBarButtonItem];
7675 - (void) reloadData {
7676 [self setLeftBarButtonItem];
7680 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7681 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7683 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7684 Section *ignored = nil;
7685 Section *section = nil;
7689 bool unseens = false;
7691 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7693 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7694 Package *package = [packages objectAtIndex:offset];
7696 BOOL uae = [package upgradableAndEssential:YES];
7700 time_t seen([package seen]);
7702 if (section == nil || last != seen) {
7706 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7709 _profile(ChangesController$reloadData$Allocate)
7710 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7711 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7712 [sections addObject:section];
7716 [section addToCount];
7717 } else if ([package ignored]) {
7718 if (ignored == nil) {
7719 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7721 [ignored addToCount];
7724 [upgradable addToCount];
7729 CFRelease(formatter);
7732 Section *last = [sections lastObject];
7733 size_t count = [last count];
7734 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7735 [sections removeLastObject];
7738 if ([ignored count] != 0)
7739 [sections insertObject:ignored atIndex:0];
7741 [sections insertObject:upgradable atIndex:0];
7745 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7746 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7747 style:UIBarButtonItemStylePlain
7749 action:@selector(upgradeButtonClicked)
7750 ] autorelease]) animated:YES];
7757 /* Search Controller {{{ */
7758 @interface SearchController : FilteredPackageListController <
7761 _H<UISearchBar, 1> search_;
7766 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7767 - (void) reloadData;
7771 @implementation SearchController
7773 - (NSURL *) referrerURL {
7774 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7777 - (NSURL *) navigationURL {
7778 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7779 return [NSURL URLWithString:@"cydia://search"];
7781 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7784 - (NSArray *) termsForQuery:(NSString *)query {
7785 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7786 for (NSString *component in [query componentsSeparatedByString:@" "])
7787 if ([component length] != 0)
7788 [terms addObject:component];
7793 - (void) useSearch {
7794 _H<NSArray> query([self termsForQuery:[search_ text]]);
7797 @synchronized (self) {
7798 [self setFilter:[=](Package *package) {
7799 if (![package unfiltered])
7801 if (![package matches:query])
7806 [self setSorter:[](NSMutableArray *packages) {
7807 [packages radixSortUsingSelector:@selector(rank)];
7815 - (void) usePrefix:(NSString *)prefix {
7816 _H<NSString> query(prefix);
7819 @synchronized (self) {
7820 [self setFilter:[=](Package *package) {
7821 if ([query length] == 0)
7823 if (![package unfiltered])
7825 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7830 [self setSorter:nullptr];
7836 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7838 [self usePrefix:[search_ text]];
7841 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7842 [search_ resignFirstResponder];
7846 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7847 [search_ setText:@""];
7848 [self searchBarButtonClicked:searchBar];
7851 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7852 [self searchBarButtonClicked:searchBar];
7855 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7856 [self usePrefix:text];
7859 - (bool) shouldYield {
7863 - (bool) shouldBlock {
7867 - (bool) isSummarized {
7871 - (bool) showsSections {
7875 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7876 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7877 search_ = [[[UISearchBar alloc] init] autorelease];
7878 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7879 [search_ setDelegate:self];
7881 UITextField *textField;
7882 if ([search_ respondsToSelector:@selector(searchField)])
7883 textField = [search_ searchField];
7885 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7887 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7888 [textField setEnablesReturnKeyAutomatically:NO];
7889 [[self navigationItem] setTitleView:textField];
7892 [search_ setText:query];
7897 - (void) viewDidAppear:(BOOL)animated {
7898 [super viewDidAppear:animated];
7900 if (!searchloaded_) {
7901 searchloaded_ = YES;
7902 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7903 [search_ layoutSubviews];
7906 if ([self isSummarized])
7907 [search_ becomeFirstResponder];
7910 - (void) reloadData {
7915 - (void) didSelectPackage:(Package *)package {
7916 [search_ resignFirstResponder];
7917 [super didSelectPackage:package];
7922 /* Package Settings Controller {{{ */
7923 @interface PackageSettingsController : CyteViewController <
7924 UITableViewDataSource,
7927 _transient Database *database_;
7929 _H<Package> package_;
7930 _H<UITableView, 2> table_;
7931 _H<UISwitch> subscribedSwitch_;
7932 _H<UISwitch> ignoredSwitch_;
7933 _H<UITableViewCell> subscribedCell_;
7934 _H<UITableViewCell> ignoredCell_;
7937 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7941 @implementation PackageSettingsController
7943 - (NSURL *) navigationURL {
7944 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7947 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7948 if (package_ == nil)
7951 if ([package_ installed] == nil)
7957 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7958 if (package_ == nil)
7961 // both sections contain just one item right now.
7965 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7969 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7971 return UCLocalize("SHOW_ALL_CHANGES_EX");
7973 return UCLocalize("IGNORE_UPGRADES_EX");
7976 - (void) onSubscribed:(id)control {
7977 bool value([control isOn]);
7978 if (package_ == nil)
7980 if ([package_ setSubscribed:value])
7981 [delegate_ updateData];
7984 - (void) _updateIgnored {
7985 const char *package([name_ UTF8String]);
7986 bool on([ignoredSwitch_ isOn]);
7988 FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w"));
7989 fwrite(package, strlen(package), 1, dpkg);
7992 fwrite(" hold\n", 6, 1, dpkg);
7994 fwrite(" install\n", 9, 1, dpkg);
7999 - (void) onIgnored:(id)control {
8000 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8001 [invocation setTarget:self];
8002 [invocation setSelector:@selector(_updateIgnored)];
8004 [delegate_ reloadDataWithInvocation:invocation];
8007 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8008 if (package_ == nil)
8011 switch ([indexPath section]) {
8012 case 0: return subscribedCell_;
8013 case 1: return ignoredCell_;
8022 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8023 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8024 [self setView:view];
8026 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8027 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8028 [(UITableView *) table_ setDataSource:self];
8029 [table_ setDelegate:self];
8030 [view addSubview:table_];
8032 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8033 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8034 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8036 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8037 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8038 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8040 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8041 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8042 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8043 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8045 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8046 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8047 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8048 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8051 - (void) viewDidLoad {
8052 [super viewDidLoad];
8054 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8057 - (void) releaseSubviews {
8059 subscribedCell_ = nil;
8061 ignoredSwitch_ = nil;
8062 subscribedSwitch_ = nil;
8064 [super releaseSubviews];
8067 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8068 if ((self = [super init]) != nil) {
8069 database_ = database;
8074 - (void) reloadData {
8077 package_ = [database_ packageWithName:name_];
8079 if (package_ != nil) {
8080 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8081 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8082 } // XXX: what now, G?
8084 [table_ reloadData];
8090 /* Installed Controller {{{ */
8091 @interface InstalledController : FilteredPackageListController {
8095 - (id) initWithDatabase:(Database *)database;
8096 - (void) queueStatusDidChange;
8100 @implementation InstalledController
8102 - (NSURL *) referrerURL {
8103 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8106 - (NSURL *) navigationURL {
8107 return [NSURL URLWithString:@"cydia://installed"];
8110 - (void) useRecent {
8113 @synchronized (self) {
8114 [self setFilter:[](Package *package) {
8115 return ![package uninstalled] && package->role_ < 7;
8118 [self setSorter:[](NSMutableArray *packages) {
8119 [packages radixSortUsingSelector:@selector(recent)];
8123 - (void) useFilter:(UISegmentedControl *)segmented {
8124 NSInteger selected([segmented selectedSegmentIndex]);
8126 return [self useRecent];
8127 bool simple(selected == 0);
8130 @synchronized (self) {
8131 [self setFilter:[=](Package *package) {
8132 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8135 [self setSorter:nullptr];
8138 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8140 return [super sectionsForPackages:packages];
8142 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8144 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8145 Section *section(nil);
8148 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8149 Package *package([packages objectAtIndex:offset]);
8151 time_t upgraded([package upgraded]);
8152 if (upgraded < 1168364520)
8155 upgraded -= upgraded % (60 * 60 * 24);
8157 if (section == nil || upgraded != last) {
8162 continue; // XXX: name = UCLocalize("...");
8164 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8168 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8169 [sections addObject:section];
8172 [section addToCount];
8175 CFRelease(formatter);
8179 - (id) initWithDatabase:(Database *)database {
8180 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8181 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8182 [segmented setSelectedSegmentIndex:0];
8183 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8184 [[self navigationItem] setTitleView:segmented];
8186 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8187 [self useFilter:segmented];
8189 [self queueStatusDidChange];
8194 - (void) queueButtonClicked {
8199 - (void) queueStatusDidChange {
8202 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8203 initWithTitle:UCLocalize("QUEUE")
8204 style:UIBarButtonItemStyleDone
8206 action:@selector(queueButtonClicked)
8209 [[self navigationItem] setRightBarButtonItem:nil];
8214 - (void) modeChanged:(UISegmentedControl *)segmented {
8215 [self useFilter:segmented];
8222 /* Source Cell {{{ */
8223 @interface SourceCell : CyteTableViewCell <
8224 CyteTableViewCellDelegate,
8227 _H<Source, 1> source_;
8230 _H<NSString> origin_;
8231 _H<NSString> label_;
8232 _H<UIActivityIndicatorView> indicator_;
8235 - (void) setSource:(Source *)source;
8236 - (void) setFetch:(NSNumber *)fetch;
8240 @implementation SourceCell
8242 - (void) _setImage:(NSArray *)data {
8243 if ([url_ isEqual:[data objectAtIndex:0]]) {
8244 icon_ = [data objectAtIndex:1];
8245 [content_ setNeedsDisplay];
8249 - (void) _setSource:(NSURL *) url {
8250 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8252 if (NSData *data = [NSURLConnection
8253 sendSynchronousRequest:[NSURLRequest
8255 cachePolicy:NSURLRequestUseProtocolCachePolicy
8259 returningResponse:NULL
8262 if (UIImage *image = [UIImage imageWithData:data])
8263 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8268 - (void) setSource:(Source *)source {
8270 [source_ setDelegate:self];
8272 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8274 icon_ = [UIImage imageNamed:@"unknown.png"];
8276 origin_ = [source name];
8277 label_ = [source rooturi];
8279 [content_ setNeedsDisplay];
8281 url_ = [source iconURL];
8282 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8285 - (void) setAllSource {
8287 [indicator_ stopAnimating];
8289 icon_ = [UIImage imageNamed:@"folder.png"];
8290 origin_ = UCLocalize("ALL_SOURCES");
8291 label_ = UCLocalize("ALL_SOURCES_EX");
8292 [content_ setNeedsDisplay];
8295 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8296 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8297 UIView *content([self contentView]);
8298 CGRect bounds([content bounds]);
8300 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8301 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8302 [content_ setBackgroundColor:[UIColor whiteColor]];
8303 [content addSubview:content_];
8305 [content_ setDelegate:self];
8306 [content_ setOpaque:YES];
8308 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8309 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8310 [content addSubview:indicator_];
8312 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8316 - (void) layoutSubviews {
8317 [super layoutSubviews];
8319 UIView *content([self contentView]);
8320 CGRect bounds([content bounds]);
8322 CGRect frame([indicator_ frame]);
8323 frame.origin.x = bounds.size.width - frame.size.width;
8324 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8326 if (kCFCoreFoundationVersionNumber < 800)
8327 frame.origin.x -= 8;
8328 [indicator_ setFrame:frame];
8331 - (NSString *) accessibilityLabel {
8335 - (void) drawContentRect:(CGRect)rect {
8336 bool highlighted(highlighted_);
8337 float width(rect.size.width);
8341 rect.size = [(UIImage *) icon_ size];
8343 while (rect.size.width > 32 || rect.size.height > 32) {
8344 rect.size.width /= 2;
8345 rect.size.height /= 2;
8348 rect.origin.x = 26 - rect.size.width / 2;
8349 rect.origin.y = 26 - rect.size.height / 2;
8351 [icon_ drawInRect:Retina(rect)];
8354 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8359 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8363 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8366 - (void) setFetch:(NSNumber *)fetch {
8367 if ([fetch boolValue])
8368 [indicator_ startAnimating];
8370 [indicator_ stopAnimating];
8375 /* Sources Controller {{{ */
8376 @interface SourcesController : CyteViewController <
8377 UITableViewDataSource,
8380 _transient Database *database_;
8383 _H<UITableView, 2> list_;
8384 _H<NSMutableArray> sources_;
8388 _H<UIProgressHUD> hud_;
8391 NSURLConnection *trivial_bz2_;
8392 NSURLConnection *trivial_gz_;
8397 - (id) initWithDatabase:(Database *)database;
8398 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8402 @implementation SourcesController
8404 - (void) _releaseConnection:(NSURLConnection *)connection {
8405 if (connection != nil) {
8406 [connection cancel];
8407 //[connection setDelegate:nil];
8408 [connection release];
8413 [self _releaseConnection:trivial_gz_];
8414 [self _releaseConnection:trivial_bz2_];
8419 - (NSURL *) navigationURL {
8420 return [NSURL URLWithString:@"cydia://sources"];
8423 - (void) viewDidAppear:(BOOL)animated {
8424 [super viewDidAppear:animated];
8425 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8428 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8432 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8434 return UCLocalize("INDIVIDUAL_SOURCES");
8438 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8441 case 1: return [sources_ count];
8446 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8447 @synchronized (database_) {
8448 if ([database_ era] != era_)
8450 if ([indexPath section] != 1)
8452 NSUInteger index([indexPath row]);
8453 if (index >= [sources_ count])
8455 return [sources_ objectAtIndex:index];
8458 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8459 static NSString *cellIdentifier = @"SourceCell";
8461 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8462 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8463 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8465 Source *source([self sourceAtIndexPath:indexPath]);
8467 [cell setAllSource];
8469 [cell setSource:source];
8474 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8475 SectionsController *controller([[[SectionsController alloc]
8476 initWithDatabase:database_
8477 source:[self sourceAtIndexPath:indexPath]
8480 [controller setDelegate:delegate_];
8481 [[self navigationController] pushViewController:controller animated:YES];
8484 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8485 if ([indexPath section] != 1)
8487 Source *source = [self sourceAtIndexPath:indexPath];
8488 return [source record] != nil;
8491 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8492 _assert([indexPath section] == 1);
8493 if (editingStyle == UITableViewCellEditingStyleDelete) {
8494 Source *source = [self sourceAtIndexPath:indexPath];
8495 if (source == nil) return;
8497 [Sources_ removeObjectForKey:[source key]];
8499 [delegate_ _saveConfig];
8500 [delegate_ reloadDataWithInvocation:nil];
8504 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8505 [self updateButtonsForEditingStatusAnimated:YES];
8509 [delegate_ addTrivialSource:href_];
8512 [delegate_ syncData];
8515 - (NSString *) getWarning {
8516 NSString *href(href_);
8517 NSRange colon([href rangeOfString:@"://"]);
8518 if (colon.location != NSNotFound)
8519 href = [href substringFromIndex:(colon.location + 3)];
8520 href = [href stringByAddingPercentEscapes];
8521 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8523 NSURL *url([NSURL URLWithString:href]);
8525 NSStringEncoding encoding;
8526 NSError *error(nil);
8528 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8529 return [warning length] == 0 ? nil : warning;
8533 - (void) _endConnection:(NSURLConnection *)connection {
8534 // XXX: the memory management in this method is horribly awkward
8536 NSURLConnection **field = NULL;
8537 if (connection == trivial_bz2_)
8538 field = &trivial_bz2_;
8539 else if (connection == trivial_gz_)
8540 field = &trivial_gz_;
8541 _assert(field != NULL);
8542 [connection release];
8546 trivial_bz2_ == nil &&
8549 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8551 [delegate_ releaseNetworkActivityIndicator];
8553 [delegate_ removeProgressHUD:hud_];
8557 if (warning != nil) {
8558 UIAlertView *alert = [[[UIAlertView alloc]
8559 initWithTitle:UCLocalize("SOURCE_WARNING")
8562 cancelButtonTitle:UCLocalize("CANCEL")
8564 UCLocalize("ADD_ANYWAY"),
8568 [alert setContext:@"warning"];
8569 [alert setNumberOfRows:1];
8572 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8578 } else if (error_ != nil) {
8579 UIAlertView *alert = [[[UIAlertView alloc]
8580 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8581 message:[error_ localizedDescription]
8583 cancelButtonTitle:UCLocalize("OK")
8584 otherButtonTitles:nil
8587 [alert setContext:@"urlerror"];
8592 UIAlertView *alert = [[[UIAlertView alloc]
8593 initWithTitle:UCLocalize("NOT_REPOSITORY")
8594 message:UCLocalize("NOT_REPOSITORY_EX")
8596 cancelButtonTitle:UCLocalize("OK")
8597 otherButtonTitles:nil
8600 [alert setContext:@"trivial"];
8610 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8611 switch ([response statusCode]) {
8617 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8618 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8620 [self _endConnection:connection];
8623 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8624 [self _endConnection:connection];
8627 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8628 NSURL *url([NSURL URLWithString:href]);
8630 NSMutableURLRequest *request = [NSMutableURLRequest
8632 cachePolicy:NSURLRequestUseProtocolCachePolicy
8636 [request setHTTPMethod:method];
8638 if (Machine_ != NULL)
8639 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8641 if (UniqueID_ != nil)
8642 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8644 if ([url isCydiaSecure]) {
8645 if (UniqueID_ != nil)
8646 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8649 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8652 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8653 NSString *context([alert context]);
8655 if ([context isEqualToString:@"source"]) {
8658 NSString *href = [[alert textField] text];
8659 href = VerifySource(href);
8664 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8665 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8669 // XXX: this is stupid
8670 hud_ = [delegate_ addProgressHUD];
8671 [hud_ setText:UCLocalize("VERIFYING_URL")];
8672 [delegate_ retainNetworkActivityIndicator];
8681 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8682 } else if ([context isEqualToString:@"trivial"])
8683 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8684 else if ([context isEqualToString:@"urlerror"])
8685 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8686 else if ([context isEqualToString:@"warning"]) {
8689 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8698 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8702 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8703 BOOL editing([list_ isEditing]);
8706 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8707 initWithTitle:UCLocalize("ADD")
8708 style:UIBarButtonItemStylePlain
8710 action:@selector(addButtonClicked)
8711 ] autorelease] animated:animated];
8712 else if ([delegate_ updating])
8713 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8714 initWithTitle:UCLocalize("CANCEL")
8715 style:UIBarButtonItemStyleDone
8717 action:@selector(cancelButtonClicked)
8718 ] autorelease] animated:animated];
8720 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8721 initWithTitle:UCLocalize("REFRESH")
8722 style:UIBarButtonItemStylePlain
8724 action:@selector(refreshButtonClicked)
8725 ] autorelease] animated:animated];
8727 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8728 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8729 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8731 action:@selector(editButtonClicked)
8732 ] autorelease] animated:animated];
8736 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8737 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8738 [list_ setRowHeight:53];
8739 [(UITableView *) list_ setDataSource:self];
8740 [list_ setDelegate:self];
8741 [self setView:list_];
8744 - (void) viewDidLoad {
8745 [super viewDidLoad];
8747 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8748 [self updateButtonsForEditingStatusAnimated:NO];
8751 - (void) viewWillAppear:(BOOL)animated {
8752 [super viewWillAppear:animated];
8754 [list_ setEditing:NO];
8755 [self updateButtonsForEditingStatusAnimated:NO];
8758 - (void) releaseSubviews {
8763 [super releaseSubviews];
8766 - (id) initWithDatabase:(Database *)database {
8767 if ((self = [super init]) != nil) {
8768 database_ = database;
8772 - (void) reloadData {
8774 [self updateButtonsForEditingStatusAnimated:YES];
8776 @synchronized (database_) {
8777 era_ = [database_ era];
8779 sources_ = [NSMutableArray arrayWithCapacity:16];
8780 [sources_ addObjectsFromArray:[database_ sources]];
8782 [sources_ sortUsingSelector:@selector(compareByName:)];
8785 int count([sources_ count]);
8787 for (int i = 0; i != count; i++) {
8788 if ([[sources_ objectAtIndex:i] record] == nil)
8796 - (void) showAddSourcePrompt {
8797 UIAlertView *alert = [[[UIAlertView alloc]
8798 initWithTitle:UCLocalize("ENTER_APT_URL")
8801 cancelButtonTitle:UCLocalize("CANCEL")
8803 UCLocalize("ADD_SOURCE"),
8807 [alert setContext:@"source"];
8809 [alert setNumberOfRows:1];
8810 [alert addTextFieldWithValue:@"http://" label:@""];
8812 UITextInputTraits *traits = [[alert textField] textInputTraits];
8813 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8814 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8815 [traits setKeyboardType:UIKeyboardTypeURL];
8816 // XXX: UIReturnKeyDone
8817 [traits setReturnKeyType:UIReturnKeyNext];
8822 - (void) addButtonClicked {
8823 [self showAddSourcePrompt];
8826 - (void) refreshButtonClicked {
8827 if ([delegate_ requestUpdate])
8828 [self updateButtonsForEditingStatusAnimated:YES];
8831 - (void) cancelButtonClicked {
8832 [delegate_ cancelUpdate];
8835 - (void) editButtonClicked {
8836 [list_ setEditing:![list_ isEditing] animated:YES];
8837 [self updateButtonsForEditingStatusAnimated:YES];
8843 /* Stash Controller {{{ */
8844 @interface StashController : CyteViewController {
8845 _H<UIActivityIndicatorView> spinner_;
8846 _H<UILabel> status_;
8847 _H<UILabel> caption_;
8852 @implementation StashController
8855 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8856 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8857 [self setView:view];
8859 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8861 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8862 CGRect spinrect = [spinner_ frame];
8863 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8864 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8865 [spinner_ setFrame:spinrect];
8866 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8867 [view addSubview:spinner_];
8868 [spinner_ startAnimating];
8871 captrect.size.width = [[self view] frame].size.width;
8872 captrect.size.height = 40.0f;
8873 captrect.origin.x = 0;
8874 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8875 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8876 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8877 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8878 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8879 [caption_ setTextColor:[UIColor whiteColor]];
8880 [caption_ setBackgroundColor:[UIColor clearColor]];
8881 [caption_ setShadowColor:[UIColor blackColor]];
8882 [caption_ setTextAlignment:NSTextAlignmentCenter];
8883 [view addSubview:caption_];
8886 statusrect.size.width = [[self view] frame].size.width;
8887 statusrect.size.height = 30.0f;
8888 statusrect.origin.x = 0;
8889 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8890 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8891 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8892 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8893 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8894 [status_ setTextColor:[UIColor whiteColor]];
8895 [status_ setBackgroundColor:[UIColor clearColor]];
8896 [status_ setShadowColor:[UIColor blackColor]];
8897 [status_ setTextAlignment:NSTextAlignmentCenter];
8898 [view addSubview:status_];
8901 - (void) releaseSubviews {
8906 [super releaseSubviews];
8912 @interface CYURLCache : SDURLCache {
8917 @implementation CYURLCache
8919 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8922 else if ([event isEqualToString:@"no-cache"])
8924 else if ([event isEqualToString:@"store"])
8926 else if ([event isEqualToString:@"invalid"])
8928 else if ([event isEqualToString:@"memory"])
8930 else if ([event isEqualToString:@"disk"])
8932 else if ([event isEqualToString:@"miss"])
8935 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8939 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8940 if (NSURLResponse *response = [cached response])
8941 if (NSString *mime = [response MIMEType])
8942 if ([mime isEqualToString:@"text/cache-manifest"]) {
8943 NSURL *url([response URL]);
8946 NSLog(@"###: %@", [url absoluteString]);
8949 @synchronized (HostConfig_) {
8950 [CachedURLs_ addObject:url];
8954 [super storeCachedResponse:cached forRequest:request];
8957 - (void) createDiskCachePath {
8958 [super createDiskCachePath];
8963 @interface Cydia : UIApplication <
8964 ConfirmationControllerDelegate,
8968 _H<UIWindow> window_;
8969 _H<CydiaTabBarController> tabbar_;
8970 _H<CyteTabBarController> emulated_;
8971 _H<AppCacheController> appcache_;
8973 _H<NSMutableArray> essential_;
8974 _H<NSMutableArray> broken_;
8976 Database *database_;
8978 _H<NSURL> starturl_;
8983 _H<StashController> stash_;
8992 @implementation Cydia
8994 - (void) lockSuspend {
8995 if (locked_++ == 0) {
8996 if ($SBSSetInterceptsMenuButtonForever != NULL)
8997 (*$SBSSetInterceptsMenuButtonForever)(true);
8999 [self setIdleTimerDisabled:YES];
9003 - (void) unlockSuspend {
9004 if (--locked_ == 0) {
9005 [self setIdleTimerDisabled:NO];
9007 if ($SBSSetInterceptsMenuButtonForever != NULL)
9008 (*$SBSSetInterceptsMenuButtonForever)(false);
9012 - (void) beginUpdate {
9013 [tabbar_ beginUpdate];
9016 - (void) cancelUpdate {
9017 [tabbar_ cancelUpdate];
9020 - (bool) requestUpdate {
9021 if (IsReachable("cydia.saurik.com")) {
9025 UIAlertView *alert = [[[UIAlertView alloc]
9026 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
9027 message:@"Host Unreachable" // XXX: Localize
9029 cancelButtonTitle:UCLocalize("OK")
9030 otherButtonTitles:nil
9033 [alert setContext:@"norefresh"];
9041 return [tabbar_ updating];
9045 if ([broken_ count] != 0) {
9046 int count = [broken_ count];
9048 UIAlertView *alert = [[[UIAlertView alloc]
9049 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9050 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9052 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9054 UCLocalize("TEMPORARY_IGNORE"),
9058 [alert setContext:@"fixhalf"];
9059 [alert setNumberOfRows:2];
9061 } else if (!Ignored_ && [essential_ count] != 0) {
9062 int count = [essential_ count];
9064 UIAlertView *alert = [[[UIAlertView alloc]
9065 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9066 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9068 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9070 UCLocalize("UPGRADE_ESSENTIAL"),
9071 UCLocalize("COMPLETE_UPGRADE"),
9075 [alert setContext:@"upgrade"];
9080 - (void) returnToCydia {
9084 - (void) reloadSpringBoard {
9085 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
9086 system("/bin/launchctl stop com.apple.backboardd");
9088 system("/bin/launchctl stop com.apple.SpringBoard");
9090 system("/usr/bin/killall backboardd SpringBoard");
9093 - (void) _saveConfig {
9094 SaveConfig(database_);
9097 // Navigation controller for the queuing badge.
9098 - (UINavigationController *) queueNavigationController {
9099 NSArray *controllers = [tabbar_ viewControllers];
9100 return [controllers objectAtIndex:3];
9103 - (void) unloadData {
9104 [tabbar_ unloadData];
9107 - (void) _updateData {
9111 UINavigationController *navigation = [self queueNavigationController];
9113 id queuedelegate = nil;
9114 if ([[navigation viewControllers] count] > 0)
9115 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9117 [queuedelegate queueStatusDidChange];
9118 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9121 - (void) _refreshIfPossible {
9122 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9124 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:@ CacheState_] objectForKey:@"LastUpdate"]);
9126 bool recently = false;
9127 if (update != nil) {
9128 NSTimeInterval interval([update timeIntervalSinceNow]);
9129 if (interval > -(15*60))
9133 // Don't automatic refresh if:
9134 // - We already refreshed recently.
9135 // - We already auto-refreshed this launch.
9136 // - Auto-refresh is disabled.
9137 // - Cydia's server is not reachable
9138 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9139 // If we are cancelling, we need to make sure it knows it's already loaded.
9142 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9144 // We are going to load, so remember that.
9147 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
9153 - (void) refreshIfPossible {
9154 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
9157 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9158 _profile(reloadDataWithInvocation)
9159 @synchronized (self) {
9160 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9162 [hud setText:UCLocalize("RELOADING_DATA")];
9164 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9168 [essential_ removeAllObjects];
9169 [broken_ removeAllObjects];
9171 _profile(reloadDataWithInvocation$Essential)
9172 NSArray *packages([database_ packages]);
9173 for (Package *package in packages) {
9175 [broken_ addObject:package];
9176 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9177 if ([package essential] && [package installed] != nil)
9178 [essential_ addObject:package];
9184 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9187 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9188 [changesItem setBadgeValue:badge];
9189 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9190 [self setApplicationIconBadgeNumber:changes];
9193 [changesItem setBadgeValue:nil];
9194 [changesItem setAnimatedBadge:NO];
9195 [self setApplicationIconBadgeNumber:0];
9202 [self removeProgressHUD:hud];
9209 - (void) updateData {
9213 - (void) updateDataAndLoad {
9215 if ([database_ progressDelegate] == nil)
9221 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9224 - (void) disemulate {
9225 if (emulated_ == nil)
9228 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9229 [window_ setRootViewController:tabbar_];
9231 [window_ addSubview:[tabbar_ view]];
9232 [[emulated_ view] removeFromSuperview];
9236 [window_ setUserInteractionEnabled:YES];
9239 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9240 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9242 UIViewController *parent;
9243 if (emulated_ == nil)
9253 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9254 [parent presentModalViewController:navigation animated:YES];
9257 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9258 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9260 if (navigation != nil)
9261 [navigation pushViewController:progress animated:YES];
9263 [self presentModalViewController:progress force:YES];
9265 [progress invoke:invocation withTitle:title];
9269 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9270 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9273 - (void) repairWithInvocation:(NSInvocation *)invocation {
9275 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9279 - (void) repairWithSelector:(SEL)selector {
9280 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9283 - (void) reloadData {
9284 [self reloadDataWithInvocation:nil];
9285 if ([database_ progressDelegate] == nil)
9291 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9294 - (void) addSource:(NSDictionary *) source {
9295 CydiaAddSource(source);
9298 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9299 CydiaAddSource(href, distribution, sections);
9302 // XXX: this method should not return anything
9303 - (BOOL) addTrivialSource:(NSString *)href {
9304 CydiaAddSource(href, @"./");
9309 pkgProblemResolver *resolver = [database_ resolver];
9311 resolver->InstallProtect();
9312 if (!resolver->Resolve(true))
9317 // XXX: this is a really crappy way of doing this.
9318 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9319 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9320 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9321 if ([tabbar_ updating])
9322 [tabbar_ cancelUpdate];
9324 if (![database_ prepare])
9327 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9328 [page setDelegate:self];
9329 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9332 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9333 [tabbar_ presentModalViewController:confirm_ animated:YES];
9339 @synchronized (self) {
9344 - (void) clearPackage:(Package *)package {
9345 @synchronized (self) {
9352 - (void) installPackages:(NSArray *)packages {
9353 @synchronized (self) {
9354 for (Package *package in packages)
9361 - (void) installPackage:(Package *)package {
9362 @synchronized (self) {
9369 - (void) removePackage:(Package *)package {
9370 @synchronized (self) {
9377 - (void) distUpgrade {
9378 @synchronized (self) {
9379 if (![database_ upgrade])
9387 system("/usr/bin/uicache");
9392 UIProgressHUD *hud([self addProgressHUD]);
9393 [hud setText:UCLocalize("LOADING")];
9394 [self yieldToSelector:@selector(_uicache)];
9395 [self removeProgressHUD:hud];
9399 [database_ perform];
9400 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9401 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9404 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9407 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9408 [self unlockSuspend];
9411 - (void) retainNetworkActivityIndicator {
9412 if (activity_++ == 0)
9413 [self setNetworkActivityIndicatorVisible:YES];
9416 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9420 - (void) releaseNetworkActivityIndicator {
9421 if (--activity_ == 0)
9422 [self setNetworkActivityIndicatorVisible:NO];
9425 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9430 - (void) cancelAndClear:(bool)clear {
9431 @synchronized (self) {
9443 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9444 NSString *context([alert context]);
9446 if ([context isEqualToString:@"conffile"]) {
9447 FILE *input = [database_ input];
9448 if (button == [alert cancelButtonIndex])
9449 fprintf(input, "N\n");
9450 else if (button == [alert firstOtherButtonIndex])
9451 fprintf(input, "Y\n");
9454 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9455 } else if ([context isEqualToString:@"fixhalf"]) {
9456 if (button == [alert cancelButtonIndex]) {
9457 @synchronized (self) {
9458 for (Package *broken in (id) broken_) {
9460 NSString *id(ShellEscape([broken id]));
9461 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
9462 " /var/lib/dpkg/info/%@.prerm"
9463 " /var/lib/dpkg/info/%@.postrm"
9464 " /var/lib/dpkg/info/%@.preinst"
9465 " /var/lib/dpkg/info/%@.postinst"
9466 " /var/lib/dpkg/info/%@.extrainst_"
9467 "", id, id, id, id, id] UTF8String]);
9473 } else if (button == [alert firstOtherButtonIndex]) {
9474 [broken_ removeAllObjects];
9478 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9479 } else if ([context isEqualToString:@"upgrade"]) {
9480 if (button == [alert firstOtherButtonIndex]) {
9481 @synchronized (self) {
9482 for (Package *essential in (id) essential_)
9483 [essential install];
9488 } else if (button == [alert firstOtherButtonIndex] + 1) {
9490 } else if (button == [alert cancelButtonIndex]) {
9494 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9498 - (void) system:(NSString *)command {
9499 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9502 system([command UTF8String]);
9508 - (void) applicationWillSuspend {
9510 [super applicationWillSuspend];
9513 - (BOOL) isSafeToSuspend {
9516 NSLog(@"isSafeToSuspend: locked_ != 0");
9521 if ([tabbar_ modalViewController] != nil)
9524 // Use external process status API internally.
9525 // This is probably a really bad idea.
9526 // XXX: what is the point of this? does this solve anything at all?
9527 uint64_t status = 0;
9529 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9530 notify_get_state(notify_token, &status);
9531 notify_cancel(notify_token);
9536 NSLog(@"isSafeToSuspend: status != 0");
9542 NSLog(@"isSafeToSuspend: -> true");
9547 - (void) suspendReturningToLastApp:(BOOL)returning {
9548 if ([self isSafeToSuspend])
9549 [super suspendReturningToLastApp:returning];
9553 if ([self isSafeToSuspend])
9557 - (void) applicationSuspend {
9558 if ([self isSafeToSuspend])
9559 [super applicationSuspend];
9562 - (void) applicationSuspend:(__GSEvent *)event {
9563 if ([self isSafeToSuspend])
9564 [super applicationSuspend:event];
9567 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9568 if ([self isSafeToSuspend])
9569 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9572 - (void) _setSuspended:(BOOL)value {
9573 if ([self isSafeToSuspend])
9574 [super _setSuspended:value];
9577 - (UIProgressHUD *) addProgressHUD {
9578 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9579 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9581 [window_ setUserInteractionEnabled:NO];
9583 UIViewController *target(tabbar_);
9584 if (UIViewController *modal = [target modalViewController])
9587 [hud showInView:[target view]];
9593 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9594 [self unlockSuspend];
9596 [hud removeFromSuperview];
9597 [window_ setUserInteractionEnabled:YES];
9600 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9601 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9604 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9605 NSString *scheme([[url scheme] lowercaseString]);
9606 if ([[url absoluteString] length] <= [scheme length] + 3)
9608 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9609 NSArray *components([path componentsSeparatedByString:@"/"]);
9611 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9612 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9613 if (controller != nil)
9614 [controller setDelegate:self];
9618 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9621 NSString *base([components objectAtIndex:0]);
9623 CyteViewController *controller = nil;
9625 if ([base isEqualToString:@"url"]) {
9626 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9627 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9628 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9629 } else if (!external && [components count] == 1) {
9630 if ([base isEqualToString:@"sources"]) {
9631 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9634 if ([base isEqualToString:@"home"]) {
9635 controller = [[[HomeController alloc] init] autorelease];
9638 if ([base isEqualToString:@"sections"]) {
9639 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9642 if ([base isEqualToString:@"search"]) {
9643 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9646 if ([base isEqualToString:@"changes"]) {
9647 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9650 if ([base isEqualToString:@"installed"]) {
9651 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9653 } else if ([components count] == 2) {
9654 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9656 if ([base isEqualToString:@"package"]) {
9657 controller = [self pageForPackage:argument withReferrer:referrer];
9660 if (!external && [base isEqualToString:@"search"]) {
9661 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9664 if (!external && [base isEqualToString:@"sections"]) {
9665 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9667 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9670 if ([base isEqualToString:@"sources"]) {
9671 if ([argument isEqualToString:@"add"]) {
9672 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9673 [(SourcesController *)controller showAddSourcePrompt];
9675 Source *source([database_ sourceWithKey:argument]);
9676 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9680 if (!external && [base isEqualToString:@"launch"]) {
9681 [self launchApplicationWithIdentifier:argument suspended:NO];
9684 } else if (!external && [components count] == 3) {
9685 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9686 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9688 if ([base isEqualToString:@"package"]) {
9689 if ([arg2 isEqualToString:@"settings"]) {
9690 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9691 } else if ([arg2 isEqualToString:@"files"]) {
9692 if (Package *package = [database_ packageWithName:arg1]) {
9693 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9694 [(FileTable *)controller setPackage:package];
9699 if ([base isEqualToString:@"sections"]) {
9700 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9701 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9702 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9706 [controller setDelegate:self];
9710 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9711 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9714 [tabbar_ setUnselectedViewController:page];
9719 - (void) applicationOpenURL:(NSURL *)url {
9720 [super applicationOpenURL:url];
9725 [self openCydiaURL:url forExternal:YES];
9728 - (void) applicationWillResignActive:(UIApplication *)application {
9729 // Stop refreshing if you get a phone call or lock the device.
9730 if ([tabbar_ updating])
9731 [tabbar_ cancelUpdate];
9733 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9734 [super applicationWillResignActive:application];
9737 - (void) saveState {
9738 [[NSDictionary dictionaryWithObjectsAndKeys:
9739 @"InterfaceState", [tabbar_ navigationURLCollection],
9740 @"LastClosed", [NSDate date],
9741 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
9742 nil] writeToFile:@ SavedState_ atomically:YES];
9747 - (void) applicationWillTerminate:(UIApplication *)application {
9751 - (void) applicationDidEnterBackground:(UIApplication *)application {
9752 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9753 return [self terminateWithSuccess];
9754 Backgrounded_ = [NSDate date];
9758 - (void) applicationWillEnterForeground:(UIApplication *)application {
9759 if (Backgrounded_ == nil)
9762 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
9764 if (interval <= -(30*60)) {
9765 [tabbar_ setSelectedIndex:0];
9766 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9769 if (interval <= -(15*60)) {
9770 if (IsReachable("cydia.saurik.com")) {
9771 [tabbar_ beginUpdate];
9772 [appcache_ reloadURLWithCache:YES];
9776 if ([database_ delocked])
9780 - (void) setConfigurationData:(NSString *)data {
9781 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9783 if (!conffile_r(data)) {
9784 lprintf("E:invalid conffile\n");
9788 NSString *ofile = conffile_r[1];
9789 //NSString *nfile = conffile_r[2];
9791 UIAlertView *alert = [[[UIAlertView alloc]
9792 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9793 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9795 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9797 UCLocalize("ACCEPT_NEW_COPY"),
9798 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9802 [alert setContext:@"conffile"];
9803 [alert setNumberOfRows:2];
9807 - (void) addStashController {
9809 stash_ = [[[StashController alloc] init] autorelease];
9810 [window_ addSubview:[stash_ view]];
9813 - (void) removeStashController {
9814 [[stash_ view] removeFromSuperview];
9816 [self unlockSuspend];
9820 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9821 UpdateExternalStatus(1);
9822 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9823 UpdateExternalStatus(0);
9825 [self removeStashController];
9826 [self reloadSpringBoard];
9829 - (void) setupViewControllers {
9830 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9832 NSMutableArray *items;
9833 if (kCFCoreFoundationVersionNumber < 800) {
9834 items = [NSMutableArray arrayWithObjects:
9835 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9836 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9837 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9838 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9839 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9842 items = [NSMutableArray arrayWithObjects:
9843 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9844 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9845 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9846 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9847 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9851 NSMutableArray *controllers([NSMutableArray array]);
9852 for (UITabBarItem *item in items) {
9853 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9854 [controller setTabBarItem:item];
9855 [controllers addObject:controller];
9857 [tabbar_ setViewControllers:controllers];
9859 [tabbar_ setUpdateDelegate:self];
9862 - (void) _sendMemoryWarningNotification {
9863 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9864 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9866 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9869 - (void) _sendMemoryWarningNotifications {
9871 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9877 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9879 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9882 - (void) applicationDidFinishLaunching:(id)unused {
9883 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9886 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9887 [self setApplicationSupportsShakeToEdit:NO];
9889 @synchronized (HostConfig_) {
9890 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9893 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9894 initWithMemoryCapacity:524288
9895 diskCapacity:10485760
9896 diskPath:Cache("SDURLCache")
9899 [CydiaWebViewController _initialize];
9901 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9903 // this would disallow http{,s} URLs from accessing this data
9904 //[WebView registerURLSchemeAsLocal:@"cydia"];
9906 Font12_ = [UIFont systemFontOfSize:12];
9907 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9908 Font14_ = [UIFont systemFontOfSize:14];
9909 Font18_ = [UIFont systemFontOfSize:18];
9910 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9911 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9913 essential_ = [NSMutableArray arrayWithCapacity:4];
9914 broken_ = [NSMutableArray arrayWithCapacity:4];
9916 // XXX: I really need this thing... like, seriously... I'm sorry
9917 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9918 [appcache_ reloadData];
9920 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9921 [window_ orderFront:self];
9922 [window_ makeKey:self];
9923 [window_ setHidden:NO];
9925 if (access("/.cydia_no_stash", F_OK) == 0);
9929 [self addStashController];
9930 // XXX: this would be much cleaner as a yieldToSelector:
9931 // that way the removeStashController could happen right here inline
9932 // we also could no longer require the useless stash_ field anymore
9933 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9938 int error(stat("/", &root));
9939 _assert(error != -1);
9941 #define Stash_(path) do { \
9942 struct stat folder; \
9943 int error(lstat((path), &folder)); \
9944 if (error != -1 && ( \
9945 folder.st_dev == root.st_dev && \
9946 S_ISDIR(folder.st_mode) \
9947 ) || error == -1 && ( \
9948 errno == ENOENT || \
9953 Stash_("/Applications");
9954 Stash_("/Library/Ringtones");
9955 Stash_("/Library/Wallpaper");
9956 //Stash_("/usr/bin");
9957 Stash_("/usr/include");
9958 Stash_("/usr/share");
9959 //Stash_("/var/lib");
9963 database_ = [Database sharedInstance];
9964 [database_ setDelegate:self];
9966 [window_ setUserInteractionEnabled:NO];
9967 [self setupViewControllers];
9969 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9970 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9971 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9973 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9974 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9975 [emulated_ setSelectedIndex:0];
9977 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9978 [emulated_ concealTabBarSelection];
9980 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9981 [window_ setRootViewController:emulated_];
9983 [window_ addSubview:[emulated_ view]];
9985 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9989 - (NSArray *) defaultStartPages {
9990 NSMutableArray *standard = [NSMutableArray array];
9991 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9992 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9993 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9994 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9995 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10001 if ([emulated_ modalViewController] != nil)
10002 [emulated_ dismissModalViewControllerAnimated:YES];
10003 [window_ setUserInteractionEnabled:NO];
10005 [self reloadDataWithInvocation:nil];
10006 [self refreshIfPossible];
10009 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
10011 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
10012 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
10013 int standardIndex = 0;
10014 NSArray *standard = [self defaultStartPages];
10021 NSDate *closed = [state objectForKey:@"LastClosed"];
10022 if (valid && closed != nil) {
10023 NSTimeInterval interval([closed timeIntervalSinceNow]);
10024 if (interval <= -(30*60))
10028 if (valid && [saved count] != [standard count])
10032 for (unsigned int i = 0; i < [standard count]; i++) {
10033 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10034 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10035 // but it's good enough for now.
10036 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10043 NSArray *items = nil;
10045 [tabbar_ setSelectedIndex:savedIndex];
10048 [tabbar_ setSelectedIndex:standardIndex];
10052 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10053 NSArray *stack = [items objectAtIndex:tab];
10054 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10055 NSMutableArray *current = [NSMutableArray array];
10057 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10058 NSString *addr = [stack objectAtIndex:nav];
10059 NSURL *url = [NSURL URLWithString:addr];
10060 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10062 [current addObject:page];
10065 [navigation setViewControllers:current];
10068 // (Try to) show the startup URL.
10069 if (starturl_ != nil) {
10070 [self openCydiaURL:starturl_ forExternal:YES];
10075 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10077 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
10078 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
10081 if (item != nil && IsWildcat_) {
10082 [sheet showFromBarButtonItem:item animated:YES];
10084 [sheet showInView:window_];
10088 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10089 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10090 [progress setTitle:task];
10091 [progress addProgressEvent:event];
10094 - (void) addProgressEventForTask:(NSArray *)data {
10095 CydiaProgressEvent *event([data objectAtIndex:0]);
10096 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10097 [self addProgressEvent:event forTask:task];
10100 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10101 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10107 id Alloc_(id self, SEL selector) {
10108 id object = alloc_(self, selector);
10109 lprintf("[%s]A-%p\n", self->isa->name, object);
10114 id Dealloc_(id self, SEL selector) {
10115 id object = dealloc_(self, selector);
10116 lprintf("[%s]D-%p\n", self->isa->name, object);
10120 Class $NSURLConnection;
10122 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10123 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10125 NSURL *url([copy URL]);
10127 NSString *host([url host]);
10128 NSString *scheme([[url scheme] lowercaseString]);
10130 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10132 @synchronized (HostConfig_) {
10133 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10134 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10135 [copy setHTTPShouldUsePipelining:YES];
10137 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10138 if ([control isEqualToString:@"max-age=0"])
10139 if ([CachedURLs_ containsObject:url]) {
10141 NSLog(@"~~~: %@", url);
10144 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10146 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10147 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10148 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10152 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10158 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10159 CGSize size([[UIScreen mainScreen] bounds].size);
10160 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10161 if ([$WAKWindow hasLandscapeOrientation])
10162 std::swap(size.width, size.height);*/
10166 Class $NSUserDefaults;
10168 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10169 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10170 return Cache("LocalStorage");
10171 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10174 static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) {
10177 if (CFGetTypeID(type) != CFDictionaryGetTypeID())
10179 CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers));
10181 return [(NSMutableDictionary *) copy autorelease];
10184 int main(int argc, char *argv[]) {
10185 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
10189 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10193 UpdateExternalStatus(0);
10195 UIScreen *screen([UIScreen mainScreen]);
10196 if ([screen respondsToSelector:@selector(scale)])
10197 ScreenScale_ = [screen scale];
10201 UIDevice *device([UIDevice currentDevice]);
10202 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10203 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10204 if (idiom == UIUserInterfaceIdiomPad)
10208 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10210 RegEx pattern("([0-9]+\\.[0-9]+).*");
10212 if (pattern([device systemVersion]))
10213 Firmware_ = pattern[1];
10214 if (pattern(Cydia_))
10215 Major_ = pattern[1];
10217 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10219 HostConfig_ = [[[NSObject alloc] init] autorelease];
10220 @synchronized (HostConfig_) {
10221 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10222 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10223 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10224 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10227 NSString *ui(@"ui/ios");
10229 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10230 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10231 UI_ = CydiaURL(ui);
10233 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10235 /* Library Hacks {{{ */
10236 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10238 $WAKWindow = objc_getClass("WAKWindow");
10239 if ($WAKWindow != NULL)
10240 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10241 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10243 $NSURLConnection = objc_getClass("NSURLConnection");
10244 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10245 if (NSURLConnection$init$ != NULL) {
10246 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10247 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10250 $NSUserDefaults = objc_getClass("NSUserDefaults");
10251 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10252 if (NSUserDefaults$objectForKey$ != NULL) {
10253 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10254 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10257 /* Set Locale {{{ */
10258 Locale_ = CFLocaleCopyCurrent();
10259 Languages_ = [NSLocale preferredLanguages];
10261 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10262 //NSLog(@"%@", [Languages_ description]);
10265 if (Locale_ != NULL)
10266 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10267 else if (Languages_ != nil && [Languages_ count] != 0)
10268 lang = [[Languages_ objectAtIndex:0] UTF8String];
10270 // XXX: consider just setting to C and then falling through?
10273 if (lang != NULL) {
10274 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
10275 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10278 NSLog(@"Setting Language: %s", lang);
10280 if (lang != NULL) {
10281 setenv("LANG", lang, true);
10282 std::setlocale(LC_ALL, lang);
10285 /* Index Collation {{{ */
10286 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10287 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10288 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10289 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10290 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10291 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10293 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10295 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10296 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10297 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})
10298 CollationOffset_.push_back(offset);
10299 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];
10300 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];
10303 CollationThumbs_ = [collation sectionIndexTitles];
10304 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10305 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10307 CollationTitles_ = [collation sectionTitles];
10308 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10310 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10311 if (&transform != NULL && transform != nil) {
10312 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10313 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10314 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10315 UErrorCode code(U_ZERO_ERROR);
10316 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10317 if (!U_SUCCESS(code))
10318 NSLog(@"%s", u_errorName(code));
10322 } @catch (NSException *e) {
10326 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10328 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];
10329 for (NSInteger offset(0); offset != 28; ++offset)
10330 CollationOffset_.push_back(offset);
10332 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];
10333 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];
10336 /* Parse Arguments {{{ */
10337 bool substrate(false);
10343 for (int argi(1); argi != argc; ++argi)
10344 if (strcmp(argv[argi], "--") == 0) {
10346 argv[argi] = argv[0];
10352 for (int argi(1); argi != arge; ++argi)
10353 if (strcmp(args[argi], "--substrate") == 0)
10356 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10360 App_ = [[NSBundle mainBundle] bundlePath];
10363 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10364 mkdir([Cache_ UTF8String], 0755);
10366 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10367 alloc_ = alloc->method_imp;
10368 alloc->method_imp = (IMP) &Alloc_;*/
10370 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10371 dealloc_ = dealloc->method_imp;
10372 dealloc->method_imp = (IMP) &Dealloc_;*/
10374 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10375 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10377 /* System Information {{{ */
10381 size = sizeof(maxproc);
10382 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10383 perror("sysctlbyname(\"kern.maxproc\", ?)");
10384 else if (maxproc < 64) {
10386 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10387 perror("sysctlbyname(\"kern.maxproc\", #)");
10390 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10391 char *osversion = new char[size];
10392 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10393 perror("sysctlbyname(\"kern.osversion\", ?)");
10395 System_ = [NSString stringWithUTF8String:osversion];
10397 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10398 char *machine = new char[size];
10399 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10400 perror("sysctlbyname(\"hw.machine\", ?)");
10402 Machine_ = machine;
10404 int64_t usermem(0);
10405 size = sizeof(usermem);
10406 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10409 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10410 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10411 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10413 UniqueID_ = UniqueIdentifier(device);
10415 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10416 Product_ = [info objectForKey:@"SafariProductVersion"];
10417 Safari_ = [info objectForKey:@"CFBundleVersion"];
10420 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10422 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Safari_))
10423 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[1], agent];
10424 if (RegEx match = RegEx("([0-9]+[A-Z][0-9]+[a-z]?).*", System_))
10425 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[1], agent];
10426 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Product_))
10427 agent = [NSString stringWithFormat:@"Version/%@ %@", match[1], agent];
10429 UserAgent_ = agent;
10431 /* Load Database {{{ */
10432 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10435 mkdir("/var/mobile/Library/Cydia", 0755);
10436 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
10439 Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")));
10440 Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")));
10441 Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")));
10442 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
10445 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
10447 if (Values_ == nil)
10448 Values_ = [metadata objectForKey:@"Values"];
10449 if (Values_ == nil)
10450 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10452 if (Sections_ == nil)
10453 Sections_ = [metadata objectForKey:@"Sections"];
10454 if (Sections_ == nil)
10455 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10457 if (Sources_ == nil)
10458 Sources_ = [metadata objectForKey:@"Sources"];
10459 if (Sources_ == nil)
10460 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10462 // XXX: this wrong, but in a way that doesn't matter :/
10463 if (Version_ == nil)
10464 Version_ = [metadata objectForKey:@"Version"];
10465 if (Version_ == nil)
10466 Version_ = [NSNumber numberWithUnsignedInt:0];
10468 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
10470 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
10473 NSLog(@"unable to import package preferences... from 2010? oh well :/");
10476 if ([Version_ unsignedIntValue] == 0) {
10477 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10478 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10479 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10480 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10482 Version_ = [NSNumber numberWithUnsignedInt:1];
10484 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:@ CacheState_]) {
10485 [cache removeObjectForKey:@"LastUpdate"];
10486 [cache writeToFile:@ CacheState_ atomically:YES];
10490 _H<NSMutableArray> broken([NSMutableArray array]);
10491 for (NSString *key in (id) Sources_)
10492 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound || ![([[Sources_ objectForKey:key] objectForKey:@"URI"] ?: @"/") hasSuffix:@"/"])
10493 [broken addObject:key];
10494 if ([broken count] != 0)
10495 for (NSString *key in (id) broken)
10496 [Sources_ removeObjectForKey:key];
10500 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
10503 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10505 if (kCFCoreFoundationVersionNumber > 1000)
10506 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
10508 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10510 if (access("/User", F_OK) != 0 || version != 6) {
10512 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
10516 if (access("/tmp/cydia.chk", F_OK) == 0) {
10517 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10518 _assert(errno == ENOENT);
10519 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10520 _assert(errno == ENOENT);
10523 system("/usr/libexec/cydia/cydo /bin/ln -sf /var/mobile/Library/Caches/com.saurik.Cydia/sources.list /etc/apt/sources.list.d/cydia.list");
10525 /* APT Initialization {{{ */
10526 _assert(pkgInitConfig(*_config));
10527 _assert(pkgInitSystem(*_config, _system));
10530 _config->Set("APT::Acquire::Translation", lang);
10532 // XXX: this timeout might be important :(
10533 //_config->Set("Acquire::http::Timeout", 15);
10535 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10537 mkdir([Cache("archives") UTF8String], 0755);
10538 mkdir([Cache("archives/partial") UTF8String], 0755);
10539 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10541 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
10542 _config->Set("Dir::State", [Cache_ UTF8String]);
10544 mkdir([Cache("lists") UTF8String], 0755);
10545 mkdir([Cache("lists/partial") UTF8String], 0755);
10546 mkdir([Cache("periodic") UTF8String], 0755);
10547 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10549 std::string logs("/var/mobile/Library/Logs/Cydia");
10550 mkdir(logs.c_str(), 0755);
10551 _config->Set("Dir::Log::Terminal", logs + "/apt.log");
10553 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
10555 /* Color Choices {{{ */
10556 space_ = CGColorSpaceCreateDeviceRGB();
10558 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10559 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10560 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10561 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10562 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10563 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10564 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10565 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10566 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10567 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10569 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10570 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10572 /* UIKit Configuration {{{ */
10573 // XXX: I have a feeling this was important
10574 //UIKeyboardDisableAutomaticAppearance();
10577 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10578 $SBSCopyIconImagePNGDataForDisplayIdentifier = reinterpret_cast<NSData *(*)(NSString *)>(dlsym(RTLD_DEFAULT, "SBSCopyIconImagePNGDataForDisplayIdentifier"));
10580 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10581 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10582 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10584 PulseInterval_ = fast ? 50000 : 500000;
10586 Colon_ = UCLocalize("COLON_DELIMITED");
10587 Elision_ = UCLocalize("ELISION");
10588 Error_ = UCLocalize("ERROR");
10589 Warning_ = UCLocalize("WARNING");
10592 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10594 CGColorSpaceRelease(space_);
10595 CFRelease(Locale_);