1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2013 Jay Freeman (saurik)
5 /* GNU General Public License, Version 3 {{{ */
7 * Cydia is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
12 * Cydia is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Cydia. If not, see <http://www.gnu.org/licenses/>.
22 // XXX: wtf/FastMalloc.h... wtf?
23 #define USE_SYSTEM_MALLOC 1
25 /* #include Directives {{{ */
26 #include "CyteKit/UCPlatform.h"
27 #include "CyteKit/Localize.h"
29 #include <objc/objc.h>
30 #include <objc/runtime.h>
32 #include <CoreGraphics/CoreGraphics.h>
33 #include <Foundation/Foundation.h>
36 #define DEPLOYMENT_TARGET_MACOSX 1
37 #define CF_BUILDING_CF 1
38 #include <CoreFoundation/CFInternal.h>
41 #include <CoreFoundation/CFPriv.h>
42 #include <CoreFoundation/CFUniChar.h>
44 #include <SystemConfiguration/SystemConfiguration.h>
46 #include <UIKit/UIKit.h>
47 #include "iPhonePrivate.h"
49 #include <IOKit/IOKitLib.h>
51 #include <QuartzCore/CALayer.h>
53 #include <WebCore/WebCoreThread.h>
54 #include <WebKit/DOMHTMLIFrameElement.h>
61 #include <ext/stdio_filebuf.h>
65 #include <apt-pkg/acquire.h>
66 #include <apt-pkg/acquire-item.h>
67 #include <apt-pkg/algorithms.h>
68 #include <apt-pkg/cachefile.h>
69 #include <apt-pkg/clean.h>
70 #include <apt-pkg/configuration.h>
71 #include <apt-pkg/debindexfile.h>
72 #include <apt-pkg/debmetaindex.h>
73 #include <apt-pkg/error.h>
74 #include <apt-pkg/init.h>
75 #include <apt-pkg/mmap.h>
76 #include <apt-pkg/pkgrecords.h>
77 #include <apt-pkg/sha1.h>
78 #include <apt-pkg/sourcelist.h>
79 #include <apt-pkg/sptr.h>
80 #include <apt-pkg/strutl.h>
81 #include <apt-pkg/tagfile.h>
83 #include <apr-1/apr_pools.h>
85 #include <sys/types.h>
87 #include <sys/sysctl.h>
88 #include <sys/param.h>
89 #include <sys/mount.h>
90 #include <sys/reboot.h>
97 #include <mach-o/nlist.h>
106 #include <Cytore.hpp>
109 #include <CydiaSubstrate/CydiaSubstrate.h>
110 #include "Menes/Menes.h"
112 #include "CyteKit/IndirectDelegate.h"
113 #include "CyteKit/PerlCompatibleRegEx.hpp"
114 #include "CyteKit/TableViewCell.h"
115 #include "CyteKit/WebScriptObject-Cyte.h"
116 #include "CyteKit/WebViewController.h"
117 #include "CyteKit/WebViewTableViewCell.h"
118 #include "CyteKit/stringWithUTF8Bytes.h"
120 #include "Cydia/MIMEAddress.h"
121 #include "Cydia/LoadingViewController.h"
122 #include "Cydia/ProgressEvent.h"
124 #include "SDURLCache/SDURLCache.h"
131 #define _timestamp ({ \
133 gettimeofday(&tv, NULL); \
134 tv.tv_sec * 1000000 + tv.tv_usec; \
137 typedef std::vector<class ProfileTime *> TimeList;
147 ProfileTime(const char *name) :
151 times_.push_back(this);
154 void AddTime(uint64_t time) {
161 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
173 ProfileTimer(ProfileTime &time) :
180 time_.AddTime(_timestamp - start_);
185 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
187 std::cerr << "========" << std::endl;
190 #define _profile(name) { \
191 static ProfileTime name(#name); \
192 ProfileTimer _ ## name(name);
197 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
198 #define synchronized(lock) \
199 synchronized(static_cast<NSObject *>(lock))
201 extern NSString *Cydia_;
203 #define lprintf(args...) fprintf(stderr, args)
206 #define TraceLogging (1 && !ForRelease)
207 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
208 #define ProfileTimes (0 && !ForRelease)
209 #define ForSaurik (0 && !ForRelease)
210 #define LogBrowser (0 && !ForRelease)
211 #define TrackResize (0 && !ForRelease)
212 #define ManualRefresh (1 && !ForRelease)
213 #define ShowInternals (0 && !ForRelease)
214 #define AlwaysReload (0 && !ForRelease)
215 #define TryIndexedCollation (0 && !ForRelease)
219 #define _trace(args...)
224 #define _profile(name) {
227 #define PrintTimes() do {} while (false)
230 // Hash Functions/Structures {{{
231 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
239 static NSString *Colon_;
241 static NSString *Error_;
242 static NSString *Warning_;
244 static NSString *Cache_;
246 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
248 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
250 static NSString *UniqueIdentifier(UIDevice *device = nil) {
251 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
252 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
254 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
257 static bool IsReachable(const char *name) {
258 SCNetworkReachabilityFlags flags; {
259 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
260 SCNetworkReachabilityGetFlags(reachability, &flags);
261 CFRelease(reachability);
264 // XXX: this elaborate mess is what Apple is using to determine this? :(
265 // XXX: do we care if the user has to intervene? maybe that's ok?
267 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
268 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
269 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
270 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
271 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
272 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
277 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
279 static _finline NSString *CydiaURL(NSString *path) {
281 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
282 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
283 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
284 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
285 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
287 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
290 static void ReapZombie(pid_t pid) {
293 if (waitpid(pid, &status, 0) == -1)
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_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | 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(apr_pool_t *pool) {
550 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
551 memcpy(temp, data_, size_);
556 void set(apr_pool_t *pool, const char *data, size_t size) {
562 data_ = const_cast<char *>(data);
570 _finline void set(apr_pool_t *pool, const char *data) {
571 set(pool, data, data == NULL ? 0 : strlen(data));
574 _finline void set(apr_pool_t *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> Token_;
717 static _H<NSString> UniqueID_;
718 static _H<NSString> UserAgent_;
719 static _H<NSString> Product_;
720 static _H<NSString> Safari_;
722 static CFLocaleRef Locale_;
723 static NSArray *Languages_;
724 static CGColorSpaceRef space_;
726 static NSDictionary *SectionMap_;
727 static NSMutableDictionary *Metadata_;
728 static _transient NSMutableDictionary *Settings_;
729 static _transient NSString *Role_;
730 static _transient NSMutableDictionary *Packages_;
731 static _transient NSMutableDictionary *Values_;
732 static _transient NSMutableDictionary *Sections_;
733 _H<NSMutableDictionary> Sources_;
734 static _transient NSNumber *Version_;
739 static CGFloat ScreenScale_;
740 static NSString *Idiom_;
741 static _H<NSString> Firmware_;
742 static NSString *Major_;
744 static _H<NSMutableDictionary> SessionData_;
745 static _H<NSObject> HostConfig_;
746 static _H<NSMutableSet> BridgedHosts_;
747 static _H<NSMutableSet> TokenHosts_;
748 static _H<NSMutableSet> InsecureHosts_;
749 static _H<NSMutableSet> PipelinedHosts_;
750 static _H<NSMutableSet> CachedURLs_;
752 static NSString *kCydiaProgressEventTypeError = @"Error";
753 static NSString *kCydiaProgressEventTypeInformation = @"Information";
754 static NSString *kCydiaProgressEventTypeStatus = @"Status";
755 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
758 /* Display Helpers {{{ */
759 inline float Interpolate(float begin, float end, float fraction) {
760 return (end - begin) * fraction + begin;
763 static _finline const char *StripVersion_(const char *version) {
764 const char *colon(strchr(version, ':'));
765 return colon == NULL ? version : colon + 1;
768 NSString *LocalizeSection(NSString *section) {
769 static Pcre title_r("^(.*?) \\((.*)\\)$");
770 if (title_r(section)) {
771 NSString *parent(title_r[1]);
772 NSString *child(title_r[2]);
774 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
775 LocalizeSection(parent),
776 LocalizeSection(child)
780 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
783 NSString *Simplify(NSString *title) {
784 const char *data = [title UTF8String];
785 size_t size = [title length];
787 static Pcre square_r("^\\[(.*)\\]$");
788 if (square_r(data, size))
789 return Simplify(square_r[1]);
791 static Pcre paren_r("^\\((.*)\\)$");
792 if (paren_r(data, size))
793 return Simplify(paren_r[1]);
795 static Pcre title_r("^(.*?) \\((.*)\\)$");
796 if (title_r(data, size))
797 return Simplify(title_r[1]);
803 NSString *GetLastUpdate() {
804 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
807 return UCLocalize("NEVER_OR_UNKNOWN");
809 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
810 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
812 CFRelease(formatter);
814 return [(NSString *) formatted autorelease];
817 bool isSectionVisible(NSString *section) {
818 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
819 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
820 return hidden == nil || ![hidden boolValue];
823 static NSObject *CYIOGetValue(const char *path, NSString *property) {
824 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
825 if (entry == MACH_PORT_NULL)
828 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
829 IOObjectRelease(entry);
833 return [(id) value autorelease];
836 static NSString *CYHex(NSData *data, bool reverse = false) {
840 size_t length([data length]);
841 uint8_t bytes[length];
842 [data getBytes:bytes];
844 char string[length * 2 + 1];
845 for (size_t i(0); i != length; ++i)
846 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
848 return [NSString stringWithUTF8String:string];
853 /* Delegate Prototypes {{{ */
856 @class CydiaProgressEvent;
858 @protocol DatabaseDelegate
859 - (void) repairWithSelector:(SEL)selector;
860 - (void) setConfigurationData:(NSString *)data;
861 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
864 @class CYPackageController;
866 @protocol CydiaDelegate
867 - (void) returnToCydia;
869 - (void) retainNetworkActivityIndicator;
870 - (void) releaseNetworkActivityIndicator;
871 - (void) clearPackage:(Package *)package;
872 - (void) installPackage:(Package *)package;
873 - (void) installPackages:(NSArray *)packages;
874 - (void) removePackage:(Package *)package;
875 - (void) beginUpdate;
877 - (void) distUpgrade;
880 - (void) _saveConfig;
882 - (void) addSource:(NSDictionary *)source;
883 - (void) addTrivialSource:(NSString *)href;
884 - (void) showSettings;
885 - (UIProgressHUD *) addProgressHUD;
886 - (void) removeProgressHUD:(UIProgressHUD *)hud;
887 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
888 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
892 /* Status Delegation {{{ */
894 public pkgAcquireStatus
897 _transient NSObject<ProgressDelegate> *delegate_;
907 void setDelegate(NSObject<ProgressDelegate> *delegate) {
908 delegate_ = delegate;
911 NSObject<ProgressDelegate> *getDelegate() const {
915 virtual bool MediaChange(std::string media, std::string drive) {
919 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
923 virtual void Fetch(pkgAcquire::ItemDesc &item) {
924 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
925 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
926 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
929 virtual void Done(pkgAcquire::ItemDesc &item) {
930 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
931 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
932 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
935 virtual void Fail(pkgAcquire::ItemDesc &item) {
937 item.Owner->Status == pkgAcquire::Item::StatIdle ||
938 item.Owner->Status == pkgAcquire::Item::StatDone
942 std::string &error(item.Owner->ErrorText);
946 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
947 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
950 virtual bool Pulse(pkgAcquire *Owner) {
951 bool value = pkgAcquireStatus::Pulse(Owner);
954 double(CurrentBytes + CurrentItems) /
955 double(TotalBytes + TotalItems)
958 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
959 [NSNumber numberWithDouble:percent], @"Percent",
961 [NSNumber numberWithDouble:CurrentBytes], @"Current",
962 [NSNumber numberWithDouble:TotalBytes], @"Total",
963 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
964 nil] waitUntilDone:YES];
966 if (value && ![delegate_ isProgressCancelled])
974 _finline bool WasCancelled() const {
978 virtual void Start() {
979 pkgAcquireStatus::Start();
980 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
983 virtual void Stop() {
984 pkgAcquireStatus::Stop();
985 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
986 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
990 /* Database Interface {{{ */
991 typedef std::map< unsigned long, _H<Source> > SourceMap;
993 @interface Database : NSObject {
1000 pkgDepCache::Policy *policy_;
1001 pkgRecords *records_;
1002 pkgProblemResolver *resolver_;
1003 pkgAcquire *fetcher_;
1005 SPtr<pkgPackageManager> manager_;
1006 pkgSourceList *list_;
1008 SourceMap sourceMap_;
1009 _H<NSMutableArray> sourceList_;
1011 CFMutableArrayRef packages_;
1013 _transient NSObject<DatabaseDelegate> *delegate_;
1014 _transient NSObject<ProgressDelegate> *progress_;
1022 std::map<const char *, _H<NSString> > sections_;
1025 + (Database *) sharedInstance;
1028 - (void) _readCydia:(NSNumber *)fd;
1029 - (void) _readStatus:(NSNumber *)fd;
1030 - (void) _readOutput:(NSNumber *)fd;
1034 - (Package *) packageWithName:(NSString *)name;
1036 - (pkgCacheFile &) cache;
1037 - (pkgDepCache::Policy *) policy;
1038 - (pkgRecords *) records;
1039 - (pkgProblemResolver *) resolver;
1040 - (pkgAcquire &) fetcher;
1041 - (pkgSourceList &) list;
1042 - (NSArray *) packages;
1043 - (NSArray *) sources;
1044 - (Source *) sourceWithKey:(NSString *)key;
1045 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1053 - (void) updateWithStatus:(Status &)status;
1055 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1057 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1058 - (NSObject<ProgressDelegate> *) progressDelegate;
1060 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1062 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1066 /* ProgressEvent Implementation {{{ */
1067 @implementation CydiaProgressEvent
1069 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1070 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1073 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1074 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1075 [event setPackage:package];
1079 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1080 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1082 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1083 NSArray *fields([description componentsSeparatedByString:@" "]);
1084 [event setItem:fields];
1086 if ([fields count] > 3) {
1087 [event setPackage:[fields objectAtIndex:2]];
1088 [event setVersion:[fields objectAtIndex:3]];
1091 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1096 + (NSArray *) _attributeKeys {
1097 return [NSArray arrayWithObjects:
1107 - (NSArray *) attributeKeys {
1108 return [[self class] _attributeKeys];
1111 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1112 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1115 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1116 if ((self = [super init]) != nil) {
1122 - (NSString *) message {
1126 - (NSString *) type {
1130 - (NSArray *) item {
1131 return (id) item_ ?: [NSNull null];
1134 - (void) setItem:(NSArray *)item {
1138 - (NSString *) package {
1139 return (id) package_ ?: [NSNull null];
1142 - (void) setPackage:(NSString *)package {
1146 - (NSString *) url {
1147 return (id) url_ ?: [NSNull null];
1150 - (void) setURL:(NSString *)url {
1154 - (void) setVersion:(NSString *)version {
1158 - (NSString *) version {
1159 return (id) version_ ?: [NSNull null];
1162 - (NSString *) compound:(NSString *)value {
1164 NSString *mode(nil); {
1165 NSString *type([self type]);
1166 if ([type isEqualToString:kCydiaProgressEventTypeError])
1167 mode = UCLocalize("ERROR");
1168 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1169 mode = UCLocalize("WARNING");
1173 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1179 - (NSString *) compoundMessage {
1180 return [self compound:[self message]];
1183 - (NSString *) compoundTitle {
1186 if (package_ == nil)
1188 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1189 title = [package name];
1193 return [self compound:title];
1199 // Cytore Definitions {{{
1200 struct PackageValue :
1203 Cytore::Offset<PackageValue> next_;
1205 uint32_t index_ : 23;
1206 uint32_t subscribed_ : 1;
1223 Cytore::Offset<PackageValue> packages_[1 << 16];
1226 static Cytore::File<MetaValue> MetaFile_;
1228 // Cytore Helper Functions {{{
1229 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1230 SplitHash nhash = { hashlittle(name, length) };
1232 PackageValue *metadata;
1234 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1235 offset: if (offset->IsNull()) {
1236 *offset = MetaFile_.New<PackageValue>(length + 1);
1237 metadata = &MetaFile_.Get(*offset);
1239 if (metadata == NULL) {
1243 metadata = new PackageValue();
1244 memset(metadata, 0, sizeof(*metadata));
1247 memcpy(metadata->name_, name, length + 1);
1248 metadata->nhash_ = nhash.u16[1];
1250 metadata = &MetaFile_.Get(*offset);
1252 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1253 offset = &metadata->next_;
1261 static void PackageImport(const void *key, const void *value, void *context) {
1262 bool &fail(*reinterpret_cast<bool *>(context));
1265 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1266 NSLog(@"failed to import package %@", key);
1270 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1271 NSDictionary *package((NSDictionary *) value);
1273 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1274 if ([subscribed boolValue] && !metadata->subscribed_)
1275 metadata->subscribed_ = true;
1277 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1278 time_t time([date timeIntervalSince1970]);
1279 if (metadata->first_ > time || metadata->first_ == 0)
1280 metadata->first_ = time;
1283 NSDate *date([package objectForKey:@"LastSeen"]);
1284 NSString *version([package objectForKey:@"LastVersion"]);
1286 if (date != nil && version != nil) {
1287 time_t time([date timeIntervalSince1970]);
1288 if (metadata->last_ < time || metadata->last_ == 0)
1289 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1290 size_t length(strlen(buffer));
1291 uint16_t vhash(hashlittle(buffer, length));
1293 size_t capped(std::min<size_t>(8, length));
1294 char *latest(buffer + length - capped);
1296 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1297 metadata->vhash_ = vhash;
1299 metadata->last_ = time;
1305 /* Source Class {{{ */
1306 @interface Source : NSObject {
1308 Database *database_;
1311 CYString depiction_;
1312 CYString description_;
1318 CYString distribution_;
1324 _H<NSString> authority_;
1326 CYString defaultIcon_;
1328 _H<NSMutableDictionary> record_;
1332 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1334 - (NSComparisonResult) compareByName:(Source *)source;
1336 - (NSString *) depictionForPackage:(NSString *)package;
1337 - (NSString *) supportForPackage:(NSString *)package;
1339 - (metaIndex *) metaIndex;
1340 - (NSDictionary *) record;
1343 - (NSString *) rooturi;
1344 - (NSString *) distribution;
1345 - (NSString *) type;
1348 - (NSString *) host;
1350 - (NSString *) name;
1351 - (NSString *) shortDescription;
1352 - (NSString *) label;
1353 - (NSString *) origin;
1354 - (NSString *) version;
1356 - (NSString *) defaultIcon;
1357 - (NSURL *) iconURL;
1361 @implementation Source
1363 + (NSString *) webScriptNameForSelector:(SEL)selector {
1365 else if (selector == @selector(addSection:))
1366 return @"addSection";
1367 else if (selector == @selector(getField:))
1369 else if (selector == @selector(removeSection:))
1370 return @"removeSection";
1371 else if (selector == @selector(remove))
1377 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1378 return [self webScriptNameForSelector:selector] == nil;
1381 + (NSArray *) _attributeKeys {
1382 return [NSArray arrayWithObjects:
1393 @"shortDescription",
1400 - (NSArray *) attributeKeys {
1401 return [[self class] _attributeKeys];
1404 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1405 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1408 - (metaIndex *) metaIndex {
1412 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1413 trusted_ = index->IsTrusted();
1415 uri_.set(pool, index->GetURI());
1416 distribution_.set(pool, index->GetDist());
1417 type_.set(pool, index->GetType());
1419 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1420 if (dindex != NULL) {
1421 base_.set(pool, dindex->MetaIndexURI(""));
1424 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1427 pkgTagFile tags(&fd);
1429 pkgTagSection section;
1436 {"default-icon", &defaultIcon_},
1437 {"depiction", &depiction_},
1438 {"description", &description_},
1440 {"origin", &origin_},
1441 {"support", &support_},
1442 {"version", &version_},
1445 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1446 const char *start, *end;
1448 if (section.Find(names[i].name_, start, end)) {
1449 CYString &value(*names[i].value_);
1450 value.set(pool, start, end - start);
1456 record_ = [Sources_ objectForKey:[self key]];
1458 NSURL *url([NSURL URLWithString:uri_]);
1462 host_ = [host_ lowercaseString];
1467 authority_ = [url path];
1470 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1471 if ((self = [super init]) != nil) {
1472 era_ = [database era];
1473 database_ = database;
1476 [self setMetaIndex:index inPool:pool];
1480 - (NSString *) getField:(NSString *)name {
1481 @synchronized (database_) {
1482 if ([database_ era] != era_ || index_ == NULL)
1485 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1490 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1495 pkgTagFile tags(&fd);
1497 pkgTagSection section;
1500 const char *start, *end;
1501 if (!section.Find([name UTF8String], start, end))
1502 return (NSString *) [NSNull null];
1504 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1507 - (NSComparisonResult) compareByName:(Source *)source {
1508 NSString *lhs = [self name];
1509 NSString *rhs = [source name];
1511 if ([lhs length] != 0 && [rhs length] != 0) {
1512 unichar lhc = [lhs characterAtIndex:0];
1513 unichar rhc = [rhs characterAtIndex:0];
1515 if (isalpha(lhc) && !isalpha(rhc))
1516 return NSOrderedAscending;
1517 else if (!isalpha(lhc) && isalpha(rhc))
1518 return NSOrderedDescending;
1521 return [lhs compare:rhs options:LaxCompareOptions_];
1524 - (NSString *) depictionForPackage:(NSString *)package {
1525 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1528 - (NSString *) supportForPackage:(NSString *)package {
1529 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1532 - (NSArray *) sections {
1533 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1536 - (void) _addSection:(NSString *)section {
1539 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1540 if (![sections containsObject:section]) {
1541 [sections addObject:section];
1545 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1550 - (bool) addSection:(NSString *)section {
1554 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1558 - (void) _removeSection:(NSString *)section {
1562 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1563 if ([sections containsObject:section]) {
1564 [sections removeObject:section];
1569 - (bool) removeSection:(NSString *)section {
1573 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1578 [Sources_ removeObjectForKey:[self key]];
1583 bool value(record_ != nil);
1584 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1588 - (NSDictionary *) record {
1596 - (NSString *) rooturi {
1600 - (NSString *) distribution {
1601 return distribution_;
1604 - (NSString *) type {
1608 - (NSString *) baseuri {
1609 return base_.empty() ? nil : (id) base_;
1612 - (NSString *) iconuri {
1613 if (NSString *base = [self baseuri])
1614 return [base stringByAppendingString:@"CydiaIcon.png"];
1619 - (NSURL *) iconURL {
1620 if (NSString *uri = [self iconuri])
1621 return [NSURL URLWithString:uri];
1625 - (NSString *) key {
1626 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1629 - (NSString *) host {
1633 - (NSString *) name {
1634 return origin_.empty() ? (id) authority_ : origin_;
1637 - (NSString *) shortDescription {
1638 return description_;
1641 - (NSString *) label {
1642 return label_.empty() ? (id) authority_ : label_;
1645 - (NSString *) origin {
1649 - (NSString *) version {
1653 - (NSString *) defaultIcon {
1654 return defaultIcon_;
1659 /* CydiaOperation Class {{{ */
1660 @interface CydiaOperation : NSObject {
1661 _H<NSString> operator_;
1662 _H<NSString> value_;
1665 - (NSString *) operator;
1666 - (NSString *) value;
1670 @implementation CydiaOperation
1672 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1673 if ((self = [super init]) != nil) {
1674 operator_ = [NSString stringWithUTF8String:_operator];
1675 value_ = [NSString stringWithUTF8String:value];
1679 + (NSArray *) _attributeKeys {
1680 return [NSArray arrayWithObjects:
1686 - (NSArray *) attributeKeys {
1687 return [[self class] _attributeKeys];
1690 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1691 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1694 - (NSString *) operator {
1698 - (NSString *) value {
1704 /* CydiaClause Class {{{ */
1705 @interface CydiaClause : NSObject {
1706 _H<NSString> package_;
1707 _H<CydiaOperation> version_;
1710 - (NSString *) package;
1711 - (CydiaOperation *) version;
1715 @implementation CydiaClause
1717 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1718 if ((self = [super init]) != nil) {
1719 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1721 if (const char *version = dep.TargetVer())
1722 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1724 version_ = (id) [NSNull null];
1728 + (NSArray *) _attributeKeys {
1729 return [NSArray arrayWithObjects:
1735 - (NSArray *) attributeKeys {
1736 return [[self class] _attributeKeys];
1739 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1740 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1743 - (NSString *) package {
1747 - (CydiaOperation *) version {
1753 /* CydiaRelation Class {{{ */
1754 @interface CydiaRelation : NSObject {
1755 _H<NSString> relationship_;
1756 _H<NSMutableArray> clauses_;
1759 - (NSString *) relationship;
1760 - (NSArray *) clauses;
1764 @implementation CydiaRelation
1766 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1767 if ((self = [super init]) != nil) {
1768 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1769 clauses_ = [NSMutableArray arrayWithCapacity:8];
1771 pkgCache::DepIterator start;
1772 pkgCache::DepIterator end;
1773 dep.GlobOr(start, end); // ++dep
1776 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1778 // yes, seriously. (wtf?)
1786 + (NSArray *) _attributeKeys {
1787 return [NSArray arrayWithObjects:
1793 - (NSArray *) attributeKeys {
1794 return [[self class] _attributeKeys];
1797 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1798 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1801 - (NSString *) relationship {
1802 return relationship_;
1805 - (NSArray *) clauses {
1809 - (void) addClause:(CydiaClause *)clause {
1810 [clauses_ addObject:clause];
1815 /* Package Class {{{ */
1816 struct ParsedPackage {
1820 CYString architecture_;
1823 CYString depiction_;
1830 @interface Package : NSObject {
1833 uint32_t essential_ : 1;
1834 uint32_t obsolete_ : 1;
1835 uint32_t ignored_ : 1;
1836 uint32_t pooled_ : 1;
1842 _transient Database *database_;
1844 pkgCache::VerIterator version_;
1845 pkgCache::PkgIterator iterator_;
1846 pkgCache::VerFileIterator file_;
1852 CYString installed_;
1854 const char *section_;
1855 _transient NSString *section$_;
1859 PackageValue *metadata_;
1860 ParsedPackage *parsed_;
1862 _H<NSMutableArray> tags_;
1865 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1866 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1868 - (pkgCache::PkgIterator) iterator;
1871 - (NSString *) section;
1872 - (NSString *) simpleSection;
1874 - (NSString *) longSection;
1875 - (NSString *) shortSection;
1879 - (MIMEAddress *) maintainer;
1881 - (NSString *) longDescription;
1882 - (NSString *) shortDescription;
1885 - (PackageValue *) metadata;
1888 - (bool) subscribed;
1889 - (bool) setSubscribed:(bool)subscribed;
1893 - (NSString *) latest;
1894 - (NSString *) installed;
1895 - (BOOL) uninstalled;
1898 - (BOOL) upgradableAndEssential:(BOOL)essential;
1901 - (BOOL) unfiltered;
1905 - (BOOL) halfConfigured;
1906 - (BOOL) halfInstalled;
1908 - (NSString *) mode;
1911 - (NSString *) name;
1913 - (NSString *) homepage;
1914 - (NSString *) depiction;
1915 - (MIMEAddress *) author;
1917 - (NSString *) support;
1919 - (NSArray *) files;
1920 - (NSArray *) warnings;
1921 - (NSArray *) applications;
1923 - (Source *) source;
1926 - (BOOL) matches:(NSArray *)query;
1928 - (bool) hasSupportingRole;
1929 - (BOOL) hasTag:(NSString *)tag;
1930 - (NSString *) primaryPurpose;
1931 - (NSArray *) purposes;
1932 - (bool) isCommercial;
1934 - (void) setIndex:(size_t)index;
1936 - (CYString &) cyname;
1938 - (uint32_t) compareBySection:(NSArray *)sections;
1943 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1944 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1945 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1946 - (bool) isVisibleInSection:(NSString *)section;
1947 - (bool) isVisibleInSource:(Source *)source;
1951 uint32_t PackageChangesRadix(Package *self, void *) {
1956 uint32_t timestamp : 30;
1957 uint32_t ignored : 1;
1958 uint32_t upgradable : 1;
1962 bool upgradable([self upgradableAndEssential:YES]);
1963 value.bits.upgradable = upgradable ? 1 : 0;
1966 value.bits.timestamp = 0;
1967 value.bits.ignored = [self ignored] ? 0 : 1;
1968 value.bits.upgradable = 1;
1970 value.bits.timestamp = [self seen] >> 2;
1971 value.bits.ignored = 0;
1972 value.bits.upgradable = 0;
1975 return _not(uint32_t) - value.key;
1978 uint32_t PackagePrefixRadix(Package *self, void *context) {
1979 size_t offset(reinterpret_cast<size_t>(context));
1980 CYString &name([self cyname]);
1982 size_t size(name.size());
1985 char *text(name.data());
1988 if (!isdigit(text[0]))
1992 while (size != digits && isdigit(text[digits]))
2000 if (offset == 0 && zeros != 0) {
2001 memset(data, '0', zeros);
2002 memcpy(data + zeros, text, 4 - zeros);
2004 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2005 if (size <= offset - zeros)
2008 text += offset - zeros;
2009 size -= offset - zeros;
2012 memcpy(data, text, 4);
2014 memcpy(data, text, size);
2015 memset(data + size, 0, 4 - size);
2018 for (size_t i(0); i != 4; ++i)
2019 if (isalpha(data[i]))
2027 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2029 /* XXX: ntohl may be more honest */
2030 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2033 CYString &(*PackageName)(Package *self, SEL sel);
2035 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2036 _profile(PackageNameCompare)
2037 CYString &lhi(PackageName(lhs, @selector(cyname)));
2038 CYString &rhi(PackageName(rhs, @selector(cyname)));
2039 CFStringRef lhn(lhi), rhn(rhi);
2042 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2043 else if (rhn == NULL)
2044 return NSOrderedDescending;
2046 _profile(PackageNameCompare$NumbersLast)
2047 if (!lhi.empty() && !rhi.empty()) {
2048 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2049 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2050 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2051 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2052 return lha ? NSOrderedAscending : NSOrderedDescending;
2056 CFIndex length = CFStringGetLength(lhn);
2058 _profile(PackageNameCompare$Compare)
2059 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2064 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2065 return PackageNameCompare(*lhs, *rhs, context);
2068 struct PackageNameOrdering :
2069 std::binary_function<Package *, Package *, bool>
2071 _finline bool operator ()(Package *lhs, Package *rhs) const {
2072 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2076 @implementation Package
2078 - (NSString *) description {
2079 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2084 apr_pool_destroy(pool_);
2085 if (parsed_ != NULL)
2090 + (NSString *) webScriptNameForSelector:(SEL)selector {
2092 else if (selector == @selector(clear))
2094 else if (selector == @selector(getField:))
2096 else if (selector == @selector(getRecord))
2097 return @"getRecord";
2098 else if (selector == @selector(hasTag:))
2100 else if (selector == @selector(install))
2102 else if (selector == @selector(remove))
2108 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2109 return [self webScriptNameForSelector:selector] == nil;
2112 + (NSArray *) _attributeKeys {
2113 return [NSArray arrayWithObjects:
2134 @"shortDescription",
2146 - (NSArray *) attributeKeys {
2147 return [[self class] _attributeKeys];
2150 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2151 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2154 - (NSArray *) relations {
2155 @synchronized (database_) {
2156 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2157 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2158 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2162 - (NSString *) architecture {
2164 @synchronized (database_) {
2165 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2168 - (NSString *) getField:(NSString *)name {
2169 @synchronized (database_) {
2170 if ([database_ era] != era_ || file_.end())
2173 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2175 const char *start, *end;
2176 if (!parser.Find([name UTF8String], start, end))
2177 return (NSString *) [NSNull null];
2179 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2182 - (NSString *) getRecord {
2183 @synchronized (database_) {
2184 if ([database_ era] != era_ || file_.end())
2187 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2189 const char *start, *end;
2190 parser.GetRec(start, end);
2192 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2196 if (parsed_ != NULL)
2198 @synchronized (database_) {
2199 if ([database_ era] != era_ || file_.end())
2202 ParsedPackage *parsed(new ParsedPackage);
2205 _profile(Package$parse)
2206 pkgRecords::Parser *parser;
2208 _profile(Package$parse$Lookup)
2209 parser = &[database_ records]->Lookup(file_);
2215 _profile(Package$parse$Find)
2220 {"architecture", &parsed->architecture_},
2221 {"icon", &parsed->icon_},
2222 {"depiction", &parsed->depiction_},
2223 {"homepage", &parsed->homepage_},
2224 {"website", &website},
2226 {"support", &parsed->support_},
2227 {"author", &parsed->author_},
2228 {"md5sum", &parsed->md5sum_},
2231 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2232 const char *start, *end;
2234 if (parser->Find(names[i].name_, start, end)) {
2235 CYString &value(*names[i].value_);
2236 _profile(Package$parse$Value)
2237 value.set(pool_, start, end - start);
2243 _profile(Package$parse$Tagline)
2244 const char *start, *end;
2245 if (parser->ShortDesc(start, end)) {
2246 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2249 while (stop != start && stop[-1] == '\r')
2251 parsed->tagline_.set(pool_, start, stop - start);
2255 _profile(Package$parse$Retain)
2256 if (parsed->homepage_.empty())
2257 parsed->homepage_ = website;
2258 if (parsed->homepage_ == parsed->depiction_)
2259 parsed->homepage_.clear();
2260 if (parsed->support_.empty())
2261 parsed->support_ = bugs;
2266 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2267 if ((self = [super init]) != nil) {
2268 _profile(Package$initWithVersion)
2270 apr_pool_create(&pool_, NULL);
2276 database_ = database;
2277 era_ = [database era];
2281 pkgCache::PkgIterator iterator(version.ParentPkg());
2282 iterator_ = iterator;
2284 _profile(Package$initWithVersion$Version)
2285 if (!version_.end())
2286 file_ = version_.FileList();
2288 pkgCache &cache([database_ cache]);
2289 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2293 _profile(Package$initWithVersion$Cache)
2294 name_.set(NULL, iterator.Display());
2296 latest_.set(NULL, StripVersion_(version_.VerStr()));
2298 pkgCache::VerIterator current(iterator.CurrentVer());
2300 installed_.set(NULL, StripVersion_(current.VerStr()));
2303 _profile(Package$initWithVersion$Tags)
2304 pkgCache::TagIterator tag(iterator.TagList());
2306 tags_ = [NSMutableArray arrayWithCapacity:8];
2308 goto tag; for (; !tag.end(); ++tag) tag: {
2309 const char *name(tag.Name());
2310 NSString *string((NSString *) CYStringCreate(name));
2314 [tags_ addObject:[string autorelease]];
2316 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2317 if (strcmp(name + 6, "enduser") == 0)
2319 else if (strcmp(name + 6, "hacker") == 0)
2321 else if (strcmp(name + 6, "developer") == 0)
2323 else if (strcmp(name + 6, "cydia") == 0)
2329 if (strncmp(name, "cydia::", 7) == 0) {
2330 if (strcmp(name + 7, "essential") == 0)
2332 else if (strcmp(name + 7, "obsolete") == 0)
2339 _profile(Package$initWithVersion$Metadata)
2340 const char *mixed(iterator.Name());
2341 size_t size(strlen(mixed));
2342 char lower[size + 1];
2344 for (size_t i(0); i != size; ++i)
2345 lower[i] = mixed[i] | 0x20;
2348 PackageValue *metadata(PackageFind(lower, size));
2349 metadata_ = metadata;
2351 id_.set(NULL, metadata->name_, size);
2353 const char *latest(version_.VerStr());
2354 size_t length(strlen(latest));
2356 uint16_t vhash(hashlittle(latest, length));
2358 size_t capped(std::min<size_t>(8, length));
2359 latest = latest + length - capped;
2361 if (metadata->first_ == 0)
2362 metadata->first_ = now_;
2364 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2365 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2366 metadata->vhash_ = vhash;
2367 metadata->last_ = now_;
2368 } else if (metadata->last_ == 0)
2369 metadata->last_ = metadata->first_;
2372 _profile(Package$initWithVersion$Section)
2373 section_ = version_.Section();
2376 _profile(Package$initWithVersion$Flags)
2377 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2378 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2383 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2384 pkgCache::VerIterator version;
2386 _profile(Package$packageWithIterator$GetCandidateVer)
2387 version = [database policy]->GetCandidateVer(iterator);
2395 _profile(Package$packageWithIterator$Allocate)
2396 package = [Package allocWithZone:zone];
2399 _profile(Package$packageWithIterator$Initialize)
2401 initWithVersion:version
2408 _profile(Package$packageWithIterator$Autorelease)
2409 package = [package autorelease];
2415 - (pkgCache::PkgIterator) iterator {
2419 - (NSString *) section {
2420 if (section$_ == nil) {
2421 if (section_ == NULL)
2424 _profile(Package$section$mappedSectionForPointer)
2425 section$_ = [database_ mappedSectionForPointer:section_];
2430 - (NSString *) simpleSection {
2431 if (NSString *section = [self section])
2432 return Simplify(section);
2437 - (NSString *) longSection {
2438 return LocalizeSection([self section]);
2441 - (NSString *) shortSection {
2442 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2445 - (NSString *) uri {
2448 pkgIndexFile *index;
2449 pkgCache::PkgFileIterator file(file_.File());
2450 if (![database_ list].FindIndex(file, index))
2452 return [NSString stringWithUTF8String:iterator_->Path];
2453 //return [NSString stringWithUTF8String:file.Site()];
2454 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2458 - (MIMEAddress *) maintainer {
2459 @synchronized (database_) {
2460 if ([database_ era] != era_ || file_.end())
2463 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2464 const std::string &maintainer(parser->Maintainer());
2465 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2468 - (NSString *) md5sum {
2469 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2473 @synchronized (database_) {
2474 if ([database_ era] != era_ || version_.end())
2477 return version_->InstalledSize;
2480 - (NSString *) longDescription {
2481 @synchronized (database_) {
2482 if ([database_ era] != era_ || file_.end())
2485 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2486 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2488 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2489 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2490 if ([lines count] < 2)
2493 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2494 for (size_t i(1), e([lines count]); i != e; ++i) {
2495 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2496 [trimmed addObject:trim];
2499 return [trimmed componentsJoinedByString:@"\n"];
2502 - (NSString *) shortDescription {
2503 if (parsed_ != NULL)
2504 return static_cast<NSString *>(parsed_->tagline_);
2506 @synchronized (database_) {
2507 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2509 const char *start, *end;
2510 if (!parser.ShortDesc(start, end))
2513 if (end - start > 200)
2517 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2520 while (end != start && end[-1] == '\r')
2524 return [(id) CYStringCreate(start, end - start) autorelease];
2528 _profile(Package$index)
2529 CFStringRef name((CFStringRef) [self name]);
2530 if (CFStringGetLength(name) == 0)
2532 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2533 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2535 return toupper(character);
2539 - (PackageValue *) metadata {
2544 PackageValue *metadata([self metadata]);
2545 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2548 - (bool) subscribed {
2549 return [self metadata]->subscribed_;
2552 - (bool) setSubscribed:(bool)subscribed {
2553 PackageValue *metadata([self metadata]);
2554 if (metadata->subscribed_ == subscribed)
2556 metadata->subscribed_ = subscribed;
2564 - (NSString *) latest {
2568 - (NSString *) installed {
2572 - (BOOL) uninstalled {
2573 return installed_.empty();
2577 return !version_.end();
2580 - (BOOL) upgradableAndEssential:(BOOL)essential {
2581 _profile(Package$upgradableAndEssential)
2582 pkgCache::VerIterator current(iterator_.CurrentVer());
2584 return essential && essential_;
2586 return !version_.end() && version_ != current;
2590 - (BOOL) essential {
2595 return [database_ cache][iterator_].InstBroken();
2598 - (BOOL) unfiltered {
2599 _profile(Package$unfiltered$obsolete)
2600 if (_unlikely(obsolete_))
2604 _profile(Package$unfiltered$hasSupportingRole)
2605 if (_unlikely(![self hasSupportingRole]))
2613 if (![self unfiltered])
2618 _profile(Package$visible$section)
2619 section = [self section];
2622 _profile(Package$visible$isSectionVisible)
2623 if (!isSectionVisible(section))
2631 unsigned char current(iterator_->CurrentState);
2632 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2635 - (BOOL) halfConfigured {
2636 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2639 - (BOOL) halfInstalled {
2640 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2644 @synchronized (database_) {
2645 if ([database_ era] != era_ || iterator_.end())
2648 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2649 return state.Mode != pkgDepCache::ModeKeep;
2652 - (NSString *) mode {
2653 @synchronized (database_) {
2654 if ([database_ era] != era_ || iterator_.end())
2657 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2659 switch (state.Mode) {
2660 case pkgDepCache::ModeDelete:
2661 if ((state.iFlags & pkgDepCache::Purge) != 0)
2665 case pkgDepCache::ModeKeep:
2666 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2667 return @"REINSTALL";
2668 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2672 case pkgDepCache::ModeInstall:
2673 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2674 return @"REINSTALL";
2675 else*/ switch (state.Status) {
2677 return @"DOWNGRADE";
2683 return @"NEW_INSTALL";
2694 - (NSString *) name {
2695 return name_.empty() ? id_ : name_;
2698 - (UIImage *) icon {
2699 NSString *section = [self simpleSection];
2702 if (parsed_ != NULL)
2703 if (NSString *href = parsed_->icon_)
2704 if ([href hasPrefix:@"file:///"])
2705 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2706 if (icon == nil) if (section != nil)
2707 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2708 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2709 if ([dicon hasPrefix:@"file:///"])
2710 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2712 icon = [UIImage applicationImageNamed:@"unknown.png"];
2716 - (NSString *) homepage {
2717 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2720 - (NSString *) depiction {
2721 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2724 - (MIMEAddress *) author {
2725 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2728 - (NSString *) support {
2729 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
2732 - (NSArray *) files {
2733 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2734 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2737 fin.open([path UTF8String]);
2742 while (std::getline(fin, line))
2743 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2748 - (NSString *) state {
2749 @synchronized (database_) {
2750 if ([database_ era] != era_ || file_.end())
2753 switch (iterator_->CurrentState) {
2754 case pkgCache::State::NotInstalled:
2755 return @"NotInstalled";
2756 case pkgCache::State::UnPacked:
2758 case pkgCache::State::HalfConfigured:
2759 return @"HalfConfigured";
2760 case pkgCache::State::HalfInstalled:
2761 return @"HalfInstalled";
2762 case pkgCache::State::ConfigFiles:
2763 return @"ConfigFiles";
2764 case pkgCache::State::Installed:
2765 return @"Installed";
2766 case pkgCache::State::TriggersAwaited:
2767 return @"TriggersAwaited";
2768 case pkgCache::State::TriggersPending:
2769 return @"TriggersPending";
2772 return (NSString *) [NSNull null];
2775 - (NSString *) selection {
2776 @synchronized (database_) {
2777 if ([database_ era] != era_ || file_.end())
2780 switch (iterator_->SelectedState) {
2781 case pkgCache::State::Unknown:
2783 case pkgCache::State::Install:
2785 case pkgCache::State::Hold:
2787 case pkgCache::State::DeInstall:
2788 return @"DeInstall";
2789 case pkgCache::State::Purge:
2793 return (NSString *) [NSNull null];
2796 - (NSArray *) warnings {
2797 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2798 const char *name(iterator_.Name());
2800 size_t length(strlen(name));
2801 if (length < 2) invalid:
2802 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2803 else for (size_t i(0); i != length; ++i)
2805 /* XXX: technically this is not allowed */
2806 (name[i] < 'A' || name[i] > 'Z') &&
2807 (name[i] < 'a' || name[i] > 'z') &&
2808 (name[i] < '0' || name[i] > '9') &&
2809 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2812 if (strcmp(name, "cydia") != 0) {
2815 bool _private = false;
2818 bool repository = [[self section] isEqualToString:@"Repositories"];
2820 if (NSArray *files = [self files])
2821 for (NSString *file in files)
2822 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2824 else if (!user && [file isEqualToString:@"/User"])
2826 else if (!_private && [file isEqualToString:@"/private"])
2828 else if (!stash && [file isEqualToString:@"/var/stash"])
2831 /* XXX: this is not sensitive enough. only some folders are valid. */
2832 if (cydia && !repository)
2833 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2835 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2837 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2839 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2842 return [warnings count] == 0 ? nil : warnings;
2845 - (NSArray *) applications {
2846 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2848 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2850 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2851 if (NSArray *files = [self files])
2852 for (NSString *file in files)
2853 if (application_r(file)) {
2854 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2855 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2856 if ([id isEqualToString:me])
2859 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2861 display = application_r[1];
2863 NSString *bundle([file stringByDeletingLastPathComponent]);
2864 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2865 // XXX: maybe this should check if this is really a string, not just for length
2866 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
2868 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2870 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2871 [applications addObject:application];
2873 [application addObject:id];
2874 [application addObject:display];
2875 [application addObject:url];
2878 return [applications count] == 0 ? nil : applications;
2881 - (Source *) source {
2882 if (source_ == nil) {
2883 @synchronized (database_) {
2884 if ([database_ era] != era_ || file_.end())
2885 source_ = (Source *) [NSNull null];
2887 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2891 return source_ == (Source *) [NSNull null] ? nil : source_;
2898 - (BOOL) matches:(NSArray *)query {
2899 if (query == nil || [query count] == 0)
2908 string = [self name];
2909 length = [string length];
2911 for (NSString *term in query) {
2912 range = [string rangeOfString:term options:MatchCompareOptions_];
2913 if (range.location != NSNotFound)
2914 rank_ -= 6 * 1000000 / length;
2919 length = [string length];
2921 for (NSString *term in query) {
2922 range = [string rangeOfString:term options:MatchCompareOptions_];
2923 if (range.location != NSNotFound)
2924 rank_ -= 6 * 1000000 / length;
2928 string = [self shortDescription];
2929 length = [string length];
2930 NSUInteger stop(std::min<NSUInteger>(length, 200));
2932 for (NSString *term in query) {
2933 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2934 if (range.location != NSNotFound)
2935 rank_ -= 2 * 100000;
2941 - (bool) hasSupportingRole {
2946 if ([Role_ isEqualToString:@"User"])
2950 if ([Role_ isEqualToString:@"Hacker"])
2954 if ([Role_ isEqualToString:@"Developer"])
2959 - (NSArray *) tags {
2963 - (BOOL) hasTag:(NSString *)tag {
2964 return tags_ == nil ? NO : [tags_ containsObject:tag];
2967 - (NSString *) primaryPurpose {
2968 for (NSString *tag in (NSArray *) tags_)
2969 if ([tag hasPrefix:@"purpose::"])
2970 return [tag substringFromIndex:9];
2974 - (NSArray *) purposes {
2975 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2976 for (NSString *tag in (NSArray *) tags_)
2977 if ([tag hasPrefix:@"purpose::"])
2978 [purposes addObject:[tag substringFromIndex:9]];
2979 return [purposes count] == 0 ? nil : purposes;
2982 - (bool) isCommercial {
2983 return [self hasTag:@"cydia::commercial"];
2986 - (void) setIndex:(size_t)index {
2987 if (metadata_->index_ != index)
2988 metadata_->index_ = index;
2991 - (CYString &) cyname {
2992 return name_.empty() ? id_ : name_;
2995 - (uint32_t) compareBySection:(NSArray *)sections {
2996 NSString *section([self section]);
2997 for (size_t i(0), e([sections count]); i != e; ++i) {
2998 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3002 return _not(uint32_t);
3006 @synchronized (database_) {
3007 pkgProblemResolver *resolver = [database_ resolver];
3008 resolver->Clear(iterator_);
3010 pkgCacheFile &cache([database_ cache]);
3011 cache->SetReInstall(iterator_, false);
3012 cache->MarkKeep(iterator_, false);
3016 @synchronized (database_) {
3017 pkgProblemResolver *resolver = [database_ resolver];
3018 resolver->Clear(iterator_);
3019 resolver->Protect(iterator_);
3021 pkgCacheFile &cache([database_ cache]);
3022 cache->SetReInstall(iterator_, false);
3023 cache->MarkInstall(iterator_, false);
3025 pkgDepCache::StateCache &state((*cache)[iterator_]);
3026 if (!state.Install())
3027 cache->SetReInstall(iterator_, true);
3031 @synchronized (database_) {
3032 pkgProblemResolver *resolver = [database_ resolver];
3033 resolver->Clear(iterator_);
3034 resolver->Remove(iterator_);
3035 resolver->Protect(iterator_);
3037 pkgCacheFile &cache([database_ cache]);
3038 cache->SetReInstall(iterator_, false);
3039 cache->MarkDelete(iterator_, true);
3042 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3043 _profile(Package$isUnfilteredAndSearchedForBy)
3046 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3047 value &= [self unfiltered];
3050 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3051 value &= [self matches:query];
3058 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3059 if ([search length] == 0)
3062 _profile(Package$isUnfilteredAndSelectedForBy)
3065 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3066 value &= [self unfiltered];
3069 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3070 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3077 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3078 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3081 - (bool) isVisibleInSection:(NSString *)name {
3082 NSString *section([self section]);
3086 section == nil && [name length] == 0 ||
3087 [name isEqualToString:section]
3088 ) && [self visible];
3091 - (bool) isVisibleInSource:(Source *)source {
3092 return [self source] == source && [self visible];
3097 /* Section Class {{{ */
3098 @interface Section : NSObject {
3103 _H<NSString> localized_;
3106 - (NSComparisonResult) compareByLocalized:(Section *)section;
3107 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3108 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3109 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3110 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3111 - (NSString *) name;
3118 - (void) addToCount;
3120 - (void) setCount:(size_t)count;
3121 - (NSString *) localized;
3125 @implementation Section
3127 - (NSComparisonResult) compareByLocalized:(Section *)section {
3128 NSString *lhs(localized_);
3129 NSString *rhs([section localized]);
3131 /*if ([lhs length] != 0 && [rhs length] != 0) {
3132 unichar lhc = [lhs characterAtIndex:0];
3133 unichar rhc = [rhs characterAtIndex:0];
3135 if (isalpha(lhc) && !isalpha(rhc))
3136 return NSOrderedAscending;
3137 else if (!isalpha(lhc) && isalpha(rhc))
3138 return NSOrderedDescending;
3141 return [lhs compare:rhs options:LaxCompareOptions_];
3144 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3145 if ((self = [self initWithName:name localize:NO]) != nil) {
3146 if (localized != nil)
3147 localized_ = localized;
3151 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3152 return [self initWithName:name row:0 localize:localize];
3155 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3156 if ((self = [super init]) != nil) {
3161 localized_ = LocalizeSection(name_);
3165 /* XXX: localize the index thingees */
3166 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3167 if ((self = [super init]) != nil) {
3168 name_ = [NSString stringWithCharacters:&index length:1];
3174 - (NSString *) name {
3194 - (void) addToCount {
3198 - (void) setCount:(size_t)count {
3202 - (NSString *) localized {
3209 class CydiaLogCleaner :
3210 public pkgArchiveCleaner
3213 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3218 /* Database Implementation {{{ */
3219 @implementation Database
3221 + (Database *) sharedInstance {
3222 static _H<Database> instance;
3223 if (instance == nil)
3224 instance = [[[Database alloc] init] autorelease];
3232 - (void) releasePackages {
3233 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3234 CFArrayRemoveAllValues(packages_);
3238 // XXX: actually implement this thing
3240 [self releasePackages];
3241 apr_pool_destroy(pool_);
3242 NSRecycleZone(zone_);
3246 - (void) _readCydia:(NSNumber *)fd {
3247 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3248 std::istream is(&ib);
3251 static Pcre finish_r("^finish:([^:]*)$");
3253 while (std::getline(is, line)) {
3254 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3256 const char *data(line.c_str());
3257 size_t size = line.size();
3258 lprintf("C:%s\n", data);
3260 if (finish_r(data, size)) {
3261 NSString *finish = finish_r[1];
3262 int index = [Finishes_ indexOfObject:finish];
3263 if (index != INT_MAX && index > Finish_)
3273 - (void) _readStatus:(NSNumber *)fd {
3274 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3275 std::istream is(&ib);
3278 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3279 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3281 while (std::getline(is, line)) {
3282 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3284 const char *data(line.c_str());
3285 size_t size(line.size());
3286 lprintf("S:%s\n", data);
3288 if (conffile_r(data, size)) {
3289 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3290 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3291 } else if (strncmp(data, "status: ", 8) == 0) {
3292 // status: <package>: {unpacked,half-configured,installed}
3293 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3294 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3295 } else if (strncmp(data, "processing: ", 12) == 0) {
3296 // processing: configure: config-test
3297 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3298 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3299 } else if (pmstatus_r(data, size)) {
3300 std::string type([pmstatus_r[1] UTF8String]);
3302 NSString *package = pmstatus_r[2];
3303 if ([package isEqualToString:@"dpkg-exec"])
3306 float percent([pmstatus_r[3] floatValue]);
3307 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3309 NSString *string = pmstatus_r[4];
3311 if (type == "pmerror") {
3312 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3313 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3314 } else if (type == "pmstatus") {
3315 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3316 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3317 } else if (type == "pmconffile")
3318 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3320 lprintf("E:unknown pmstatus\n");
3322 lprintf("E:unknown status\n");
3330 - (void) _readOutput:(NSNumber *)fd {
3331 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3332 std::istream is(&ib);
3335 while (std::getline(is, line)) {
3336 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3338 lprintf("O:%s\n", line.c_str());
3340 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3341 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3353 - (Package *) packageWithName:(NSString *)name {
3356 @synchronized (self) {
3357 if (static_cast<pkgDepCache *>(cache_) == NULL)
3359 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3360 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3364 if ((self = [super init]) != nil) {
3371 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3372 apr_pool_create(&pool_, NULL);
3374 size_t capacity(MetaFile_->active_);
3380 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3381 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3385 _assert(pipe(fds) != -1);
3388 _config->Set("APT::Keep-Fds::", cydiafd_);
3389 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3392 detachNewThreadSelector:@selector(_readCydia:)
3394 withObject:[NSNumber numberWithInt:fds[0]]
3397 _assert(pipe(fds) != -1);
3401 detachNewThreadSelector:@selector(_readStatus:)
3403 withObject:[NSNumber numberWithInt:fds[0]]
3406 _assert(pipe(fds) != -1);
3407 _assert(dup2(fds[0], 0) != -1);
3408 _assert(close(fds[0]) != -1);
3410 input_ = fdopen(fds[1], "a");
3412 _assert(pipe(fds) != -1);
3413 _assert(dup2(fds[1], 1) != -1);
3414 _assert(close(fds[1]) != -1);
3417 detachNewThreadSelector:@selector(_readOutput:)
3419 withObject:[NSNumber numberWithInt:fds[0]]
3424 - (pkgCacheFile &) cache {
3428 - (pkgDepCache::Policy *) policy {
3432 - (pkgRecords *) records {
3436 - (pkgProblemResolver *) resolver {
3440 - (pkgAcquire &) fetcher {
3444 - (pkgSourceList &) list {
3448 - (NSArray *) packages {
3449 return (NSArray *) packages_;
3452 - (NSArray *) sources {
3456 - (Source *) sourceWithKey:(NSString *)key {
3457 for (Source *source in [self sources]) {
3458 if ([[source key] isEqualToString:key])
3463 - (bool) popErrorWithTitle:(NSString *)title {
3466 while (!_error->empty()) {
3468 bool warning(!_error->PopMessage(error));
3473 size_t size(error.size());
3474 if (size == 0 || error[size - 1] != '\n')
3476 error.resize(size - 1);
3479 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3481 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3482 if (warning && no_pubkey(error.c_str()))
3485 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3491 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3492 return [self popErrorWithTitle:title] || !success;
3495 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3496 @synchronized (self) {
3499 [self releasePackages];
3502 [sourceList_ removeAllObjects];
3522 apr_pool_clear(pool_);
3524 NSRecycleZone(zone_);
3525 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3527 int chk(creat("/tmp/cydia.chk", 0644));
3531 if (invocation != nil)
3532 [invocation invoke];
3534 NSString *title(UCLocalize("DATABASE"));
3536 list_ = new pkgSourceList();
3537 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3540 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3541 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3542 [sourceList_ addObject:object];
3546 OpProgress progress;
3548 if (!cache_.Open(progress, true)) {
3549 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3550 while (!_error->empty()) {
3552 bool warning(!_error->PopMessage(error));
3554 lprintf("cache_.Open():[%s]\n", error.c_str());
3556 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3560 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3561 repair = @selector(configure);
3562 //else if (error == "The package lists or status file could not be parsed or opened.")
3563 // repair = @selector(update);
3564 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3565 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3566 // else if (error == "Malformed Status line")
3567 // else if (error == "The list of sources could not be read.")
3569 if (repair != NULL) {
3571 [delegate_ repairWithSelector:repair];
3580 unlink("/tmp/cydia.chk");
3582 now_ = [[NSDate date] timeIntervalSince1970];
3584 policy_ = new pkgDepCache::Policy();
3585 records_ = new pkgRecords(cache_);
3586 resolver_ = new pkgProblemResolver(cache_);
3587 fetcher_ = new pkgAcquire(&status_);
3590 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3591 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3595 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3598 if (cache_->BrokenCount() != 0) {
3599 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3602 if (cache_->BrokenCount() != 0) {
3603 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3607 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3611 for (Source *object in (id) sourceList_) {
3612 metaIndex *source([object metaIndex]);
3613 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3614 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3615 // XXX: this could be more intelligent
3616 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3617 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3619 sourceMap_[cached->ID] = object;
3624 /*std::vector<Package *> packages;
3625 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3630 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3631 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3632 //packages.push_back(package);
3633 CFArrayAppendValue(packages_, CFRetain(package));
3637 /*if (packages.empty())
3638 packages_ = [[NSArray alloc] init];
3640 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3643 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3644 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3645 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3653 /*if (!packages.empty())
3654 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3655 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3657 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3659 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3661 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3665 size_t count(CFArrayGetCount(packages_));
3666 MetaFile_->active_ = count;
3668 for (size_t index(0); index != count; ++index)
3669 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3676 @synchronized (self) {
3678 resolver_ = new pkgProblemResolver(cache_);
3680 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3681 if (!cache_[iterator].Keep())
3682 cache_->MarkKeep(iterator, false);
3683 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3684 cache_->SetReInstall(iterator, false);
3687 - (void) configure {
3688 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3690 system([dpkg UTF8String]);
3695 @synchronized (self) {
3696 // XXX: I don't remember this condition
3701 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3703 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3705 if ([self popErrorWithTitle:title])
3709 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3711 CydiaLogCleaner cleaner;
3712 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3719 fetcher_->Shutdown();
3721 pkgRecords records(cache_);
3723 lock_ = new FileFd();
3724 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3726 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3728 if ([self popErrorWithTitle:title])
3732 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3735 manager_ = (_system->CreatePM(cache_));
3736 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3743 bool substrate(RestartSubstrate_);
3744 RestartSubstrate_ = false;
3746 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3748 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3750 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3752 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3753 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3756 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3758 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3760 [self popErrorWithTitle:title];
3764 bool failed = false;
3765 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3766 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3768 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3771 std::string uri = (*item)->DescURI();
3772 std::string error = (*item)->ErrorText;
3774 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3777 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3778 [delegate_ addProgressEventOnMainThread:event forTask:title];
3781 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3789 RestartSubstrate_ = true;
3792 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3793 if ([self popErrorWithTitle:title])
3796 if (result == pkgPackageManager::Failed) {
3801 if (result != pkgPackageManager::Completed) {
3806 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3808 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3810 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3811 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3814 if (![before isEqualToArray:after])
3819 NSString *title(UCLocalize("UPGRADE"));
3820 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3826 [self updateWithStatus:status_];
3829 - (void) updateWithStatus:(Status &)status {
3830 NSString *title(UCLocalize("REFRESHING_DATA"));
3833 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3837 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3838 if ([self popErrorWithTitle:title])
3841 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3843 bool success(ListUpdate(status, list, PulseInterval_));
3844 if (status.WasCancelled())
3847 [self popErrorWithTitle:title forOperation:success];
3848 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3852 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3855 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3856 delegate_ = delegate;
3859 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3860 progress_ = delegate;
3861 status_.setDelegate(delegate);
3864 - (NSObject<ProgressDelegate> *) progressDelegate {
3868 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3869 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3870 return i == sourceMap_.end() ? nil : i->second;
3873 - (NSString *) mappedSectionForPointer:(const char *)section {
3874 _H<NSString> *mapped;
3876 _profile(Database$mappedSectionForPointer$Cache)
3877 mapped = §ions_[section];
3880 if (*mapped == NULL) {
3881 size_t length(strlen(section));
3882 char spaced[length + 1];
3884 _profile(Database$mappedSectionForPointer$Replace)
3885 for (size_t index(0); index != length; ++index)
3886 spaced[index] = section[index] == '_' ? ' ' : section[index];
3887 spaced[length] = '\0';
3892 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3893 string = [NSString stringWithUTF8String:spaced];
3896 _profile(Database$mappedSectionForPointer$Map)
3897 string = [SectionMap_ objectForKey:string] ?: string;
3907 static _H<NSMutableSet> Diversions_;
3909 @interface Diversion : NSObject {
3912 _H<NSString> format_;
3917 @implementation Diversion
3919 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3920 if ((self = [super init]) != nil) {
3921 pattern_ = [from UTF8String];
3927 - (NSString *) divert:(NSString *)url {
3928 return !pattern_(url) ? nil : pattern_->*format_;
3931 + (NSURL *) divertURL:(NSURL *)url {
3933 NSString *href([url absoluteString]);
3935 for (Diversion *diversion in (id) Diversions_)
3936 if (NSString *diverted = [diversion divert:href]) {
3938 NSLog(@"div: %@", diverted);
3940 url = [NSURL URLWithString:diverted];
3947 - (NSString *) key {
3951 - (NSUInteger) hash {
3955 - (BOOL) isEqual:(Diversion *)object {
3956 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3961 @interface CydiaObject : NSObject {
3962 _H<CyteWebViewController> indirect_;
3963 _transient id delegate_;
3966 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3972 @interface CydiaWebViewController : CyteWebViewController {
3973 _H<CydiaObject> cydia_;
3976 + (void) addDiversion:(Diversion *)diversion;
3977 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
3978 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
3979 - (void) setDelegate:(id)delegate;
3983 /* Web Scripting {{{ */
3984 @implementation CydiaObject
3986 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3987 if ((self = [super init]) != nil) {
3988 indirect_ = (CyteWebViewController *) indirect;
3992 - (void) setDelegate:(id)delegate {
3993 delegate_ = delegate;
3996 + (NSArray *) _attributeKeys {
3997 return [NSArray arrayWithObjects:
4000 @"coreFoundationVersionNumber",
4017 - (NSArray *) attributeKeys {
4018 return [[self class] _attributeKeys];
4021 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4022 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4025 - (NSString *) version {
4029 - (NSString *) build {
4033 - (NSString *) coreFoundationVersionNumber {
4034 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4037 - (NSString *) device {
4038 return UniqueIdentifier();
4041 - (NSString *) firmware {
4042 return [[UIDevice currentDevice] systemVersion];
4045 - (NSString *) hostname {
4046 return [[UIDevice currentDevice] name];
4049 - (NSString *) idiom {
4050 return (id) Idiom_ ?: [NSNull null];
4053 - (NSString *) mcc {
4054 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4055 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4059 - (NSString *) mnc {
4060 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4061 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4065 - (NSString *) operator {
4066 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4067 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4071 - (NSString *) bbsnum {
4072 return (id) BBSNum_ ?: [NSNull null];
4075 - (NSString *) ecid {
4076 return (id) ChipID_ ?: [NSNull null];
4079 - (NSString *) serial {
4080 return SerialNumber_;
4083 - (NSString *) role {
4084 return (id) Role_ ?: [NSNull null];
4087 - (NSString *) model {
4088 return [NSString stringWithUTF8String:Machine_];
4091 - (NSString *) token {
4092 return (id) Token_ ?: [NSNull null];
4095 + (NSString *) webScriptNameForSelector:(SEL)selector {
4097 else if (selector == @selector(addBridgedHost:))
4098 return @"addBridgedHost";
4099 else if (selector == @selector(addInsecureHost:))
4100 return @"addInsecureHost";
4101 else if (selector == @selector(addInternalRedirect::))
4102 return @"addInternalRedirect";
4103 else if (selector == @selector(addPipelinedHost:scheme:))
4104 return @"addPipelinedHost";
4105 else if (selector == @selector(addSource:::))
4106 return @"addSource";
4107 else if (selector == @selector(addTokenHost:))
4108 return @"addTokenHost";
4109 else if (selector == @selector(addTrivialSource:))
4110 return @"addTrivialSource";
4111 else if (selector == @selector(close))
4113 else if (selector == @selector(du:))
4115 else if (selector == @selector(stringWithFormat:arguments:))
4117 else if (selector == @selector(getAllSources))
4118 return @"getAllSources";
4119 else if (selector == @selector(getApplicationInfo:value:))
4120 return @"getApplicationInfoValue";
4121 else if (selector == @selector(getKernelNumber:))
4122 return @"getKernelNumber";
4123 else if (selector == @selector(getKernelString:))
4124 return @"getKernelString";
4125 else if (selector == @selector(getInstalledPackages))
4126 return @"getInstalledPackages";
4127 else if (selector == @selector(getIORegistryEntry::))
4128 return @"getIORegistryEntry";
4129 else if (selector == @selector(getLocaleIdentifier))
4130 return @"getLocaleIdentifier";
4131 else if (selector == @selector(getPreferredLanguages))
4132 return @"getPreferredLanguages";
4133 else if (selector == @selector(getPackageById:))
4134 return @"getPackageById";
4135 else if (selector == @selector(getMetadataKeys))
4136 return @"getMetadataKeys";
4137 else if (selector == @selector(getMetadataValue:))
4138 return @"getMetadataValue";
4139 else if (selector == @selector(getSessionValue:))
4140 return @"getSessionValue";
4141 else if (selector == @selector(installPackages:))
4142 return @"installPackages";
4143 else if (selector == @selector(isReachable:))
4144 return @"isReachable";
4145 else if (selector == @selector(localizedStringForKey:value:table:))
4147 else if (selector == @selector(popViewController:))
4148 return @"popViewController";
4149 else if (selector == @selector(refreshSources))
4150 return @"refreshSources";
4151 else if (selector == @selector(registerFrame:))
4152 return @"registerFrame";
4153 else if (selector == @selector(removeButton))
4154 return @"removeButton";
4155 else if (selector == @selector(saveConfig))
4156 return @"saveConfig";
4157 else if (selector == @selector(setMetadataValue::))
4158 return @"setMetadataValue";
4159 else if (selector == @selector(setSessionValue::))
4160 return @"setSessionValue";
4161 else if (selector == @selector(substitutePackageNames:))
4162 return @"substitutePackageNames";
4163 else if (selector == @selector(scrollToBottom:))
4164 return @"scrollToBottom";
4165 else if (selector == @selector(setAllowsNavigationAction:))
4166 return @"setAllowsNavigationAction";
4167 else if (selector == @selector(setBadgeValue:))
4168 return @"setBadgeValue";
4169 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4170 return @"setButtonImage";
4171 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4172 return @"setButtonTitle";
4173 else if (selector == @selector(setHidesBackButton:))
4174 return @"setHidesBackButton";
4175 else if (selector == @selector(setHidesNavigationBar:))
4176 return @"setHidesNavigationBar";
4177 else if (selector == @selector(setNavigationBarStyle:))
4178 return @"setNavigationBarStyle";
4179 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4180 return @"setNavigationBarTintColor";
4181 else if (selector == @selector(setPasteboardString:))
4182 return @"setPasteboardString";
4183 else if (selector == @selector(setPasteboardURL:))
4184 return @"setPasteboardURL";
4185 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4186 return @"setScrollAlwaysBounceVertical";
4187 else if (selector == @selector(setScrollIndicatorStyle:))
4188 return @"setScrollIndicatorStyle";
4189 else if (selector == @selector(setToken:))
4191 else if (selector == @selector(setViewportWidth:))
4192 return @"setViewportWidth";
4193 else if (selector == @selector(statfs:))
4195 else if (selector == @selector(supports:))
4197 else if (selector == @selector(unload))
4203 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4204 return [self webScriptNameForSelector:selector] == nil;
4207 - (BOOL) supports:(NSString *)feature {
4208 return [feature isEqualToString:@"window.open"];
4212 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4215 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4216 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4219 - (void) setScrollIndicatorStyle:(NSString *)style {
4220 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4223 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4224 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4227 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4229 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4230 return (id) [NSNull null];
4231 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4233 return (id) [NSNull null];
4234 return [info objectForKey:key];
4237 - (NSNumber *) getKernelNumber:(NSString *)name {
4238 const char *string([name UTF8String]);
4241 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4242 return (id) [NSNull null];
4244 if (size != sizeof(int))
4245 return (id) [NSNull null];
4248 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4249 return (id) [NSNull null];
4251 return [NSNumber numberWithInt:value];
4254 - (NSString *) getKernelString:(NSString *)name {
4255 const char *string([name UTF8String]);
4258 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4259 return (id) [NSNull null];
4261 char value[size + 1];
4262 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4263 return (id) [NSNull null];
4265 // XXX: just in case you request something ludicrous
4268 return [NSString stringWithCString:value];
4271 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4272 NSObject *value(CYIOGetValue([path UTF8String], entry));
4275 if ([value isKindOfClass:[NSData class]])
4276 value = CYHex((NSData *) value);
4281 - (NSArray *) getMetadataKeys {
4282 @synchronized (Values_) {
4283 return [Values_ allKeys];
4286 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4287 WebFrame *frame([iframe contentFrame]);
4288 [indirect_ registerFrame:frame];
4291 - (id) getMetadataValue:(NSString *)key {
4292 @synchronized (Values_) {
4293 return [Values_ objectForKey:key];
4296 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4297 @synchronized (Values_) {
4298 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4299 [Values_ removeObjectForKey:key];
4301 [Values_ setObject:value forKey:key];
4303 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4306 - (id) getSessionValue:(NSString *)key {
4307 @synchronized (SessionData_) {
4308 return [SessionData_ objectForKey:key];
4311 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4312 @synchronized (SessionData_) {
4313 if (value == (id) [WebUndefined undefined])
4314 [SessionData_ removeObjectForKey:key];
4316 [SessionData_ setObject:value forKey:key];
4319 - (void) addBridgedHost:(NSString *)host {
4320 @synchronized (HostConfig_) {
4321 [BridgedHosts_ addObject:host];
4324 - (void) addInsecureHost:(NSString *)host {
4325 @synchronized (HostConfig_) {
4326 [InsecureHosts_ addObject:host];
4329 - (void) addTokenHost:(NSString *)host {
4330 @synchronized (HostConfig_) {
4331 [TokenHosts_ addObject:host];
4334 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4335 @synchronized (HostConfig_) {
4336 if (scheme != (id) [WebUndefined undefined])
4337 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4339 [PipelinedHosts_ addObject:host];
4342 - (void) popViewController:(NSNumber *)value {
4343 if (value == (id) [WebUndefined undefined])
4344 value = [NSNumber numberWithBool:YES];
4345 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4348 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4349 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4351 for (NSString *section in sections)
4352 [array addObject:section];
4354 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4357 distribution, @"Distribution",
4359 nil] waitUntilDone:NO];
4362 - (void) addTrivialSource:(NSString *)href {
4363 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4366 - (void) refreshSources {
4367 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4370 - (void) saveConfig {
4371 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4374 - (NSArray *) getAllSources {
4375 return [[Database sharedInstance] sources];
4378 - (NSArray *) getInstalledPackages {
4379 Database *database([Database sharedInstance]);
4380 @synchronized (database) {
4381 NSArray *packages([database packages]);
4382 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4383 for (Package *package in packages)
4384 if (![package uninstalled])
4385 [installed addObject:package];
4389 - (Package *) getPackageById:(NSString *)id {
4390 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4394 return (Package *) [NSNull null];
4397 - (NSString *) getLocaleIdentifier {
4398 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4401 - (NSArray *) getPreferredLanguages {
4405 - (NSArray *) statfs:(NSString *)path {
4408 if (path == nil || statfs([path UTF8String], &stat) == -1)
4411 return [NSArray arrayWithObjects:
4412 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4413 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4414 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4418 - (NSNumber *) du:(NSString *)path {
4419 NSNumber *value(nil);
4422 _assert(pipe(fds) != -1);
4424 pid_t pid(ExecFork());
4426 _assert(dup2(fds[1], 1) != -1);
4427 _assert(close(fds[0]) != -1);
4428 _assert(close(fds[1]) != -1);
4429 /* XXX: this should probably not use du */
4430 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4433 _assert(close(fds[1]) != -1);
4435 if (FILE *du = fdopen(fds[0], "r")) {
4437 while (fgets(line, sizeof(line), du) != NULL) {
4438 size_t length(strlen(line));
4439 while (length != 0 && line[length - 1] == '\n')
4440 line[--length] = '\0';
4441 if (char *tab = strchr(line, '\t')) {
4443 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4449 _assert(close(fds[0]) != -1);
4456 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4459 - (NSNumber *) isReachable:(NSString *)name {
4460 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4463 - (void) installPackages:(NSArray *)packages {
4464 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4467 - (NSString *) substitutePackageNames:(NSString *)message {
4468 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4469 for (size_t i(0), e([words count]); i != e; ++i) {
4470 NSString *word([words objectAtIndex:i]);
4471 if (Package *package = [[Database sharedInstance] packageWithName:word])
4472 [words replaceObjectAtIndex:i withObject:[package name]];
4475 return [words componentsJoinedByString:@" "];
4478 - (void) removeButton {
4479 [indirect_ removeButton];
4482 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4483 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4486 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4487 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4490 - (void) setBadgeValue:(id)value {
4491 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4494 - (void) setAllowsNavigationAction:(NSString *)value {
4495 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4498 - (void) setHidesBackButton:(NSString *)value {
4499 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4502 - (void) setHidesNavigationBar:(NSString *)value {
4503 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4506 - (void) setNavigationBarStyle:(NSString *)value {
4507 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4510 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4511 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4512 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4513 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4516 - (void) setPasteboardString:(NSString *)value {
4517 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4520 - (void) setPasteboardURL:(NSString *)value {
4521 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4524 - (void) _setToken:(NSString *)token {
4528 [Metadata_ removeObjectForKey:@"Token"];
4530 [Metadata_ setObject:Token_ forKey:@"Token"];
4535 - (void) setToken:(NSString *)token {
4536 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4539 - (void) scrollToBottom:(NSNumber *)animated {
4540 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4543 - (void) setViewportWidth:(float)width {
4544 [indirect_ setViewportWidthOnMainThread:width];
4547 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4548 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4549 unsigned count([arguments count]);
4551 for (unsigned i(0); i != count; ++i)
4552 values[i] = [arguments objectAtIndex:i];
4553 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4556 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4557 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4559 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4561 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4567 @interface NSURL (CydiaSecure)
4570 @implementation NSURL (CydiaSecure)
4572 - (bool) isCydiaSecure {
4573 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4576 @synchronized (HostConfig_) {
4577 if ([InsecureHosts_ containsObject:[self host]])
4586 /* Cydia Browser Controller {{{ */
4587 @implementation CydiaWebViewController
4589 - (NSURL *) navigationURL {
4590 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4593 + (void) _initialize {
4594 [super _initialize];
4596 Diversions_ = [NSMutableSet setWithCapacity:0];
4599 + (void) addDiversion:(Diversion *)diversion {
4600 [Diversions_ addObject:diversion];
4603 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4604 [super webView:view didClearWindowObject:window forFrame:frame];
4605 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4608 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4609 WebDataSource *source([frame dataSource]);
4610 NSURLResponse *response([source response]);
4611 NSURL *url([response URL]);
4612 NSString *scheme([[url scheme] lowercaseString]);
4614 bool bridged(false);
4616 @synchronized (HostConfig_) {
4617 if ([scheme isEqualToString:@"file"])
4619 else if ([scheme isEqualToString:@"https"])
4620 if ([BridgedHosts_ containsObject:[url host]])
4625 [window setValue:cydia forKey:@"cydia"];
4628 - (void) _setupMail:(MFMailComposeViewController *)controller {
4629 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4631 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4632 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4635 - (NSURL *) URLWithURL:(NSURL *)url {
4636 return [Diversion divertURL:url];
4639 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4640 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4643 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4644 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4646 NSURL *url([copy URL]);
4647 NSString *href([url absoluteString]);
4648 NSString *host([url host]);
4650 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4651 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4652 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4653 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4656 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4657 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4659 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4663 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4664 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4665 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4666 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4671 @synchronized (HostConfig_) {
4672 bridged = [BridgedHosts_ containsObject:host];
4673 token = [TokenHosts_ containsObject:host];
4676 if ([url isCydiaSecure]) {
4678 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4679 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4681 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4682 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4689 - (void) setDelegate:(id)delegate {
4690 [super setDelegate:delegate];
4691 [cydia_ setDelegate:delegate];
4694 - (NSString *) applicationNameForUserAgent {
4699 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4700 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4706 @interface AppCacheController : CydiaWebViewController {
4711 @implementation AppCacheController
4713 - (void) didReceiveMemoryWarning {
4714 // XXX: this doesn't work
4717 - (bool) retainsNetworkActivityIndicator {
4725 @interface NSObject (CydiaScript)
4726 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4729 @implementation NSObject (CydiaScript)
4731 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4737 @implementation NSArray (CydiaScript)
4739 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4740 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4741 for (size_t i(0), e([self count]); i != e; ++i)
4742 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4748 @implementation NSDictionary (CydiaScript)
4750 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4751 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4753 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4760 /* Confirmation Controller {{{ */
4761 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4762 if (!iterator.end())
4763 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4764 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4766 pkgCache::PkgIterator package(dep.TargetPkg());
4769 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4776 @protocol ConfirmationControllerDelegate
4777 - (void) cancelAndClear:(bool)clear;
4778 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4782 @interface ConfirmationController : CydiaWebViewController {
4783 _transient Database *database_;
4785 _H<UIAlertView> essential_;
4787 _H<NSDictionary> changes_;
4788 _H<NSMutableArray> issues_;
4789 _H<NSDictionary> sizes_;
4794 - (id) initWithDatabase:(Database *)database;
4798 @implementation ConfirmationController
4802 RestartSubstrate_ = true;
4803 [delegate_ confirmWithNavigationController:[self navigationController]];
4806 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4807 NSString *context([alert context]);
4809 if ([context isEqualToString:@"remove"]) {
4810 if (button == [alert cancelButtonIndex])
4811 [self dismissModalViewControllerAnimated:YES];
4812 else if (button == [alert firstOtherButtonIndex]) {
4813 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
4816 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4817 } else if ([context isEqualToString:@"unable"]) {
4818 [self dismissModalViewControllerAnimated:YES];
4819 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4821 [super alertView:alert clickedButtonAtIndex:button];
4825 - (void) _doContinue {
4826 [delegate_ cancelAndClear:NO];
4827 [self dismissModalViewControllerAnimated:YES];
4830 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4831 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4835 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4836 [super webView:view didClearWindowObject:window forFrame:frame];
4838 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4839 (id) changes_, @"changes",
4840 (id) issues_, @"issues",
4841 (id) sizes_, @"sizes",
4843 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4846 - (id) initWithDatabase:(Database *)database {
4847 if ((self = [super init]) != nil) {
4848 database_ = database;
4850 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4851 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4852 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4853 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4854 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4858 pkgCacheFile &cache([database_ cache]);
4859 NSArray *packages([database_ packages]);
4860 pkgDepCache::Policy *policy([database_ policy]);
4862 issues_ = [NSMutableArray arrayWithCapacity:4];
4864 for (Package *package in packages) {
4865 pkgCache::PkgIterator iterator([package iterator]);
4866 NSString *name([package id]);
4868 if ([package broken]) {
4869 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4871 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4873 reasons, @"reasons",
4876 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4880 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4881 pkgCache::DepIterator start;
4882 pkgCache::DepIterator end;
4883 dep.GlobOr(start, end); // ++dep
4885 if (!cache->IsImportantDep(end))
4887 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4890 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4892 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4893 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4894 clauses, @"clauses",
4898 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4900 pkgCache::PkgIterator target(start.TargetPkg());
4901 if (target->ProvidesList != 0)
4902 reason = @"missing";
4904 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4906 reason = @"installed";
4907 installed = [NSString stringWithUTF8String:ver.VerStr()];
4908 } else if (!cache[target].CandidateVerIter(cache).end())
4909 reason = @"uninstalled";
4910 else if (target->ProvidesList == 0)
4911 reason = @"uninstallable";
4913 reason = @"virtual";
4916 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4917 [NSString stringWithUTF8String:start.CompType()], @"operator",
4918 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4921 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4922 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4923 version, @"version",
4925 installed, @"installed",
4928 // yes, seriously. (wtf?)
4936 pkgDepCache::StateCache &state(cache[iterator]);
4938 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4940 if (state.NewInstall())
4941 [installs addObject:name];
4942 // XXX: else if (state.Install())
4943 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4944 [reinstalls addObject:name];
4945 // XXX: move before previous if
4946 else if (state.Upgrade())
4947 [upgrades addObject:name];
4948 else if (state.Downgrade())
4949 [downgrades addObject:name];
4950 else if (!state.Delete())
4951 // XXX: _assert(state.Keep());
4953 else if (special_r(name))
4954 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4955 [NSNull null], @"package",
4956 [NSArray arrayWithObjects:
4957 [NSDictionary dictionaryWithObjectsAndKeys:
4958 @"Conflicts", @"relationship",
4959 [NSArray arrayWithObjects:
4960 [NSDictionary dictionaryWithObjectsAndKeys:
4962 [NSNull null], @"version",
4963 @"installed", @"reason",
4970 if ([package essential])
4972 [removes addObject:name];
4975 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4976 substrate_ |= DepSubstrate(iterator.CurrentVer());
4981 else if (Advanced_) {
4982 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4984 essential_ = [[[UIAlertView alloc]
4985 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4986 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4988 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4990 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4994 [essential_ setContext:@"remove"];
4995 [essential_ setNumberOfRows:2];
4997 essential_ = [[[UIAlertView alloc]
4998 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4999 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5001 cancelButtonTitle:UCLocalize("OKAY")
5002 otherButtonTitles:nil
5005 [essential_ setContext:@"unable"];
5008 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5009 installs, @"installs",
5010 reinstalls, @"reinstalls",
5011 upgrades, @"upgrades",
5012 downgrades, @"downgrades",
5013 removes, @"removes",
5016 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5017 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5018 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5021 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5025 - (UIBarButtonItem *) leftButton {
5026 return [[[UIBarButtonItem alloc]
5027 initWithTitle:UCLocalize("CANCEL")
5028 style:UIBarButtonItemStylePlain
5030 action:@selector(cancelButtonClicked)
5035 - (void) applyRightButton {
5036 if ([issues_ count] == 0 && ![self isLoading])
5037 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5038 initWithTitle:UCLocalize("CONFIRM")
5039 style:UIBarButtonItemStyleDone
5041 action:@selector(confirmButtonClicked)
5044 [[self navigationItem] setRightBarButtonItem:nil];
5048 - (void) cancelButtonClicked {
5049 [delegate_ cancelAndClear:YES];
5050 [self dismissModalViewControllerAnimated:YES];
5054 - (void) confirmButtonClicked {
5055 if (essential_ != nil)
5065 /* Progress Data {{{ */
5066 @interface CydiaProgressData : NSObject {
5067 _transient id delegate_;
5076 _H<NSMutableArray> events_;
5077 _H<NSString> title_;
5079 _H<NSString> status_;
5080 _H<NSString> finish_;
5085 @implementation CydiaProgressData
5087 + (NSArray *) _attributeKeys {
5088 return [NSArray arrayWithObjects:
5100 - (NSArray *) attributeKeys {
5101 return [[self class] _attributeKeys];
5104 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5105 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5109 if ((self = [super init]) != nil) {
5110 events_ = [NSMutableArray arrayWithCapacity:32];
5118 - (void) setDelegate:(id)delegate {
5119 delegate_ = delegate;
5122 - (void) setPercent:(float)value {
5126 - (NSNumber *) percent {
5127 return [NSNumber numberWithFloat:percent_];
5130 - (void) setCurrent:(float)value {
5134 - (NSNumber *) current {
5135 return [NSNumber numberWithFloat:current_];
5138 - (void) setTotal:(float)value {
5142 - (NSNumber *) total {
5143 return [NSNumber numberWithFloat:total_];
5146 - (void) setSpeed:(float)value {
5150 - (NSNumber *) speed {
5151 return [NSNumber numberWithFloat:speed_];
5154 - (NSArray *) events {
5158 - (void) removeAllEvents {
5159 [events_ removeAllObjects];
5162 - (void) addEvent:(CydiaProgressEvent *)event {
5163 [events_ addObject:event];
5166 - (void) setTitle:(NSString *)text {
5170 - (NSString *) title {
5174 - (void) setFinish:(NSString *)text {
5178 - (NSString *) finish {
5179 return (id) finish_ ?: [NSNull null];
5182 - (void) setRunning:(bool)running {
5186 - (NSNumber *) running {
5187 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5192 /* Progress Controller {{{ */
5193 @interface ProgressController : CydiaWebViewController <
5196 _transient Database *database_;
5197 _H<CydiaProgressData, 1> progress_;
5201 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5203 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5205 - (void) setTitle:(NSString *)title;
5206 - (void) setCancellable:(bool)cancellable;
5210 @implementation ProgressController
5213 [database_ setProgressDelegate:nil];
5217 - (UIBarButtonItem *) leftButton {
5218 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5219 initWithTitle:UCLocalize("CANCEL")
5220 style:UIBarButtonItemStylePlain
5222 action:@selector(cancel)
5223 ] autorelease] : nil;
5226 - (void) updateCancel {
5227 [super applyLeftButton];
5230 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5231 if ((self = [super init]) != nil) {
5232 database_ = database;
5233 delegate_ = delegate;
5235 [database_ setProgressDelegate:self];
5237 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5238 [progress_ setDelegate:self];
5240 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5242 [scroller_ setBackgroundColor:[UIColor blackColor]];
5244 [[self navigationItem] setHidesBackButton:YES];
5246 [self updateCancel];
5250 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5251 [super webView:view didClearWindowObject:window forFrame:frame];
5252 [window setValue:progress_ forKey:@"cydiaProgress"];
5255 - (void) updateProgress {
5256 [self dispatchEvent:@"CydiaProgressUpdate"];
5259 - (void) viewWillAppear:(BOOL)animated {
5260 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5261 [super viewWillAppear:animated];
5264 - (void) reloadSpringBoard {
5265 if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
5266 system("/bin/launchctl stop com.apple.backboardd");
5268 system("/usr/bin/killall backboardd SpringBoard sbreload");
5272 pid_t pid(ExecFork());
5277 pid_t pid(ExecFork());
5279 execl("/usr/bin/sbreload", "sbreload", NULL);
5289 system("/usr/bin/killall backboardd SpringBoard sbreload");
5293 UpdateExternalStatus(0);
5296 [delegate_ saveState];
5300 [delegate_ returnToCydia];
5304 [delegate_ terminateWithSuccess];
5305 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5306 [delegate_ suspendWithAnimation:YES];
5308 [delegate_ suspend];*/
5320 UIProgressHUD *hud([delegate_ addProgressHUD]);
5321 [hud setText:UCLocalize("LOADING")];
5322 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5328 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5329 SBReboot(SBSSpringBoardServerPort());
5331 reboot2(RB_AUTOBOOT);
5338 - (void) setTitle:(NSString *)title {
5339 [progress_ setTitle:title];
5340 [self updateProgress];
5343 - (UIBarButtonItem *) rightButton {
5344 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5345 initWithTitle:UCLocalize("CLOSE")
5346 style:UIBarButtonItemStylePlain
5348 action:@selector(close)
5352 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5353 UpdateExternalStatus(1);
5355 [progress_ setRunning:true];
5356 [self setTitle:title];
5357 // implicit updateProgress
5359 SHA1SumValue notifyconf; {
5361 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5364 MMap mmap(file, MMap::ReadOnly);
5366 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5367 notifyconf = sha1.Result();
5371 SHA1SumValue springlist; {
5373 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5376 MMap mmap(file, MMap::ReadOnly);
5378 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5379 springlist = sha1.Result();
5383 if (invocation != nil) {
5384 [invocation yieldToSelector:@selector(invoke)];
5385 [self setTitle:@"COMPLETE"];
5390 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5393 MMap mmap(file, MMap::ReadOnly);
5395 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5396 if (!(notifyconf == sha1.Result()))
5403 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5406 MMap mmap(file, MMap::ReadOnly);
5408 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5409 if (!(springlist == sha1.Result()))
5415 if (RestartSubstrate_)
5419 RestartSubstrate_ = false;
5422 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5423 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5424 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5425 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5426 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5429 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5431 [progress_ setRunning:false];
5432 [self updateProgress];
5434 [self applyRightButton];
5437 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5438 [progress_ addEvent:event];
5439 [self updateProgress];
5442 - (bool) isProgressCancelled {
5443 return cancel_ == 2;
5448 [self updateCancel];
5451 - (void) setCancellable:(bool)cancellable {
5452 unsigned cancel(cancel_);
5456 else if (cancel_ == 0)
5459 if (cancel != cancel_)
5460 [self updateCancel];
5463 - (void) setProgressCancellable:(NSNumber *)cancellable {
5464 [self setCancellable:[cancellable boolValue]];
5467 - (void) setProgressPercent:(NSNumber *)percent {
5468 [progress_ setPercent:[percent floatValue]];
5469 [self updateProgress];
5472 - (void) setProgressStatus:(NSDictionary *)status {
5473 if (status == nil) {
5474 [progress_ setCurrent:0];
5475 [progress_ setTotal:0];
5476 [progress_ setSpeed:0];
5478 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5480 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5481 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5482 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5485 [self updateProgress];
5491 /* Package Cell {{{ */
5492 @interface PackageCell : CyteTableViewCell <
5493 CyteTableViewCellDelegate
5497 _H<NSString> description_;
5499 _H<NSString> source_;
5501 _H<UIImage> placard_;
5505 - (PackageCell *) init;
5506 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5508 - (void) drawContentRect:(CGRect)rect;
5512 @implementation PackageCell
5514 - (PackageCell *) init {
5515 CGRect frame(CGRectMake(0, 0, 320, 74));
5516 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5517 UIView *content([self contentView]);
5518 CGRect bounds([content bounds]);
5520 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5521 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5522 [content addSubview:content_];
5524 [content_ setDelegate:self];
5525 [content_ setOpaque:YES];
5529 - (NSString *) accessibilityLabel {
5533 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5534 summarized_ = summary;
5544 [content_ setBackgroundColor:[UIColor whiteColor]];
5548 Source *source = [package source];
5550 icon_ = [package icon];
5552 if (NSString *name = [package name])
5553 name_ = [NSString stringWithString:name];
5555 if (NSString *description = [package shortDescription])
5556 description_ = [NSString stringWithString:description];
5558 commercial_ = [package isCommercial];
5560 NSString *label = nil;
5561 bool trusted = false;
5563 if (source != nil) {
5564 label = [source label];
5565 trusted = [source trusted];
5566 } else if ([[package id] isEqualToString:@"firmware"])
5567 label = UCLocalize("APPLE");
5569 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5571 NSString *from(label);
5573 NSString *section = [package simpleSection];
5574 if (section != nil && ![section isEqualToString:label]) {
5575 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5576 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5579 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5581 if (NSString *purpose = [package primaryPurpose])
5582 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5587 if (NSString *mode = [package mode]) {
5588 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5589 color = RemovingColor_;
5590 placard = @"removing";
5592 color = InstallingColor_;
5593 placard = @"installing";
5596 color = [UIColor whiteColor];
5598 if ([package installed] != nil)
5599 placard = @"installed";
5604 [content_ setBackgroundColor:color];
5607 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5610 [self setNeedsDisplay];
5611 [content_ setNeedsDisplay];
5614 - (void) drawSummaryContentRect:(CGRect)rect {
5615 bool highlighted(highlighted_);
5616 float width([self bounds].size.width);
5620 rect.size = [(UIImage *) icon_ size];
5622 while (rect.size.width > 16 || rect.size.height > 16) {
5623 rect.size.width /= 2;
5624 rect.size.height /= 2;
5627 rect.origin.x = 19 - rect.size.width / 2;
5628 rect.origin.y = 19 - rect.size.height / 2;
5630 [icon_ drawInRect:rect];
5633 if (badge_ != nil) {
5635 rect.size = [(UIImage *) badge_ size];
5637 rect.size.width /= 4;
5638 rect.size.height /= 4;
5640 rect.origin.x = 25 - rect.size.width / 2;
5641 rect.origin.y = 25 - rect.size.height / 2;
5643 [badge_ drawInRect:rect];
5646 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5650 UISetColor(commercial_ ? Purple_ : Black_);
5651 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5653 if (placard_ != nil)
5654 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5657 - (void) drawNormalContentRect:(CGRect)rect {
5658 bool highlighted(highlighted_);
5659 float width([self bounds].size.width);
5663 rect.size = [(UIImage *) icon_ size];
5665 while (rect.size.width > 32 || rect.size.height > 32) {
5666 rect.size.width /= 2;
5667 rect.size.height /= 2;
5670 rect.origin.x = 25 - rect.size.width / 2;
5671 rect.origin.y = 25 - rect.size.height / 2;
5673 [icon_ drawInRect:rect];
5676 if (badge_ != nil) {
5678 rect.size = [(UIImage *) badge_ size];
5680 rect.size.width /= 2;
5681 rect.size.height /= 2;
5683 rect.origin.x = 36 - rect.size.width / 2;
5684 rect.origin.y = 36 - rect.size.height / 2;
5686 [badge_ drawInRect:rect];
5689 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5693 UISetColor(commercial_ ? Purple_ : Black_);
5694 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5695 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5698 UISetColor(commercial_ ? Purplish_ : Gray_);
5699 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5701 if (placard_ != nil)
5702 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5705 - (void) drawContentRect:(CGRect)rect {
5707 [self drawSummaryContentRect:rect];
5709 [self drawNormalContentRect:rect];
5714 /* Section Cell {{{ */
5715 @interface SectionCell : CyteTableViewCell <
5716 CyteTableViewCellDelegate
5718 _H<NSString> basic_;
5719 _H<NSString> section_;
5721 _H<NSString> count_;
5723 _H<UISwitch> switch_;
5727 - (void) setSection:(Section *)section editing:(BOOL)editing;
5731 @implementation SectionCell
5733 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5734 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5735 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5736 // XXX: this initial frame is wrong, but is fixed later
5737 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5738 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5740 UIView *content([self contentView]);
5741 CGRect bounds([content bounds]);
5743 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5744 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5745 [content addSubview:content_];
5746 [content_ setBackgroundColor:[UIColor whiteColor]];
5748 [content_ setDelegate:self];
5752 - (void) onSwitch:(id)sender {
5753 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5754 if (metadata == nil) {
5755 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5756 [Sections_ setObject:metadata forKey:basic_];
5759 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5763 - (void) setSection:(Section *)section editing:(BOOL)editing {
5764 if (editing != editing_) {
5766 [switch_ removeFromSuperview];
5768 [self addSubview:switch_];
5777 if (section == nil) {
5778 name_ = UCLocalize("ALL_PACKAGES");
5781 basic_ = [section name];
5782 section_ = [section localized];
5784 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5785 count_ = [NSString stringWithFormat:@"%d", [section count]];
5788 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5791 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5792 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5794 [content_ setNeedsDisplay];
5797 - (void) setFrame:(CGRect)frame {
5798 [super setFrame:frame];
5800 CGRect rect([switch_ frame]);
5801 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
5804 - (NSString *) accessibilityLabel {
5808 - (void) drawContentRect:(CGRect)rect {
5809 bool highlighted(highlighted_ && !editing_);
5811 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
5813 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5816 float width(rect.size.width);
5818 width -= 9 + [switch_ frame].size.width;
5822 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:UILineBreakModeTailTruncation];
5824 CGSize size = [count_ sizeWithFont:Font14_];
5826 UISetColor(Folder_);
5828 [count_ drawAtPoint:CGPointMake(10 + (30 - size.width) / 2, 18) withFont:Font12Bold_];
5834 /* File Table {{{ */
5835 @interface FileTable : CyteViewController <
5836 UITableViewDataSource,
5839 _transient Database *database_;
5840 _H<Package> package_;
5842 _H<NSMutableArray> files_;
5843 _H<UITableView, 2> list_;
5846 - (id) initWithDatabase:(Database *)database;
5847 - (void) setPackage:(Package *)package;
5851 @implementation FileTable
5853 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5854 return files_ == nil ? 0 : [files_ count];
5857 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5861 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5862 static NSString *reuseIdentifier = @"Cell";
5864 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5866 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5867 [cell setFont:[UIFont systemFontOfSize:16]];
5869 [cell setText:[files_ objectAtIndex:indexPath.row]];
5870 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5875 - (NSURL *) navigationURL {
5876 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5880 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5881 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5882 [list_ setRowHeight:24.0f];
5883 [(UITableView *) list_ setDataSource:self];
5884 [list_ setDelegate:self];
5885 [self setView:list_];
5888 - (void) viewDidLoad {
5889 [super viewDidLoad];
5891 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5894 - (void) releaseSubviews {
5900 [super releaseSubviews];
5903 - (id) initWithDatabase:(Database *)database {
5904 if ((self = [super init]) != nil) {
5905 database_ = database;
5909 - (void) setPackage:(Package *)package {
5913 files_ = [NSMutableArray arrayWithCapacity:32];
5915 if (package != nil) {
5917 name_ = [package id];
5919 if (NSArray *files = [package files])
5920 [files_ addObjectsFromArray:files];
5922 if ([files_ count] != 0) {
5923 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5924 [files_ removeObjectAtIndex:0];
5925 [files_ sortUsingSelector:@selector(compareByPath:)];
5927 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5928 [stack addObject:@"/"];
5930 for (int i(0), e([files_ count]); i != e; ++i) {
5931 NSString *file = [files_ objectAtIndex:i];
5932 while (![file hasPrefix:[stack lastObject]])
5933 [stack removeLastObject];
5934 NSString *directory = [stack lastObject];
5935 [stack addObject:[file stringByAppendingString:@"/"]];
5936 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5937 ([stack count] - 2) * 3, "",
5938 [file substringFromIndex:[directory length]]
5947 - (void) reloadData {
5950 [self setPackage:[database_ packageWithName:name_]];
5955 /* Package Controller {{{ */
5956 @interface CYPackageController : CydiaWebViewController <
5957 UIActionSheetDelegate
5959 _transient Database *database_;
5960 _H<Package> package_;
5963 _H<NSMutableArray> buttons_;
5964 _H<UIBarButtonItem> button_;
5967 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
5971 @implementation CYPackageController
5973 - (NSURL *) navigationURL {
5974 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5977 /* XXX: this is not safe at all... localization of /fail/ */
5978 - (void) _clickButtonWithName:(NSString *)name {
5979 if ([name isEqualToString:UCLocalize("CLEAR")])
5980 [delegate_ clearPackage:package_];
5981 else if ([name isEqualToString:UCLocalize("INSTALL")])
5982 [delegate_ installPackage:package_];
5983 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5984 [delegate_ installPackage:package_];
5985 else if ([name isEqualToString:UCLocalize("REMOVE")])
5986 [delegate_ removePackage:package_];
5987 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5988 [delegate_ installPackage:package_];
5989 else _assert(false);
5992 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5993 NSString *context([sheet context]);
5995 if ([context isEqualToString:@"modify"]) {
5996 if (button != [sheet cancelButtonIndex]) {
5997 NSString *buttonName = [buttons_ objectAtIndex:button];
5998 [self _clickButtonWithName:buttonName];
6001 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6005 - (bool) _allowJavaScriptPanel {
6010 - (void) _customButtonClicked {
6011 int count([buttons_ count]);
6016 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6018 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6019 [buttons addObjectsFromArray:buttons_];
6021 UIActionSheet *sheet = [[[UIActionSheet alloc]
6024 cancelButtonTitle:nil
6025 destructiveButtonTitle:nil
6026 otherButtonTitles:nil
6029 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6031 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6032 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6034 [sheet setContext:@"modify"];
6036 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6040 - (void) reloadButtonClicked {
6041 if (commercial_ && function_ == nil && [package_ uninstalled])
6043 [self customButtonClicked];
6046 - (void) applyLoadingTitle {
6047 // Don't show "Loading" as the title. Ever.
6050 - (UIBarButtonItem *) rightButton {
6055 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6056 if ((self = [super init]) != nil) {
6057 database_ = database;
6058 buttons_ = [NSMutableArray arrayWithCapacity:4];
6059 name_ = name == nil ? @"" : [NSString stringWithString:name];
6060 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6064 - (void) reloadData {
6067 package_ = [database_ packageWithName:name_];
6069 [buttons_ removeAllObjects];
6071 if (package_ != nil) {
6072 [(Package *) package_ parse];
6074 commercial_ = [package_ isCommercial];
6076 if ([package_ mode] != nil)
6077 [buttons_ addObject:UCLocalize("CLEAR")];
6078 if ([package_ source] == nil);
6079 else if ([package_ upgradableAndEssential:NO])
6080 [buttons_ addObject:UCLocalize("UPGRADE")];
6081 else if ([package_ uninstalled])
6082 [buttons_ addObject:UCLocalize("INSTALL")];
6084 [buttons_ addObject:UCLocalize("REINSTALL")];
6085 if (![package_ uninstalled])
6086 [buttons_ addObject:UCLocalize("REMOVE")];
6090 switch ([buttons_ count]) {
6091 case 0: title = nil; break;
6092 case 1: title = [buttons_ objectAtIndex:0]; break;
6093 default: title = UCLocalize("MODIFY"); break;
6096 button_ = [[[UIBarButtonItem alloc]
6098 style:UIBarButtonItemStylePlain
6100 action:@selector(customButtonClicked)
6104 - (bool) isLoading {
6105 return commercial_ ? [super isLoading] : false;
6111 /* Package List Controller {{{ */
6112 @interface PackageListController : CyteViewController <
6113 UITableViewDataSource,
6116 _transient Database *database_;
6118 _H<NSArray> packages_;
6119 _H<NSMutableArray> sections_;
6120 _H<UITableView, 2> list_;
6121 _H<NSMutableArray> index_;
6122 _H<NSMutableDictionary> indices_;
6123 _H<NSString> title_;
6124 unsigned reloading_;
6127 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6128 - (void) setDelegate:(id)delegate;
6129 - (void) resetCursor;
6134 @implementation PackageListController
6136 - (NSURL *) referrerURL {
6137 return [self navigationURL];
6140 - (bool) isSummarized {
6144 - (bool) showsSections {
6148 - (void) deselectWithAnimation:(BOOL)animated {
6149 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6152 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6153 CGRect base = [[self view] bounds];
6154 base.size.height -= bounds.size.height;
6155 base.origin = [list_ frame].origin;
6157 [UIView beginAnimations:nil context:NULL];
6158 [UIView setAnimationBeginsFromCurrentState:YES];
6159 [UIView setAnimationCurve:curve];
6160 [UIView setAnimationDuration:duration];
6161 [list_ setFrame:base];
6162 [UIView commitAnimations];
6165 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6166 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6169 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6170 [self resizeForKeyboardBounds:bounds duration:0];
6173 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6174 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6175 *curve = UIViewAnimationCurveEaseInOut;
6177 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6179 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6182 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6185 - (void) keyboardWillShow:(NSNotification *)notification {
6188 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6189 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6191 NSTimeInterval duration;
6192 UIViewAnimationCurve curve;
6193 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6195 CGRect kbframe = CGRectMake(round(center.x - bounds.size.width / 2.0), round(center.y - bounds.size.height / 2.0), bounds.size.width, bounds.size.height);
6196 UIViewController *base = self;
6197 while ([base parentOrPresentingViewController] != nil)
6198 base = [base parentOrPresentingViewController];
6199 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6200 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6202 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6203 intersection.size.height += CYStatusBarHeight();
6205 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6208 - (void) keyboardWillHide:(NSNotification *)notification {
6209 NSTimeInterval duration;
6210 UIViewAnimationCurve curve;
6211 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6213 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6216 - (void) viewWillAppear:(BOOL)animated {
6217 [super viewWillAppear:animated];
6219 [self resizeForKeyboardBounds:CGRectZero];
6220 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6221 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6224 - (void) viewWillDisappear:(BOOL)animated {
6225 [super viewWillDisappear:animated];
6227 [self resizeForKeyboardBounds:CGRectZero];
6228 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6229 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6232 - (void) viewDidAppear:(BOOL)animated {
6233 [super viewDidAppear:animated];
6234 [self deselectWithAnimation:animated];
6237 - (void) didSelectPackage:(Package *)package {
6238 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6239 [view setDelegate:delegate_];
6240 [[self navigationController] pushViewController:view animated:YES];
6243 #if TryIndexedCollation
6244 + (BOOL) hasIndexedCollation {
6245 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6249 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6250 NSInteger count([sections_ count]);
6251 return count == 0 ? 1 : count;
6254 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6255 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6257 return [[sections_ objectAtIndex:section] name];
6260 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6261 if ([sections_ count] == 0)
6263 return [[sections_ objectAtIndex:section] count];
6266 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6267 @synchronized (database_) {
6268 if ([database_ era] != era_)
6271 Section *section([sections_ objectAtIndex:[path section]]);
6272 NSInteger row([path row]);
6273 Package *package([packages_ objectAtIndex:([section row] + row)]);
6274 return [[package retain] autorelease];
6277 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6278 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6280 cell = [[[PackageCell alloc] init] autorelease];
6282 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6283 [cell setPackage:package asSummary:[self isSummarized]];
6287 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6288 Package *package([self packageAtIndexPath:path]);
6289 package = [database_ packageWithName:[package id]];
6290 [self didSelectPackage:package];
6293 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6294 if (![self showsSections])
6300 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6301 #if TryIndexedCollation
6302 if ([[self class] hasIndexedCollation]) {
6303 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6310 - (void) updateHeight {
6311 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6314 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6315 if ((self = [super init]) != nil) {
6316 database_ = database;
6317 title_ = [title copy];
6318 [[self navigationItem] setTitle:title_];
6323 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6324 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6325 [self setView:view];
6327 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6328 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6329 [view addSubview:list_];
6331 // XXX: is 20 the most optimal number here?
6332 [list_ setSectionIndexMinimumDisplayRowCount:20];
6334 [(UITableView *) list_ setDataSource:self];
6335 [list_ setDelegate:self];
6337 [self updateHeight];
6340 - (void) releaseSubviews {
6348 [super releaseSubviews];
6351 - (void) setDelegate:(id)delegate {
6352 delegate_ = delegate;
6355 - (bool) shouldYield {
6359 - (bool) shouldBlock {
6363 - (NSMutableArray *) _reloadPackages {
6364 @synchronized (database_) {
6365 era_ = [database_ era];
6366 NSArray *packages([database_ packages]);
6368 return [NSMutableArray arrayWithArray:packages];
6371 - (void) _reloadData {
6372 if (reloading_ != 0) {
6380 if ([self shouldYield]) {
6384 if (![self shouldBlock])
6387 hud = [delegate_ addProgressHUD];
6388 [hud setText:UCLocalize("LOADING")];
6392 packages = [self yieldToSelector:@selector(_reloadPackages)];
6395 [delegate_ removeProgressHUD:hud];
6396 } while (reloading_ == 2);
6398 packages = [self _reloadPackages];
6401 @synchronized (database_) {
6402 if (era_ != [database_ era])
6406 packages_ = packages;
6408 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6409 sections_ = [NSMutableArray arrayWithCapacity:16];
6411 Section *section = nil;
6413 #if TryIndexedCollation
6414 if ([[self class] hasIndexedCollation]) {
6415 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6417 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6418 NSArray *titles = [collation sectionIndexTitles];
6421 _profile(PackageTable$reloadData$Section)
6422 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6426 _profile(PackageTable$reloadData$Section$Package)
6427 package = [packages_ objectAtIndex:offset];
6428 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6431 while (secidx < index) {
6434 _profile(PackageTable$reloadData$Section$Allocate)
6435 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6438 _profile(PackageTable$reloadData$Section$Add)
6439 [sections_ addObject:section];
6443 [section addToCount];
6449 index_ = [NSMutableArray arrayWithCapacity:32];
6451 bool sectioned([self showsSections]);
6453 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6454 [sections_ addObject:section];
6457 _profile(PackageTable$reloadData$Section)
6458 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6462 _profile(PackageTable$reloadData$Section$Package)
6463 package = [packages_ objectAtIndex:offset];
6464 index = [package index];
6467 if (sectioned && (section == nil || [section index] != index)) {
6468 _profile(PackageTable$reloadData$Section$Allocate)
6469 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6472 [index_ addObject:[section name]];
6473 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6475 _profile(PackageTable$reloadData$Section$Add)
6476 [sections_ addObject:section];
6480 [section addToCount];
6485 [self updateHeight];
6487 _profile(PackageTable$reloadData$List)
6488 [(UITableView *) list_ setDataSource:self];
6493 - (void) reloadData {
6496 if ([self shouldYield])
6497 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6502 - (void) resetCursor {
6503 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6506 - (void) clearData {
6507 [self updateHeight];
6509 [list_ setDataSource:nil];
6517 /* Filtered Package List Controller {{{ */
6518 @interface FilteredPackageListController : PackageListController {
6521 _H<NSObject> object_;
6524 - (void) setObject:(id)object;
6525 - (void) setObject:(id)object forFilter:(SEL)filter;
6528 - (void) setFilter:(SEL)filter;
6530 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6534 @implementation FilteredPackageListController
6540 - (void) setFilter:(SEL)filter {
6541 @synchronized (self) {
6544 /* XXX: this is an unsafe optimization of doomy hell */
6545 Method method(class_getInstanceMethod([Package class], filter));
6546 _assert(method != NULL);
6547 imp_ = method_getImplementation(method);
6548 _assert(imp_ != NULL);
6551 - (void) setObject:(id)object {
6552 @synchronized (self) {
6556 - (void) setObject:(id)object forFilter:(SEL)filter {
6557 @synchronized (self) {
6558 [self setFilter:filter];
6559 [self setObject:object];
6562 - (NSMutableArray *) _reloadPackages {
6563 @synchronized (database_) {
6564 era_ = [database_ era];
6565 NSArray *packages([database_ packages]);
6567 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6571 _H<NSObject> object;
6573 @synchronized (self) {
6579 _profile(PackageTable$reloadData$Filter)
6580 for (Package *package in packages)
6581 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6582 [filtered addObject:package];
6588 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6589 if ((self = [super initWithDatabase:database title:title]) != nil) {
6590 [self setFilter:filter];
6591 [self setObject:object];
6598 /* Home Controller {{{ */
6599 @interface HomeController : CydiaWebViewController {
6600 CFRunLoopRef runloop_;
6601 SCNetworkReachabilityRef reachability_;
6606 @implementation HomeController
6608 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6609 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6613 if ((self = [super init]) != nil) {
6614 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6617 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6618 if (reachability_ != NULL) {
6619 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6620 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6622 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6623 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6630 if (reachability_ != NULL && runloop_ != NULL)
6631 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6635 - (NSURL *) navigationURL {
6636 return [NSURL URLWithString:@"cydia://home"];
6639 - (void) aboutButtonClicked {
6640 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6642 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6643 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6644 [alert setCancelButtonIndex:0];
6647 @"Copyright \u00a9 2008-2013\n"
6650 "Jay Freeman (saurik)\n"
6651 "saurik@saurik.com\n"
6652 "http://www.saurik.com/"
6658 - (UIBarButtonItem *) leftButton {
6659 return [[[UIBarButtonItem alloc]
6660 initWithTitle:UCLocalize("ABOUT")
6661 style:UIBarButtonItemStylePlain
6663 action:@selector(aboutButtonClicked)
6669 /* Manage Controller {{{ */
6670 @interface ManageController : CydiaWebViewController {
6673 - (void) queueStatusDidChange;
6677 @implementation ManageController
6680 if ((self = [super init]) != nil) {
6681 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6685 - (NSURL *) navigationURL {
6686 return [NSURL URLWithString:@"cydia://manage"];
6689 - (UIBarButtonItem *) leftButton {
6690 return [[[UIBarButtonItem alloc]
6691 initWithTitle:UCLocalize("SETTINGS")
6692 style:UIBarButtonItemStylePlain
6694 action:@selector(settingsButtonClicked)
6698 - (void) settingsButtonClicked {
6699 [delegate_ showSettings];
6702 - (void) queueButtonClicked {
6706 - (UIBarButtonItem *) rightButton {
6707 return Queuing_ ? [[[UIBarButtonItem alloc]
6708 initWithTitle:UCLocalize("QUEUE")
6709 style:UIBarButtonItemStyleDone
6711 action:@selector(queueButtonClicked)
6712 ] autorelease] : nil;
6715 - (void) queueStatusDidChange {
6716 [self applyRightButton];
6719 - (bool) isLoading {
6720 return !Queuing_ && [super isLoading];
6726 /* Refresh Bar {{{ */
6727 @interface RefreshBar : UINavigationBar {
6728 _H<UIProgressIndicator> indicator_;
6729 _H<UITextLabel> prompt_;
6730 _H<UINavigationButton> cancel_;
6735 @implementation RefreshBar
6737 - (void) positionViews {
6738 CGRect frame = [cancel_ frame];
6739 frame.size = [cancel_ sizeThatFits:frame.size];
6740 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6741 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6742 [cancel_ setFrame:frame];
6744 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6745 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6746 CGRect indrect = {{indoffset, indoffset}, indsize};
6747 [indicator_ setFrame:indrect];
6749 CGSize prmsize = {215, indsize.height + 4};
6751 indoffset * 2 + indsize.width,
6752 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6754 [prompt_ setFrame:prmrect];
6757 - (void) setFrame:(CGRect)frame {
6758 [super setFrame:frame];
6759 [self positionViews];
6762 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6763 if ((self = [super initWithFrame:frame]) != nil) {
6764 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6766 [self setBarStyle:UIBarStyleBlack];
6768 UIBarStyle barstyle([self _barStyle:NO]);
6769 bool ugly(barstyle == UIBarStyleDefault);
6771 UIProgressIndicatorStyle style = ugly ?
6772 UIProgressIndicatorStyleMediumBrown :
6773 UIProgressIndicatorStyleMediumWhite;
6775 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6776 [(UIProgressIndicator *) indicator_ setStyle:style];
6777 [indicator_ startAnimation];
6778 [self addSubview:indicator_];
6780 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6781 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6782 [prompt_ setBackgroundColor:[UIColor clearColor]];
6783 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6784 [self addSubview:prompt_];
6786 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6787 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6788 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6789 [cancel_ setBarStyle:barstyle];
6791 [self positionViews];
6795 - (void) setCancellable:(bool)cancellable {
6797 [self addSubview:cancel_];
6799 [cancel_ removeFromSuperview];
6803 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6807 [self setCancellable:NO];
6810 - (void) setPrompt:(NSString *)prompt {
6811 [prompt_ setText:prompt];
6814 - (void) setProgress:(float)progress {
6820 /* Cydia Navigation Controller Interface {{{ */
6821 @interface UINavigationController (Cydia)
6823 - (NSArray *) navigationURLCollection;
6824 - (void) unloadData;
6829 /* Cydia Tab Bar Controller {{{ */
6830 @interface CYTabBarController : UITabBarController <
6831 UITabBarControllerDelegate,
6834 _transient Database *database_;
6835 _H<RefreshBar, 1> refreshbar_;
6839 // XXX: ok, "updatedelegate_"?...
6840 _transient NSObject<CydiaDelegate> *updatedelegate_;
6842 _H<UIViewController> remembered_;
6843 _transient UIViewController *transient_;
6846 - (NSArray *) navigationURLCollection;
6847 - (void) dropBar:(BOOL)animated;
6848 - (void) beginUpdate;
6849 - (void) raiseBar:(BOOL)animated;
6851 - (void) unloadData;
6855 @implementation CYTabBarController
6857 - (void) didReceiveMemoryWarning {
6858 [super didReceiveMemoryWarning];
6860 // presenting a UINavigationController on 2.x does not update its transitionView
6861 // it thereby will not allow its topViewController to be unloaded by memory pressure
6862 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6863 UIViewController *selected([self selectedViewController]);
6864 for (UINavigationController *controller in [self viewControllers])
6865 if (controller != selected)
6866 if (UIViewController *top = [controller topViewController])
6871 - (void) setUnselectedViewController:(UIViewController *)transient {
6872 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6873 if (transient != nil) {
6874 [[[self viewControllers] objectAtIndex:0] pushViewController:transient animated:YES];
6875 [self setSelectedIndex:0];
6879 NSMutableArray *controllers = [[[self viewControllers] mutableCopy] autorelease];
6880 if (transient != nil) {
6881 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
6882 [navigation setViewControllers:[NSArray arrayWithObject:transient]];
6883 transient = navigation;
6885 if (transient_ == nil)
6886 remembered_ = [controllers objectAtIndex:0];
6887 transient_ = transient;
6888 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6889 [controllers replaceObjectAtIndex:0 withObject:transient_];
6890 [self setSelectedIndex:0];
6891 [self setViewControllers:controllers];
6892 [self concealTabBarSelection];
6893 } else if (remembered_ != nil) {
6894 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6895 transient_ = transient;
6896 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6898 [self setViewControllers:controllers];
6899 [self revealTabBarSelection];
6903 - (UIViewController *) unselectedViewController {
6907 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6908 if ([self unselectedViewController])
6909 [self setUnselectedViewController:nil];
6911 // presenting a UINavigationController on 2.x does not update its transitionView
6912 // if this view was unloaded, the tranitionView may currently be presenting nothing
6913 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6914 UINavigationController *navigation((UINavigationController *) viewController);
6915 [navigation pushViewController:[[[UIViewController alloc] init] autorelease] animated:NO];
6916 [navigation popViewControllerAnimated:NO];
6920 - (NSArray *) navigationURLCollection {
6921 NSMutableArray *items([NSMutableArray array]);
6923 // XXX: Should this deal with transient view controllers?
6924 for (id navigation in [self viewControllers]) {
6925 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6927 [items addObject:stack];
6933 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6934 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6935 [self setUnselectedViewController:nil];
6937 [super dismissModalViewControllerAnimated:YES];
6940 - (void) unloadData {
6943 for (UINavigationController *controller in [self viewControllers])
6944 [controller unloadData];
6946 if (UIViewController *selected = [self selectedViewController])
6947 [selected reloadData];
6949 if (UIViewController *unselected = [self unselectedViewController]) {
6950 [unselected unloadData];
6951 [unselected reloadData];
6956 [[NSNotificationCenter defaultCenter] removeObserver:self];
6961 - (id) initWithDatabase:(Database *)database {
6962 if ((self = [super init]) != nil) {
6963 database_ = database;
6964 [self setDelegate:self];
6966 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6967 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6969 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6973 - (void) setUpdate:(NSDate *)date {
6977 - (void) beginUpdate {
6978 [(RefreshBar *) refreshbar_ start];
6981 [updatedelegate_ retainNetworkActivityIndicator];
6985 detachNewThreadSelector:@selector(performUpdate)
6991 - (void) performUpdate {
6992 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6995 status.setDelegate(self);
6996 [database_ updateWithStatus:status];
6999 performSelectorOnMainThread:@selector(completeUpdate)
7007 - (void) stopUpdateWithSelector:(SEL)selector {
7009 [updatedelegate_ releaseNetworkActivityIndicator];
7011 [self raiseBar:YES];
7014 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7017 - (void) completeUpdate {
7020 [self stopUpdateWithSelector:@selector(reloadData)];
7023 - (void) cancelUpdate {
7024 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7027 - (void) cancelPressed {
7028 [self cancelUpdate];
7035 - (void) addProgressEvent:(CydiaProgressEvent *)event {
7036 [refreshbar_ setPrompt:[event compoundMessage]];
7039 - (bool) isProgressCancelled {
7043 - (void) setProgressCancellable:(NSNumber *)cancellable {
7044 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
7047 - (void) setProgressPercent:(NSNumber *)percent {
7048 [refreshbar_ setProgress:[percent floatValue]];
7051 - (void) setProgressStatus:(NSDictionary *)status {
7053 [self setProgressPercent:[status objectForKey:@"Percent"]];
7056 - (void) setUpdateDelegate:(id)delegate {
7057 updatedelegate_ = delegate;
7060 - (UIView *) transitionView {
7061 if (![self respondsToSelector:@selector(_transitionView)])
7062 return MSHookIvar<id>(self, "_viewControllerTransitionView");
7063 else if (kCFCoreFoundationVersionNumber < 800)
7064 return [self _transitionView];
7066 return [[[self _transitionView] superview] superview];
7069 - (void) dropBar:(BOOL)animated {
7074 UIView *transition([self transitionView]);
7075 [[self view] addSubview:refreshbar_];
7077 CGRect barframe([refreshbar_ frame]);
7079 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
7080 barframe.origin.y = 0;
7081 else if (kCFCoreFoundationVersionNumber < 800)
7082 barframe.origin.y = CYStatusBarHeight();
7084 barframe.origin.y = 0; //-barframe.size.height + CYStatusBarHeight();
7086 [refreshbar_ setFrame:barframe];
7088 CGRect viewframe = [transition frame];
7090 if (kCFCoreFoundationVersionNumber < 800) {
7092 [UIView beginAnimations:nil context:NULL];
7094 float adjust(barframe.size.height);
7095 if (kCFCoreFoundationVersionNumber >= 800)
7096 adjust -= CYStatusBarHeight();
7097 viewframe.origin.y += adjust;
7098 viewframe.size.height -= adjust;
7099 [transition setFrame:viewframe];
7102 [UIView commitAnimations];
7105 // Ensure bar has the proper width for our view, it might have changed
7106 barframe.size.width = viewframe.size.width;
7107 [refreshbar_ setFrame:barframe];
7110 - (void) raiseBar:(BOOL)animated {
7115 UIView *transition([self transitionView]);
7116 [refreshbar_ removeFromSuperview];
7118 CGRect barframe([refreshbar_ frame]);
7120 if (kCFCoreFoundationVersionNumber < 800) {
7122 [UIView beginAnimations:nil context:NULL];
7124 CGRect viewframe = [transition frame];
7125 float adjust(barframe.size.height);
7126 if (kCFCoreFoundationVersionNumber >= 800)
7127 adjust -= CYStatusBarHeight();
7128 viewframe.origin.y -= adjust;
7129 viewframe.size.height += adjust;
7130 [transition setFrame:viewframe];
7133 [UIView commitAnimations];
7137 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7138 bool dropped(dropped_);
7143 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7149 - (void) statusBarFrameChanged:(NSNotification *)notification {
7159 /* Cydia Navigation Controller Implementation {{{ */
7160 @implementation UINavigationController (Cydia)
7162 - (NSArray *) navigationURLCollection {
7163 NSMutableArray *stack([NSMutableArray array]);
7165 for (CyteViewController *controller in [self viewControllers]) {
7166 NSString *url = [[controller navigationURL] absoluteString];
7168 [stack addObject:url];
7174 - (void) reloadData {
7177 UIViewController *visible([self visibleViewController]);
7179 [visible reloadData];
7181 // on the iPad, this view controller is ALSO visible. :(
7183 if (UIViewController *top = [self topViewController])
7188 - (void) unloadData {
7189 for (CyteViewController *page in [self viewControllers])
7198 /* Cydia:// Protocol {{{ */
7199 @interface CydiaURLProtocol : NSURLProtocol {
7204 @implementation CydiaURLProtocol
7206 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7207 NSURL *url([request URL]);
7211 NSString *scheme([[url scheme] lowercaseString]);
7212 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7214 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7220 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7224 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7225 id<NSURLProtocolClient> client([self client]);
7227 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7229 NSData *data(UIImagePNGRepresentation(icon));
7231 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7232 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7233 [client URLProtocol:self didLoadData:data];
7234 [client URLProtocolDidFinishLoading:self];
7238 - (void) startLoading {
7239 id<NSURLProtocolClient> client([self client]);
7240 NSURLRequest *request([self request]);
7242 NSURL *url([request URL]);
7243 NSString *href([url absoluteString]);
7244 NSString *scheme([[url scheme] lowercaseString]);
7248 if ([scheme isEqualToString:@"cydia"])
7249 path = [href substringFromIndex:8];
7250 else if ([scheme isEqualToString:@"about"])
7251 path = [href substringFromIndex:12];
7252 else _assert(false);
7254 NSRange slash([path rangeOfString:@"/"]);
7257 if (slash.location == NSNotFound) {
7261 command = [path substringToIndex:slash.location];
7262 path = [path substringFromIndex:(slash.location + 1)];
7265 Database *database([Database sharedInstance]);
7267 if ([command isEqualToString:@"package-icon"]) {
7270 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7271 Package *package([database packageWithName:path]);
7275 UIImage *icon([package icon]);
7276 [self _returnPNGWithImage:icon forRequest:request];
7277 } else if ([command isEqualToString:@"uikit-image"]) {
7280 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7281 UIImage *icon(_UIImageWithName(path));
7282 [self _returnPNGWithImage:icon forRequest:request];
7283 } else if ([command isEqualToString:@"section-icon"]) {
7286 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7287 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7289 icon = [UIImage applicationImageNamed:@"unknown.png"];
7290 [self _returnPNGWithImage:icon forRequest:request];
7292 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7296 - (void) stopLoading {
7302 /* Section Controller {{{ */
7303 @interface SectionController : FilteredPackageListController {
7304 _H<NSString> section_;
7307 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7311 @implementation SectionController
7313 - (NSURL *) referrerURL {
7314 NSString *name = section_;
7318 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@", UI_, [name stringByAddingPercentEscapesIncludingReserved]]];
7321 - (NSURL *) navigationURL {
7322 NSString *name = section_;
7326 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", [name stringByAddingPercentEscapesIncludingReserved]]];
7329 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7332 title = UCLocalize("ALL_PACKAGES");
7333 else if (![name isEqual:@""])
7334 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7336 title = UCLocalize("NO_SECTION");
7338 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7345 /* Sections Controller {{{ */
7346 @interface SectionsController : CyteViewController <
7347 UITableViewDataSource,
7350 _transient Database *database_;
7351 _H<NSMutableArray> sections_;
7352 _H<NSMutableArray> filtered_;
7353 _H<UITableView, 2> list_;
7356 - (id) initWithDatabase:(Database *)database;
7357 - (void) editButtonClicked;
7361 @implementation SectionsController
7363 - (NSURL *) navigationURL {
7364 return [NSURL URLWithString:@"cydia://sections"];
7367 - (void) updateNavigationItem {
7368 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7369 if ([sections_ count] == 0) {
7370 [[self navigationItem] setRightBarButtonItem:nil];
7372 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7373 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7375 action:@selector(editButtonClicked)
7376 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7380 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7381 [super setEditing:editing animated:animated];
7386 [delegate_ updateData];
7388 [self updateNavigationItem];
7391 - (void) viewDidAppear:(BOOL)animated {
7392 [super viewDidAppear:animated];
7393 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7396 - (void) viewWillDisappear:(BOOL)animated {
7397 [super viewWillDisappear:animated];
7398 [self setEditing:NO];
7401 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7402 Section *section = nil;
7403 int index = [indexPath row];
7404 if (![self isEditing]) {
7407 section = [filtered_ objectAtIndex:index];
7409 section = [sections_ objectAtIndex:index];
7414 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7415 if ([self isEditing])
7416 return [sections_ count];
7418 return [filtered_ count] + 1;
7421 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7425 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7426 static NSString *reuseIdentifier = @"SectionCell";
7428 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7430 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7432 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7437 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7438 if ([self isEditing])
7441 Section *section = [self sectionAtIndexPath:indexPath];
7443 SectionController *controller = [[[SectionController alloc]
7444 initWithDatabase:database_
7445 section:[section name]
7447 [controller setDelegate:delegate_];
7449 [[self navigationController] pushViewController:controller animated:YES];
7453 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7454 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7455 [list_ setRowHeight:46];
7456 [(UITableView *) list_ setDataSource:self];
7457 [list_ setDelegate:self];
7458 [self setView:list_];
7461 - (void) viewDidLoad {
7462 [super viewDidLoad];
7464 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7467 - (void) releaseSubviews {
7473 [super releaseSubviews];
7476 - (id) initWithDatabase:(Database *)database {
7477 if ((self = [super init]) != nil) {
7478 database_ = database;
7482 - (void) reloadData {
7485 NSArray *packages = [database_ packages];
7487 sections_ = [NSMutableArray arrayWithCapacity:16];
7488 filtered_ = [NSMutableArray arrayWithCapacity:16];
7490 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7493 for (Package *package in packages) {
7494 NSString *name([package section]);
7495 NSString *key(name == nil ? @"" : name);
7499 _profile(SectionsView$reloadData$Section)
7500 section = [sections objectForKey:key];
7501 if (section == nil) {
7502 _profile(SectionsView$reloadData$Section$Allocate)
7503 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7504 [sections setObject:section forKey:key];
7509 [section addToCount];
7511 _profile(SectionsView$reloadData$Filter)
7512 if (![package valid] || ![package visible])
7520 [sections_ addObjectsFromArray:[sections allValues]];
7522 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7524 for (Section *section in (id) sections_) {
7525 size_t count([section row]);
7529 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7530 [section setCount:count];
7531 [filtered_ addObject:section];
7534 [self updateNavigationItem];
7539 - (void) editButtonClicked {
7540 [self setEditing:![self isEditing] animated:YES];
7546 /* Changes Controller {{{ */
7547 @interface ChangesController : CyteViewController <
7548 UITableViewDataSource,
7551 _transient Database *database_;
7553 _H<NSMutableArray> packages_;
7554 _H<NSMutableArray> sections_;
7555 _H<UITableView, 2> list_;
7559 - (id) initWithDatabase:(Database *)database;
7563 @implementation ChangesController
7565 - (NSURL *) navigationURL {
7566 return [NSURL URLWithString:@"cydia://changes"];
7569 - (void) viewDidAppear:(BOOL)animated {
7570 [super viewDidAppear:animated];
7571 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7574 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7575 NSInteger count([sections_ count]);
7576 return count == 0 ? 1 : count;
7579 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7580 if ([sections_ count] == 0)
7582 return [[sections_ objectAtIndex:section] name];
7585 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7586 if ([sections_ count] == 0)
7588 return [[sections_ objectAtIndex:section] count];
7591 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7592 @synchronized (database_) {
7593 if ([database_ era] != era_)
7596 NSUInteger sectionIndex([path section]);
7597 if (sectionIndex >= [sections_ count])
7599 Section *section([sections_ objectAtIndex:sectionIndex]);
7600 NSInteger row([path row]);
7601 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7604 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7605 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7607 cell = [[[PackageCell alloc] init] autorelease];
7609 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7610 [cell setPackage:package asSummary:false];
7614 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7615 Package *package([self packageAtIndexPath:path]);
7616 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[NSString stringWithFormat:@"%@/#!/changes/", UI_]] autorelease]);
7617 [view setDelegate:delegate_];
7618 [[self navigationController] pushViewController:view animated:YES];
7622 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7623 NSString *context([alert context]);
7625 if ([context isEqualToString:@"norefresh"])
7626 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7629 - (void) refreshButtonClicked {
7630 if (IsReachable("cydia.saurik.com")) {
7631 [delegate_ beginUpdate];
7632 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7634 UIAlertView *alert = [[[UIAlertView alloc]
7635 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
7636 message:@"Host Unreachable" // XXX: Localize
7638 cancelButtonTitle:UCLocalize("OK")
7639 otherButtonTitles:nil
7642 [alert setContext:@"norefresh"];
7647 - (void) upgradeButtonClicked {
7648 [delegate_ distUpgrade];
7649 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7653 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7654 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7655 [self setView:view];
7657 list_ = [[[UITableView alloc] initWithFrame:[view bounds] style:UITableViewStylePlain] autorelease];
7658 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7659 [list_ setRowHeight:73];
7660 [(UITableView *) list_ setDataSource:self];
7661 [list_ setDelegate:self];
7662 [view addSubview:list_];
7665 - (void) viewDidLoad {
7666 [super viewDidLoad];
7668 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7671 - (void) releaseSubviews {
7677 [super releaseSubviews];
7680 - (id) initWithDatabase:(Database *)database {
7681 if ((self = [super init]) != nil) {
7682 database_ = database;
7686 - (NSMutableArray *) _reloadPackages {
7687 @synchronized (database_) {
7688 era_ = [database_ era];
7689 NSArray *packages([database_ packages]);
7691 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7694 _profile(ChangesController$_reloadPackages$Filter)
7695 for (Package *package in packages)
7696 if ([package upgradableAndEssential:YES] || [package visible])
7697 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7700 _profile(ChangesController$_reloadPackages$radixSort)
7701 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7708 - (void) _reloadData {
7709 NSMutableArray *packages;
7713 UIProgressHUD *hud([delegate_ addProgressHUD]);
7714 [hud setText:UCLocalize("LOADING")];
7715 //NSLog(@"HUD:%@::%@", delegate_, hud);
7716 packages = [self yieldToSelector:@selector(_reloadPackages)];
7717 [delegate_ removeProgressHUD:hud];
7719 packages = [self _reloadPackages];
7722 @synchronized (database_) {
7723 if (era_ != [database_ era])
7726 packages_ = packages;
7727 sections_ = [NSMutableArray arrayWithCapacity:16];
7729 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7730 Section *ignored = nil;
7731 Section *section = nil;
7735 bool unseens = false;
7737 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7739 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7740 Package *package = [packages_ objectAtIndex:offset];
7742 BOOL uae = [package upgradableAndEssential:YES];
7746 time_t seen([package seen]);
7748 if (section == nil || last != seen) {
7752 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7755 _profile(ChangesController$reloadData$Allocate)
7756 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7757 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7758 [sections_ addObject:section];
7762 [section addToCount];
7763 } else if ([package ignored]) {
7764 if (ignored == nil) {
7765 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7767 [ignored addToCount];
7770 [upgradable addToCount];
7775 CFRelease(formatter);
7778 Section *last = [sections_ lastObject];
7779 size_t count = [last count];
7780 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7781 [sections_ removeLastObject];
7784 if ([ignored count] != 0)
7785 [sections_ insertObject:ignored atIndex:0];
7787 [sections_ insertObject:upgradable atIndex:0];
7791 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7792 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7793 style:UIBarButtonItemStylePlain
7795 action:@selector(upgradeButtonClicked)
7796 ] autorelease]) animated:YES];
7798 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7799 initWithTitle:UCLocalize("REFRESH")
7800 style:UIBarButtonItemStylePlain
7802 action:@selector(refreshButtonClicked)
7803 ] autorelease]) animated:YES];
7808 - (void) reloadData {
7810 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7815 /* Search Controller {{{ */
7816 @interface SearchController : FilteredPackageListController <
7819 _H<UISearchBar, 1> search_;
7823 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7824 - (void) reloadData;
7828 @implementation SearchController
7830 - (NSURL *) referrerURL {
7831 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7834 - (NSURL *) navigationURL {
7835 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7836 return [NSURL URLWithString:@"cydia://search"];
7838 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7841 - (NSArray *) termsForQuery:(NSString *)query {
7842 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7843 for (NSString *component in [query componentsSeparatedByString:@" "])
7844 if ([component length] != 0)
7845 [terms addObject:component];
7850 - (void) useSearch {
7851 [self setObject:[self termsForQuery:[search_ text]] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7856 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7857 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7862 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7863 [search_ resignFirstResponder];
7867 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7868 [search_ setText:@""];
7869 [self searchBarButtonClicked:searchBar];
7872 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7873 [self searchBarButtonClicked:searchBar];
7876 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7877 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7881 - (bool) shouldYield {
7885 - (bool) shouldBlock {
7886 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7889 - (bool) isSummarized {
7890 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7893 - (bool) showsSections {
7897 - (NSMutableArray *) _reloadPackages {
7898 NSMutableArray *packages([super _reloadPackages]);
7899 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7900 [packages radixSortUsingSelector:@selector(rank)];
7904 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7905 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[self termsForQuery:query]])) {
7906 search_ = [[[UISearchBar alloc] init] autorelease];
7907 [search_ setDelegate:self];
7910 [search_ setText:query];
7914 - (void) viewDidAppear:(BOOL)animated {
7915 [super viewDidAppear:animated];
7917 if (!searchloaded_) {
7918 searchloaded_ = YES;
7919 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7920 [search_ layoutSubviews];
7921 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7923 UITextField *textField;
7924 if ([search_ respondsToSelector:@selector(searchField)])
7925 textField = [search_ searchField];
7927 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7929 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7930 [textField setEnablesReturnKeyAutomatically:NO];
7931 [[self navigationItem] setTitleView:textField];
7934 if ([self isSummarized])
7935 [search_ becomeFirstResponder];
7938 - (void) reloadData {
7939 id object([search_ text]);
7940 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7941 object = [self termsForQuery:object];
7943 [self setObject:object];
7949 - (void) didSelectPackage:(Package *)package {
7950 [search_ resignFirstResponder];
7951 [super didSelectPackage:package];
7956 /* Package Settings Controller {{{ */
7957 @interface PackageSettingsController : CyteViewController <
7958 UITableViewDataSource,
7961 _transient Database *database_;
7963 _H<Package> package_;
7964 _H<UITableView, 2> table_;
7965 _H<UISwitch> subscribedSwitch_;
7966 _H<UISwitch> ignoredSwitch_;
7967 _H<UITableViewCell> subscribedCell_;
7968 _H<UITableViewCell> ignoredCell_;
7971 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7975 @implementation PackageSettingsController
7977 - (NSURL *) navigationURL {
7978 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7981 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7982 if (package_ == nil)
7985 if ([package_ installed] == nil)
7991 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7992 if (package_ == nil)
7995 // both sections contain just one item right now.
7999 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8003 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8005 return UCLocalize("SHOW_ALL_CHANGES_EX");
8007 return UCLocalize("IGNORE_UPGRADES_EX");
8010 - (void) onSubscribed:(id)control {
8011 bool value([control isOn]);
8012 if (package_ == nil)
8014 if ([package_ setSubscribed:value])
8015 [delegate_ updateData];
8018 - (void) _updateIgnored {
8019 const char *package([name_ UTF8String]);
8020 bool on([ignoredSwitch_ isOn]);
8022 pid_t pid(ExecFork());
8024 FILE *dpkg(popen("dpkg --set-selections", "w"));
8025 fwrite(package, strlen(package), 1, dpkg);
8028 fwrite(" hold\n", 6, 1, dpkg);
8030 fwrite(" install\n", 9, 1, dpkg);
8038 - (void) onIgnored:(id)control {
8039 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8040 [invocation setTarget:self];
8041 [invocation setSelector:@selector(_updateIgnored)];
8043 [delegate_ reloadDataWithInvocation:invocation];
8046 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8047 if (package_ == nil)
8050 switch ([indexPath section]) {
8051 case 0: return subscribedCell_;
8052 case 1: return ignoredCell_;
8061 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8062 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8063 [self setView:view];
8065 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8066 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8067 [(UITableView *) table_ setDataSource:self];
8068 [table_ setDelegate:self];
8069 [view addSubview:table_];
8071 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8072 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8073 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8075 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8076 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8077 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8079 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8080 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8081 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8082 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8084 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8085 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8086 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8087 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8090 - (void) viewDidLoad {
8091 [super viewDidLoad];
8093 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8096 - (void) releaseSubviews {
8098 subscribedCell_ = nil;
8100 ignoredSwitch_ = nil;
8101 subscribedSwitch_ = nil;
8103 [super releaseSubviews];
8106 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8107 if ((self = [super init]) != nil) {
8108 database_ = database;
8113 - (void) reloadData {
8116 package_ = [database_ packageWithName:name_];
8118 if (package_ != nil) {
8119 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8120 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8121 } // XXX: what now, G?
8123 [table_ reloadData];
8129 /* Installed Controller {{{ */
8130 @interface InstalledController : FilteredPackageListController {
8134 - (id) initWithDatabase:(Database *)database;
8136 - (void) updateRoleButton;
8137 - (void) queueStatusDidChange;
8141 @implementation InstalledController
8143 - (NSURL *) referrerURL {
8144 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8147 - (NSURL *) navigationURL {
8148 return [NSURL URLWithString:@"cydia://installed"];
8151 - (id) initWithDatabase:(Database *)database {
8152 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8153 [self updateRoleButton];
8154 [self queueStatusDidChange];
8159 - (void) queueButtonClicked {
8164 - (void) queueStatusDidChange {
8168 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8169 initWithTitle:UCLocalize("QUEUE")
8170 style:UIBarButtonItemStyleDone
8172 action:@selector(queueButtonClicked)
8175 [[self navigationItem] setLeftBarButtonItem:nil];
8181 - (void) updateRoleButton {
8182 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8183 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8184 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8185 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8187 action:@selector(roleButtonClicked)
8191 - (void) roleButtonClicked {
8192 [self setObject:[NSNumber numberWithBool:expert_]];
8196 [self updateRoleButton];
8202 /* Source Cell {{{ */
8203 @interface SourceCell : CyteTableViewCell <
8204 CyteTableViewCellDelegate
8208 _H<NSString> origin_;
8209 _H<NSString> label_;
8212 - (void) setSource:(Source *)source;
8216 @implementation SourceCell
8218 - (void) _setImage:(NSArray *)data {
8219 if ([url_ isEqual:[data objectAtIndex:0]]) {
8220 icon_ = [data objectAtIndex:1];
8221 [content_ setNeedsDisplay];
8225 - (void) _setSource:(NSURL *) url {
8226 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8228 if (NSData *data = [NSURLConnection
8229 sendSynchronousRequest:[NSURLRequest
8231 cachePolicy:NSURLRequestUseProtocolCachePolicy
8235 returningResponse:NULL
8238 if (UIImage *image = [UIImage imageWithData:data])
8239 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8244 - (void) setSource:(Source *)source {
8245 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8247 origin_ = [source name];
8248 label_ = [source rooturi];
8250 [content_ setNeedsDisplay];
8252 url_ = [source iconURL];
8253 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8256 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8257 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8258 UIView *content([self contentView]);
8259 CGRect bounds([content bounds]);
8261 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8262 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8263 [content_ setBackgroundColor:[UIColor whiteColor]];
8264 [content addSubview:content_];
8266 [content_ setDelegate:self];
8267 [content_ setOpaque:YES];
8269 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8273 - (NSString *) accessibilityLabel {
8277 - (void) drawContentRect:(CGRect)rect {
8278 bool highlighted(highlighted_);
8279 float width(rect.size.width);
8283 rect.size = [(UIImage *) icon_ size];
8285 while (rect.size.width > 32 || rect.size.height > 32) {
8286 rect.size.width /= 2;
8287 rect.size.height /= 2;
8290 rect.origin.x = 26 - rect.size.width / 2;
8291 rect.origin.y = 26 - rect.size.height / 2;
8293 [icon_ drawInRect:rect];
8296 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8301 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 61) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8305 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 61) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8310 /* Source Controller {{{ */
8311 @interface SourceController : FilteredPackageListController {
8312 _transient Source *source_;
8316 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8320 @implementation SourceController
8322 - (NSURL *) referrerURL {
8323 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sources/%@", UI_, [key_ stringByAddingPercentEscapesIncludingReserved]]];
8326 - (NSURL *) navigationURL {
8327 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8330 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8331 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8333 key_ = [source key];
8337 - (void) reloadData {
8338 source_ = [database_ sourceWithKey:key_];
8339 key_ = [source_ key];
8340 [self setObject:source_];
8342 [[self navigationItem] setTitle:[source_ label]];
8349 /* Sources Controller {{{ */
8350 @interface SourcesController : CyteViewController <
8351 UITableViewDataSource,
8354 _transient Database *database_;
8357 _H<UITableView, 2> list_;
8358 _H<NSMutableArray> sources_;
8362 _H<UIProgressHUD> hud_;
8365 //NSURLConnection *installer_;
8366 NSURLConnection *trivial_bz2_;
8367 NSURLConnection *trivial_gz_;
8368 //NSURLConnection *automatic_;
8373 - (id) initWithDatabase:(Database *)database;
8374 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8378 @implementation SourcesController
8380 - (void) _releaseConnection:(NSURLConnection *)connection {
8381 if (connection != nil) {
8382 [connection cancel];
8383 //[connection setDelegate:nil];
8384 [connection release];
8389 //[self _releaseConnection:installer_];
8390 [self _releaseConnection:trivial_gz_];
8391 [self _releaseConnection:trivial_bz2_];
8392 //[self _releaseConnection:automatic_];
8397 - (NSURL *) navigationURL {
8398 return [NSURL URLWithString:@"cydia://sources"];
8401 - (void) viewDidAppear:(BOOL)animated {
8402 [super viewDidAppear:animated];
8403 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8406 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8410 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8414 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8415 return [sources_ count];
8418 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8419 @synchronized (database_) {
8420 if ([database_ era] != era_)
8423 NSUInteger index([indexPath row]);
8424 return index < [sources_ count] ? [sources_ objectAtIndex:index] : nil;
8427 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8428 static NSString *cellIdentifier = @"SourceCell";
8430 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8431 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8432 [cell setSource:[self sourceAtIndexPath:indexPath]];
8433 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8438 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8439 Source *source = [self sourceAtIndexPath:indexPath];
8440 if (source == nil) return;
8442 SourceController *controller = [[[SourceController alloc]
8443 initWithDatabase:database_
8447 [controller setDelegate:delegate_];
8449 [[self navigationController] pushViewController:controller animated:YES];
8452 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8453 Source *source = [self sourceAtIndexPath:indexPath];
8454 return [source record] != nil;
8457 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8458 if (editingStyle == UITableViewCellEditingStyleDelete) {
8459 Source *source = [self sourceAtIndexPath:indexPath];
8460 if (source == nil) return;
8462 [Sources_ removeObjectForKey:[source key]];
8465 [delegate_ _saveConfig];
8466 [delegate_ reloadDataWithInvocation:nil];
8471 [delegate_ addTrivialSource:href_];
8474 [delegate_ syncData];
8477 - (NSString *) getWarning {
8478 NSString *href(href_);
8479 NSRange colon([href rangeOfString:@"://"]);
8480 if (colon.location != NSNotFound)
8481 href = [href substringFromIndex:(colon.location + 3)];
8482 href = [href stringByAddingPercentEscapes];
8483 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8485 NSURL *url([NSURL URLWithString:href]);
8487 NSStringEncoding encoding;
8488 NSError *error(nil);
8490 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8491 return [warning length] == 0 ? nil : warning;
8495 - (void) _endConnection:(NSURLConnection *)connection {
8496 // XXX: the memory management in this method is horribly awkward
8498 NSURLConnection **field = NULL;
8499 if (connection == trivial_bz2_)
8500 field = &trivial_bz2_;
8501 else if (connection == trivial_gz_)
8502 field = &trivial_gz_;
8503 _assert(field != NULL);
8504 [connection release];
8508 trivial_bz2_ == nil &&
8511 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8513 [delegate_ releaseNetworkActivityIndicator];
8515 [delegate_ removeProgressHUD:hud_];
8519 if (warning != nil) {
8520 UIAlertView *alert = [[[UIAlertView alloc]
8521 initWithTitle:UCLocalize("SOURCE_WARNING")
8524 cancelButtonTitle:UCLocalize("CANCEL")
8526 UCLocalize("ADD_ANYWAY"),
8530 [alert setContext:@"warning"];
8531 [alert setNumberOfRows:1];
8534 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8540 } else if (error_ != nil) {
8541 UIAlertView *alert = [[[UIAlertView alloc]
8542 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8543 message:[error_ localizedDescription]
8545 cancelButtonTitle:UCLocalize("OK")
8546 otherButtonTitles:nil
8549 [alert setContext:@"urlerror"];
8554 UIAlertView *alert = [[[UIAlertView alloc]
8555 initWithTitle:UCLocalize("NOT_REPOSITORY")
8556 message:UCLocalize("NOT_REPOSITORY_EX")
8558 cancelButtonTitle:UCLocalize("OK")
8559 otherButtonTitles:nil
8562 [alert setContext:@"trivial"];
8572 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8573 switch ([response statusCode]) {
8579 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8580 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8582 [self _endConnection:connection];
8585 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8586 [self _endConnection:connection];
8589 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8590 NSURL *url([NSURL URLWithString:href]);
8592 NSMutableURLRequest *request = [NSMutableURLRequest
8594 cachePolicy:NSURLRequestUseProtocolCachePolicy
8598 [request setHTTPMethod:method];
8600 if (Machine_ != NULL)
8601 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8603 if (UniqueID_ != nil)
8604 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8606 if ([url isCydiaSecure]) {
8607 if (UniqueID_ != nil)
8608 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8611 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8614 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8615 NSString *context([alert context]);
8617 if ([context isEqualToString:@"source"]) {
8620 NSString *href = [[alert textField] text];
8622 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8624 if (![href hasSuffix:@"/"])
8625 href_ = [href stringByAppendingString:@"/"];
8629 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8630 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8631 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8635 // XXX: this is stupid
8636 hud_ = [delegate_ addProgressHUD];
8637 [hud_ setText:UCLocalize("VERIFYING_URL")];
8638 [delegate_ retainNetworkActivityIndicator];
8647 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8648 } else if ([context isEqualToString:@"trivial"])
8649 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8650 else if ([context isEqualToString:@"urlerror"])
8651 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8652 else if ([context isEqualToString:@"warning"]) {
8655 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8664 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8669 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8670 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8671 [list_ setRowHeight:53];
8672 [(UITableView *) list_ setDataSource:self];
8673 [list_ setDelegate:self];
8674 [self setView:list_];
8677 - (void) viewDidLoad {
8678 [super viewDidLoad];
8680 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8681 [self updateButtonsForEditingStatusAnimated:NO];
8684 - (void) viewWillAppear:(BOOL)animated {
8685 [super viewWillAppear:animated];
8687 [list_ setEditing:NO];
8688 [self updateButtonsForEditingStatusAnimated:NO];
8691 - (void) releaseSubviews {
8696 [super releaseSubviews];
8699 - (id) initWithDatabase:(Database *)database {
8700 if ((self = [super init]) != nil) {
8701 database_ = database;
8705 - (void) reloadData {
8708 @synchronized (database_) {
8709 era_ = [database_ era];
8711 sources_ = [NSMutableArray arrayWithCapacity:16];
8712 [sources_ addObjectsFromArray:[database_ sources]];
8714 [sources_ sortUsingSelector:@selector(compareByName:)];
8717 int count([sources_ count]);
8719 for (int i = 0; i != count; i++) {
8720 if ([[sources_ objectAtIndex:i] record] == nil)
8728 - (void) showAddSourcePrompt {
8729 UIAlertView *alert = [[[UIAlertView alloc]
8730 initWithTitle:UCLocalize("ENTER_APT_URL")
8733 cancelButtonTitle:UCLocalize("CANCEL")
8735 UCLocalize("ADD_SOURCE"),
8739 [alert setContext:@"source"];
8741 [alert setNumberOfRows:1];
8742 [alert addTextFieldWithValue:@"http://" label:@""];
8744 UITextInputTraits *traits = [[alert textField] textInputTraits];
8745 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8746 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8747 [traits setKeyboardType:UIKeyboardTypeURL];
8748 // XXX: UIReturnKeyDone
8749 [traits setReturnKeyType:UIReturnKeyNext];
8754 - (void) addButtonClicked {
8755 [self showAddSourcePrompt];
8758 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8759 BOOL editing([list_ isEditing]);
8761 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8762 initWithTitle:UCLocalize("ADD")
8763 style:UIBarButtonItemStylePlain
8765 action:@selector(addButtonClicked)
8766 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8768 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8769 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8770 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8772 action:@selector(editButtonClicked)
8773 ] autorelease] animated:animated];
8775 if (IsWildcat_ && !editing)
8776 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8777 initWithTitle:UCLocalize("SETTINGS")
8778 style:UIBarButtonItemStylePlain
8780 action:@selector(settingsButtonClicked)
8784 - (void) settingsButtonClicked {
8785 [delegate_ showSettings];
8788 - (void) editButtonClicked {
8789 [list_ setEditing:![list_ isEditing] animated:YES];
8790 [self updateButtonsForEditingStatusAnimated:YES];
8796 /* Settings Controller {{{ */
8797 @interface SettingsController : CyteViewController <
8798 UITableViewDataSource,
8801 _transient Database *database_;
8802 // XXX: ok, "roledelegate_"?...
8803 _transient id roledelegate_;
8804 _H<UITableView, 2> table_;
8805 _H<UISegmentedControl> segment_;
8806 _H<UIView> container_;
8809 - (void) showDoneButton;
8810 - (void) resizeSegmentedControl;
8814 @implementation SettingsController
8817 table_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
8818 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8819 [table_ setDelegate:self];
8820 [(UITableView *) table_ setDataSource:self];
8821 [self setView:table_];
8823 NSArray *items = [NSArray arrayWithObjects:
8825 UCLocalize("HACKER"),
8826 UCLocalize("DEVELOPER"),
8828 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8829 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8830 [container_ addSubview:segment_];
8833 - (void) viewDidLoad {
8834 [super viewDidLoad];
8836 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8839 if ([Role_ isEqualToString:@"User"]) index = 0;
8840 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8841 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8843 [segment_ setSelectedSegmentIndex:index];
8844 [self showDoneButton];
8847 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8848 [self resizeSegmentedControl];
8851 - (void) releaseSubviews {
8856 [super releaseSubviews];
8859 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8860 if ((self = [super init]) != nil) {
8861 database_ = database;
8862 roledelegate_ = delegate;
8866 - (void) resizeSegmentedControl {
8867 CGFloat width = [[self view] frame].size.width;
8868 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8871 - (void) viewWillAppear:(BOOL)animated {
8872 [super viewWillAppear:animated];
8873 [self resizeSegmentedControl];
8876 - (void) viewDidAppear:(BOOL)animated {
8877 [super viewDidAppear:animated];
8878 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
8879 [self resizeSegmentedControl];
8882 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8883 [self resizeSegmentedControl];
8886 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8887 [self resizeSegmentedControl];
8891 NSString *role(nil);
8893 switch ([segment_ selectedSegmentIndex]) {
8894 case 0: role = @"User"; break;
8895 case 1: role = @"Hacker"; break;
8896 case 2: role = @"Developer"; break;
8901 if (![role isEqualToString:Role_]) {
8902 bool rolling(Role_ == nil);
8905 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8909 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8913 [roledelegate_ loadData];
8915 [roledelegate_ updateData];
8919 - (void) segmentChanged:(UISegmentedControl *)control {
8920 [self showDoneButton];
8923 - (void) saveAndClose {
8926 [[self navigationItem] setRightBarButtonItem:nil];
8927 [[self navigationController] dismissModalViewControllerAnimated:YES];
8930 - (void) doneButtonClicked {
8931 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8932 [spinner startAnimating];
8933 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8934 [[self navigationItem] setRightBarButtonItem:spinItem];
8936 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8939 - (void) showDoneButton {
8940 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8941 initWithTitle:UCLocalize("DONE")
8942 style:UIBarButtonItemStyleDone
8944 action:@selector(doneButtonClicked)
8945 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8948 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8949 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8953 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8957 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8958 return nil; // This method is required by the protocol.
8961 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8963 return UCLocalize("ROLE_EX");
8965 return [NSString stringWithFormat:
8966 @"%@: %@\n%@: %@\n%@: %@",
8967 UCLocalize("USER"), UCLocalize("USER_EX"),
8968 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8969 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8974 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8975 return section == 3 ? 44.0f : 0;
8978 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8979 return section == 3 ? container_ : nil;
8982 - (void) reloadData {
8985 [table_ reloadData];
8990 /* Stash Controller {{{ */
8991 @interface StashController : CyteViewController {
8992 _H<UIActivityIndicatorView> spinner_;
8993 _H<UILabel> status_;
8994 _H<UILabel> caption_;
8999 @implementation StashController
9002 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
9003 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
9004 [self setView:view];
9006 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
9008 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
9009 CGRect spinrect = [spinner_ frame];
9010 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
9011 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
9012 [spinner_ setFrame:spinrect];
9013 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
9014 [view addSubview:spinner_];
9015 [spinner_ startAnimating];
9018 captrect.size.width = [[self view] frame].size.width;
9019 captrect.size.height = 40.0f;
9020 captrect.origin.x = 0;
9021 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
9022 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
9023 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
9024 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9025 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
9026 [caption_ setTextColor:[UIColor whiteColor]];
9027 [caption_ setBackgroundColor:[UIColor clearColor]];
9028 [caption_ setShadowColor:[UIColor blackColor]];
9029 [caption_ setTextAlignment:UITextAlignmentCenter];
9030 [view addSubview:caption_];
9033 statusrect.size.width = [[self view] frame].size.width;
9034 statusrect.size.height = 30.0f;
9035 statusrect.origin.x = 0;
9036 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
9037 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
9038 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9039 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
9040 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
9041 [status_ setTextColor:[UIColor whiteColor]];
9042 [status_ setBackgroundColor:[UIColor clearColor]];
9043 [status_ setShadowColor:[UIColor blackColor]];
9044 [status_ setTextAlignment:UITextAlignmentCenter];
9045 [view addSubview:status_];
9048 - (void) releaseSubviews {
9053 [super releaseSubviews];
9059 @interface CYURLCache : SDURLCache {
9064 @implementation CYURLCache
9066 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
9069 else if ([event isEqualToString:@"no-cache"])
9071 else if ([event isEqualToString:@"store"])
9073 else if ([event isEqualToString:@"invalid"])
9075 else if ([event isEqualToString:@"memory"])
9077 else if ([event isEqualToString:@"disk"])
9079 else if ([event isEqualToString:@"miss"])
9082 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
9086 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
9087 if (NSURLResponse *response = [cached response])
9088 if (NSString *mime = [response MIMEType])
9089 if ([mime isEqualToString:@"text/cache-manifest"]) {
9090 NSURL *url([response URL]);
9093 NSLog(@"###: %@", [url absoluteString]);
9096 @synchronized (HostConfig_) {
9097 [CachedURLs_ addObject:url];
9101 [super storeCachedResponse:cached forRequest:request];
9106 @interface Cydia : UIApplication <
9107 ConfirmationControllerDelegate,
9110 UINavigationControllerDelegate,
9111 UITabBarControllerDelegate
9113 _H<UIWindow> window_;
9114 _H<CYTabBarController> tabbar_;
9115 _H<CydiaLoadingViewController> emulated_;
9117 _H<NSMutableArray> essential_;
9118 _H<NSMutableArray> broken_;
9120 Database *database_;
9122 _H<NSURL> starturl_;
9127 _H<StashController> stash_;
9136 @implementation Cydia
9138 - (void) lockSuspend {
9139 if (locked_++ == 0) {
9140 if ($SBSSetInterceptsMenuButtonForever != NULL)
9141 (*$SBSSetInterceptsMenuButtonForever)(true);
9143 [self setIdleTimerDisabled:YES];
9147 - (void) unlockSuspend {
9148 if (--locked_ == 0) {
9149 [self setIdleTimerDisabled:NO];
9151 if ($SBSSetInterceptsMenuButtonForever != NULL)
9152 (*$SBSSetInterceptsMenuButtonForever)(false);
9156 - (void) beginUpdate {
9157 [tabbar_ beginUpdate];
9161 return [tabbar_ updating];
9165 if ([broken_ count] != 0) {
9166 int count = [broken_ count];
9168 UIAlertView *alert = [[[UIAlertView alloc]
9169 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9170 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9172 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9174 UCLocalize("TEMPORARY_IGNORE"),
9178 [alert setContext:@"fixhalf"];
9179 [alert setNumberOfRows:2];
9181 } else if (!Ignored_ && [essential_ count] != 0) {
9182 int count = [essential_ count];
9184 UIAlertView *alert = [[[UIAlertView alloc]
9185 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9186 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9188 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9190 UCLocalize("UPGRADE_ESSENTIAL"),
9191 UCLocalize("COMPLETE_UPGRADE"),
9195 [alert setContext:@"upgrade"];
9200 - (void) returnToCydia {
9204 - (void) _saveConfig {
9205 @synchronized (database_) {
9212 NSString *error(nil);
9214 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9216 NSError *error(nil);
9217 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9218 NSLog(@"failure to save metadata data: %@", error);
9223 NSLog(@"failure to serialize metadata: %@", error);
9227 CydiaWriteSources();
9230 // Navigation controller for the queuing badge.
9231 - (UINavigationController *) queueNavigationController {
9232 NSArray *controllers = [tabbar_ viewControllers];
9233 return [controllers objectAtIndex:3];
9236 - (void) unloadData {
9237 [tabbar_ unloadData];
9240 - (void) _updateData {
9244 UINavigationController *navigation = [self queueNavigationController];
9246 id queuedelegate = nil;
9247 if ([[navigation viewControllers] count] > 0)
9248 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9250 [queuedelegate queueStatusDidChange];
9251 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9254 - (void) _refreshIfPossible:(NSDate *)update {
9255 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9257 bool recently = false;
9258 if (update != nil) {
9259 NSTimeInterval interval([update timeIntervalSinceNow]);
9260 if (interval <= 0 && interval > -(15*60))
9264 // Don't automatic refresh if:
9265 // - We already refreshed recently.
9266 // - We already auto-refreshed this launch.
9267 // - Auto-refresh is disabled.
9268 // - Cydia's server is not reachable
9269 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9270 // If we are cancelling, we need to make sure it knows it's already loaded.
9273 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9275 // We are going to load, so remember that.
9278 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9284 - (void) refreshIfPossible {
9285 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9288 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9289 @synchronized (self) {
9290 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9292 [hud setText:UCLocalize("RELOADING_DATA")];
9294 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9298 [essential_ removeAllObjects];
9299 [broken_ removeAllObjects];
9301 NSArray *packages([database_ packages]);
9302 for (Package *package in packages) {
9304 [broken_ addObject:package];
9305 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9306 if ([package essential] && [package installed] != nil)
9307 [essential_ addObject:package];
9312 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9315 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9316 [changesItem setBadgeValue:badge];
9317 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9318 [self setApplicationIconBadgeNumber:changes];
9321 [changesItem setBadgeValue:nil];
9322 [changesItem setAnimatedBadge:NO];
9323 [self setApplicationIconBadgeNumber:0];
9329 [self removeProgressHUD:hud];
9332 - (void) updateData {
9336 - (void) updateDataAndLoad {
9338 if ([database_ progressDelegate] == nil)
9344 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9347 - (void) disemulate {
9348 if (emulated_ == nil)
9351 [window_ addSubview:[tabbar_ view]];
9352 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9353 [window_ setRootViewController:tabbar_];
9354 [[emulated_ view] removeFromSuperview];
9356 [window_ setUserInteractionEnabled:YES];
9359 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9360 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9362 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9364 UIViewController *parent;
9365 if (emulated_ == nil)
9374 [parent presentModalViewController:navigation animated:YES];
9377 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9378 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9380 if (navigation != nil)
9381 [navigation pushViewController:progress animated:YES];
9383 [self presentModalViewController:progress force:YES];
9385 [progress invoke:invocation withTitle:title];
9389 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9390 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9393 - (void) repairWithInvocation:(NSInvocation *)invocation {
9395 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9399 - (void) repairWithSelector:(SEL)selector {
9400 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9403 - (void) reloadData {
9404 [self reloadDataWithInvocation:nil];
9405 if ([database_ progressDelegate] == nil)
9411 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9414 - (void) addSource:(NSDictionary *) source {
9415 CydiaAddSource(source);
9418 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9419 CydiaAddSource(href, distribution, sections);
9422 - (void) addTrivialSource:(NSString *)href {
9423 CydiaAddSource(href, @"./");
9426 - (void) updateValues {
9431 pkgProblemResolver *resolver = [database_ resolver];
9433 resolver->InstallProtect();
9434 if (!resolver->Resolve(true))
9439 // XXX: this is a really crappy way of doing this.
9440 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9441 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9442 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9443 if ([tabbar_ updating])
9444 [tabbar_ cancelUpdate];
9446 if (![database_ prepare])
9449 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9450 [page setDelegate:self];
9451 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9454 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9455 [tabbar_ presentModalViewController:confirm_ animated:YES];
9461 @synchronized (self) {
9466 - (void) clearPackage:(Package *)package {
9467 @synchronized (self) {
9474 - (void) installPackages:(NSArray *)packages {
9475 @synchronized (self) {
9476 for (Package *package in packages)
9483 - (void) installPackage:(Package *)package {
9484 @synchronized (self) {
9491 - (void) removePackage:(Package *)package {
9492 @synchronized (self) {
9499 - (void) distUpgrade {
9500 @synchronized (self) {
9501 if (![database_ upgrade])
9509 system("su -c /usr/bin/uicache mobile");
9514 UIProgressHUD *hud([self addProgressHUD]);
9515 [hud setText:UCLocalize("LOADING")];
9516 [self yieldToSelector:@selector(_uicache)];
9517 [self removeProgressHUD:hud];
9521 [database_ perform];
9522 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9523 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9526 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9529 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9530 [self unlockSuspend];
9533 - (void) showSettings {
9534 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9537 - (void) retainNetworkActivityIndicator {
9538 if (activity_++ == 0)
9539 [self setNetworkActivityIndicatorVisible:YES];
9542 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9546 - (void) releaseNetworkActivityIndicator {
9547 if (--activity_ == 0)
9548 [self setNetworkActivityIndicatorVisible:NO];
9551 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9556 - (void) cancelAndClear:(bool)clear {
9557 @synchronized (self) {
9569 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9570 NSString *context([alert context]);
9572 if ([context isEqualToString:@"conffile"]) {
9573 FILE *input = [database_ input];
9574 if (button == [alert cancelButtonIndex])
9575 fprintf(input, "N\n");
9576 else if (button == [alert firstOtherButtonIndex])
9577 fprintf(input, "Y\n");
9580 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9581 } else if ([context isEqualToString:@"fixhalf"]) {
9582 if (button == [alert cancelButtonIndex]) {
9583 @synchronized (self) {
9584 for (Package *broken in (id) broken_) {
9587 NSString *id = [broken id];
9588 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9589 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9590 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9591 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9597 } else if (button == [alert firstOtherButtonIndex]) {
9598 [broken_ removeAllObjects];
9602 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9603 } else if ([context isEqualToString:@"upgrade"]) {
9604 if (button == [alert firstOtherButtonIndex]) {
9605 @synchronized (self) {
9606 for (Package *essential in (id) essential_)
9607 [essential install];
9612 } else if (button == [alert firstOtherButtonIndex] + 1) {
9614 } else if (button == [alert cancelButtonIndex]) {
9618 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9622 - (void) system:(NSString *)command {
9623 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9626 system([command UTF8String]);
9632 - (void) applicationWillSuspend {
9634 [super applicationWillSuspend];
9637 - (BOOL) isSafeToSuspend {
9640 NSLog(@"isSafeToSuspend: locked_ != 0");
9645 // Use external process status API internally.
9646 // This is probably a really bad idea.
9647 // XXX: what is the point of this? does this solve anything at all?
9648 uint64_t status = 0;
9650 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9651 notify_get_state(notify_token, &status);
9652 notify_cancel(notify_token);
9657 NSLog(@"isSafeToSuspend: status != 0");
9663 NSLog(@"isSafeToSuspend: -> true");
9668 - (void) applicationSuspend:(__GSEvent *)event {
9669 if ([self isSafeToSuspend])
9670 [super applicationSuspend:event];
9673 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9674 if ([self isSafeToSuspend])
9675 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9678 - (void) _setSuspended:(BOOL)value {
9679 if ([self isSafeToSuspend])
9680 [super _setSuspended:value];
9683 - (UIProgressHUD *) addProgressHUD {
9684 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9685 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9687 [window_ setUserInteractionEnabled:NO];
9689 UIViewController *target(tabbar_);
9690 if (UIViewController *modal = [target modalViewController])
9693 [hud showInView:[target view]];
9699 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9700 [self unlockSuspend];
9702 [hud removeFromSuperview];
9703 [window_ setUserInteractionEnabled:YES];
9706 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9707 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9710 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9711 NSString *scheme([[url scheme] lowercaseString]);
9712 if ([[url absoluteString] length] <= [scheme length] + 3)
9714 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9715 NSArray *components([path componentsSeparatedByString:@"/"]);
9717 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9718 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9719 if (controller != nil)
9720 [controller setDelegate:self];
9724 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9727 NSString *base([components objectAtIndex:0]);
9729 CyteViewController *controller = nil;
9731 if ([base isEqualToString:@"url"]) {
9732 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9733 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9734 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9735 } else if (!external && [components count] == 1) {
9736 if ([base isEqualToString:@"manage"]) {
9737 controller = [[[ManageController alloc] init] autorelease];
9740 if ([base isEqualToString:@"storage"]) {
9741 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9744 if ([base isEqualToString:@"sources"]) {
9745 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9748 if ([base isEqualToString:@"home"]) {
9749 controller = [[[HomeController alloc] init] autorelease];
9752 if ([base isEqualToString:@"sections"]) {
9753 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9756 if ([base isEqualToString:@"search"]) {
9757 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9760 if ([base isEqualToString:@"changes"]) {
9761 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9764 if ([base isEqualToString:@"installed"]) {
9765 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9767 } else if ([components count] == 2) {
9768 NSString *argument = [components objectAtIndex:1];
9770 if ([base isEqualToString:@"package"]) {
9771 controller = [self pageForPackage:argument withReferrer:referrer];
9774 if (!external && [base isEqualToString:@"search"]) {
9775 controller = [[[SearchController alloc] initWithDatabase:database_ query:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9778 if (!external && [base isEqualToString:@"sections"]) {
9779 if ([argument isEqualToString:@"all"])
9781 controller = [[[SectionController alloc] initWithDatabase:database_ section:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9784 if (!external && [base isEqualToString:@"sources"]) {
9785 if ([argument isEqualToString:@"add"]) {
9786 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9787 [(SourcesController *)controller showAddSourcePrompt];
9789 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9790 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9794 if (!external && [base isEqualToString:@"launch"]) {
9795 [self launchApplicationWithIdentifier:argument suspended:NO];
9798 } else if (!external && [components count] == 3) {
9799 NSString *arg1 = [components objectAtIndex:1];
9800 NSString *arg2 = [components objectAtIndex:2];
9802 if ([base isEqualToString:@"package"]) {
9803 if ([arg2 isEqualToString:@"settings"]) {
9804 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9805 } else if ([arg2 isEqualToString:@"files"]) {
9806 if (Package *package = [database_ packageWithName:arg1]) {
9807 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9808 [(FileTable *)controller setPackage:package];
9814 [controller setDelegate:self];
9818 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9819 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9822 [tabbar_ setUnselectedViewController:page];
9827 - (void) applicationOpenURL:(NSURL *)url {
9828 [super applicationOpenURL:url];
9833 [self openCydiaURL:url forExternal:YES];
9836 - (void) applicationWillResignActive:(UIApplication *)application {
9837 // Stop refreshing if you get a phone call or lock the device.
9838 if ([tabbar_ updating])
9839 [tabbar_ cancelUpdate];
9841 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9842 [super applicationWillResignActive:application];
9845 - (void) saveState {
9846 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9847 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9848 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9854 - (void) applicationWillTerminate:(UIApplication *)application {
9858 - (void) setConfigurationData:(NSString *)data {
9859 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9861 if (!conffile_r(data)) {
9862 lprintf("E:invalid conffile\n");
9866 NSString *ofile = conffile_r[1];
9867 //NSString *nfile = conffile_r[2];
9869 UIAlertView *alert = [[[UIAlertView alloc]
9870 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9871 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9873 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9875 UCLocalize("ACCEPT_NEW_COPY"),
9876 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9880 [alert setContext:@"conffile"];
9881 [alert setNumberOfRows:2];
9885 - (void) addStashController {
9887 stash_ = [[[StashController alloc] init] autorelease];
9888 [window_ addSubview:[stash_ view]];
9891 - (void) removeStashController {
9892 [[stash_ view] removeFromSuperview];
9894 [self unlockSuspend];
9898 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9899 UpdateExternalStatus(1);
9900 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9901 UpdateExternalStatus(0);
9903 [self removeStashController];
9905 pid_t pid(ExecFork());
9907 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9908 perror("launchctl stop");
9914 - (void) setupViewControllers {
9915 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9917 NSMutableArray *items;
9918 if (kCFCoreFoundationVersionNumber < 800) {
9919 items = [NSMutableArray arrayWithObjects:
9920 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9921 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9922 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9923 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9927 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9928 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9930 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9933 items = [NSMutableArray arrayWithObjects:
9934 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home7.png"] selectedImage:[UIImage applicationImageNamed:@"home7s.png"]] autorelease],
9935 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install7.png"] selectedImage:[UIImage applicationImageNamed:@"install7s.png"]] autorelease],
9936 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes7.png"] selectedImage:[UIImage applicationImageNamed:@"changes7s.png"]] autorelease],
9937 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search7.png"] selectedImage:[UIImage applicationImageNamed:@"search7s.png"]] autorelease],
9941 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source7.png"] selectedImage:[UIImage applicationImageNamed:@"source7s.png"]] autorelease] atIndex:3];
9942 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage7.png"] selectedImage:[UIImage applicationImageNamed:@"manage7s.png"]] autorelease] atIndex:3];
9944 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage7.png"] selectedImage:[UIImage applicationImageNamed:@"manage7s.png"]] autorelease] atIndex:3];
9948 NSMutableArray *controllers([NSMutableArray array]);
9949 for (UITabBarItem *item in items) {
9950 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9951 [controller setTabBarItem:item];
9952 [controllers addObject:controller];
9954 [tabbar_ setViewControllers:controllers];
9956 [tabbar_ setUpdateDelegate:self];
9959 - (void) _sendMemoryWarningNotification {
9960 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9961 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9963 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9966 - (void) _sendMemoryWarningNotifications {
9968 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9974 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9976 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9979 - (void) applicationDidFinishLaunching:(id)unused {
9980 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9983 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9984 [self setApplicationSupportsShakeToEdit:NO];
9986 @synchronized (HostConfig_) {
9987 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9990 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9991 initWithMemoryCapacity:524288
9992 diskCapacity:10485760
9993 diskPath:[NSString stringWithFormat:@"%@/SDURLCache", Cache_]
9996 [CydiaWebViewController _initialize];
9998 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
10000 // this would disallow http{,s} URLs from accessing this data
10001 //[WebView registerURLSchemeAsLocal:@"cydia"];
10003 Font12_ = [UIFont systemFontOfSize:12];
10004 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
10005 Font14_ = [UIFont systemFontOfSize:14];
10006 Font18_ = [UIFont systemFontOfSize:18];
10007 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
10008 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
10010 essential_ = [NSMutableArray arrayWithCapacity:4];
10011 broken_ = [NSMutableArray arrayWithCapacity:4];
10013 // XXX: I really need this thing... like, seriously... I'm sorry
10014 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
10016 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
10017 [window_ orderFront:self];
10018 [window_ makeKey:self];
10019 [window_ setHidden:NO];
10021 if (false) stash: {
10022 [self addStashController];
10023 // XXX: this would be much cleaner as a yieldToSelector:
10024 // that way the removeStashController could happen right here inline
10025 // we also could no longer require the useless stash_ field anymore
10026 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
10031 int error(stat("/", &root));
10032 _assert(error != -1);
10034 #define Stash_(path) do { \
10035 struct stat folder; \
10036 int error(lstat((path), &folder)); \
10037 if (error != -1 && ( \
10038 folder.st_dev == root.st_dev && \
10039 S_ISDIR(folder.st_mode) \
10040 ) || error == -1 && ( \
10041 errno == ENOENT || \
10046 Stash_("/Applications");
10047 Stash_("/Library/Ringtones");
10048 Stash_("/Library/Wallpaper");
10049 //Stash_("/usr/bin");
10050 Stash_("/usr/include");
10051 Stash_("/usr/lib/pam");
10052 Stash_("/usr/share");
10053 //Stash_("/var/lib");
10055 database_ = [Database sharedInstance];
10056 [database_ setDelegate:self];
10058 [window_ setUserInteractionEnabled:NO];
10059 [self setupViewControllers];
10061 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
10062 [window_ addSubview:[emulated_ view]];
10063 if ([window_ respondsToSelector:@selector(setRootViewController:)])
10064 [window_ setRootViewController:emulated_];
10066 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
10070 - (NSArray *) defaultStartPages {
10071 NSMutableArray *standard = [NSMutableArray array];
10072 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
10073 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
10074 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
10076 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
10078 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
10079 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
10081 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10085 - (void) loadData {
10087 if (Role_ == nil) {
10088 [window_ setUserInteractionEnabled:YES];
10089 [self showSettings];
10092 if ([emulated_ modalViewController] != nil)
10093 [emulated_ dismissModalViewControllerAnimated:YES];
10094 [window_ setUserInteractionEnabled:NO];
10097 [self reloadDataWithInvocation:nil];
10098 [self refreshIfPossible];
10103 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
10104 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
10105 int standardIndex = 0;
10106 NSArray *standard = [self defaultStartPages];
10113 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
10114 if (valid && closed != nil) {
10115 NSTimeInterval interval([closed timeIntervalSinceNow]);
10116 // XXX: Is 30 minutes the optimal time here?
10117 if (interval <= -(30*60))
10121 if (valid && [saved count] != [standard count])
10125 for (unsigned int i = 0; i < [standard count]; i++) {
10126 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10127 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10128 // but it's good enough for now.
10129 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10136 NSArray *items = nil;
10138 [tabbar_ setSelectedIndex:savedIndex];
10141 [tabbar_ setSelectedIndex:standardIndex];
10145 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10146 NSArray *stack = [items objectAtIndex:tab];
10147 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10148 NSMutableArray *current = [NSMutableArray array];
10150 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10151 NSString *addr = [stack objectAtIndex:nav];
10152 NSURL *url = [NSURL URLWithString:addr];
10153 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10155 [current addObject:page];
10158 [navigation setViewControllers:current];
10161 // (Try to) show the startup URL.
10162 if (starturl_ != nil) {
10163 [self openCydiaURL:starturl_ forExternal:NO];
10168 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10169 if (item != nil && IsWildcat_) {
10170 [sheet showFromBarButtonItem:item animated:YES];
10172 [sheet showInView:window_];
10176 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10177 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10178 [progress setTitle:task];
10179 [progress addProgressEvent:event];
10182 - (void) addProgressEventForTask:(NSArray *)data {
10183 CydiaProgressEvent *event([data objectAtIndex:0]);
10184 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10185 [self addProgressEvent:event forTask:task];
10188 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10189 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10195 id Alloc_(id self, SEL selector) {
10196 id object = alloc_(self, selector);
10197 lprintf("[%s]A-%p\n", self->isa->name, object);
10202 id Dealloc_(id self, SEL selector) {
10203 id object = dealloc_(self, selector);
10204 lprintf("[%s]D-%p\n", self->isa->name, object);
10208 static NSSet *MobilizedFiles_;
10210 static NSURL *MobilizeURL(NSURL *url) {
10211 NSString *path([url path]);
10212 if ([path hasPrefix:@"/var/root/"]) {
10213 NSString *file([path substringFromIndex:10]);
10214 if ([MobilizedFiles_ containsObject:file])
10215 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10221 Class $CFXPreferencesPropertyListSource;
10222 @class CFXPreferencesPropertyListSource;
10224 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10225 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10226 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10227 url = MobilizeURL(url);
10228 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10229 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10235 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10236 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10237 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10238 url = MobilizeURL(url);
10239 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10240 //NSLog(@"%@ %@", [url absoluteString], value);
10246 Class $NSURLConnection;
10248 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10249 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10251 NSURL *url([copy URL]);
10253 NSString *host([url host]);
10254 NSString *scheme([[url scheme] lowercaseString]);
10256 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10258 @synchronized (HostConfig_) {
10259 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10260 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10261 [copy setHTTPShouldUsePipelining:YES];
10263 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10264 if ([control isEqualToString:@"max-age=0"])
10265 if ([CachedURLs_ containsObject:url]) {
10267 NSLog(@"~~~: %@", url);
10270 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10272 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10273 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10274 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10278 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10284 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10285 CGSize size([[UIScreen mainScreen] bounds].size);
10286 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10287 if ([$WAKWindow hasLandscapeOrientation])
10288 std::swap(size.width, size.height);*/
10292 Class $NSUserDefaults;
10294 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10295 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10296 return [NSString stringWithFormat:@"%@/LocalStorage", Cache_];
10297 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10300 int main(int argc, char *argv[]) {
10301 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10305 UpdateExternalStatus(0);
10307 UIScreen *screen([UIScreen mainScreen]);
10308 if ([screen respondsToSelector:@selector(scale)])
10309 ScreenScale_ = [screen scale];
10313 UIDevice *device([UIDevice currentDevice]);
10314 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10315 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10316 if (idiom == UIUserInterfaceIdiomPad)
10320 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10322 Pcre pattern("^([0-9]+\\.[0-9]+)");
10324 if (pattern([device systemVersion]))
10325 Firmware_ = pattern[1];
10326 if (pattern(Cydia_))
10327 Major_ = pattern[1];
10329 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10331 HostConfig_ = [[[NSObject alloc] init] autorelease];
10332 @synchronized (HostConfig_) {
10333 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10334 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10335 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10336 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10337 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10340 NSString *ui(@"ui/ios");
10342 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10343 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10344 UI_ = CydiaURL(ui);
10346 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10348 MobilizedFiles_ = [NSMutableSet setWithObjects:
10349 @"Library/Preferences/com.apple.Accessibility.plist",
10350 @"Library/Preferences/com.apple.preferences.sounds.plist",
10353 /* Library Hacks {{{ */
10354 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10356 $WAKWindow = objc_getClass("WAKWindow");
10357 if ($WAKWindow != NULL)
10358 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10359 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10361 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10363 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10364 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10365 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10366 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10369 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10370 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10371 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10372 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10375 $NSURLConnection = objc_getClass("NSURLConnection");
10376 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10377 if (NSURLConnection$init$ != NULL) {
10378 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10379 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10382 $NSUserDefaults = objc_getClass("NSUserDefaults");
10383 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10384 if (NSUserDefaults$objectForKey$ != NULL) {
10385 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10386 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10389 /* Set Locale {{{ */
10390 Locale_ = CFLocaleCopyCurrent();
10391 Languages_ = [NSLocale preferredLanguages];
10393 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10394 //NSLog(@"%@", [Languages_ description]);
10397 if (Locale_ != NULL)
10398 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10399 else if (Languages_ != nil && [Languages_ count] != 0)
10400 lang = [[Languages_ objectAtIndex:0] UTF8String];
10402 // XXX: consider just setting to C and then falling through?
10405 if (lang != NULL) {
10406 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10407 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10410 NSLog(@"Setting Language: %s", lang);
10412 if (lang != NULL) {
10413 setenv("LANG", lang, true);
10414 std::setlocale(LC_ALL, lang);
10418 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10420 /* Parse Arguments {{{ */
10421 bool substrate(false);
10427 for (int argi(1); argi != argc; ++argi)
10428 if (strcmp(argv[argi], "--") == 0) {
10430 argv[argi] = argv[0];
10436 for (int argi(1); argi != arge; ++argi)
10437 if (strcmp(args[argi], "--substrate") == 0)
10440 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10444 App_ = [[NSBundle mainBundle] bundlePath];
10450 if (access("/var/mobile/Library/Keyboard/UserDictionary.sqlite", F_OK) == 0)
10451 system("mkdir -p /var/root/Library/Keyboard; cp -af /var/mobile/Library/Keyboard/UserDictionary.sqlite /var/root/Library/Keyboard/");
10453 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/root"] retain];
10455 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10456 alloc_ = alloc->method_imp;
10457 alloc->method_imp = (IMP) &Alloc_;*/
10459 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10460 dealloc_ = dealloc->method_imp;
10461 dealloc->method_imp = (IMP) &Dealloc_;*/
10463 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10464 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10466 /* System Information {{{ */
10470 size = sizeof(maxproc);
10471 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10472 perror("sysctlbyname(\"kern.maxproc\", ?)");
10473 else if (maxproc < 64) {
10475 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10476 perror("sysctlbyname(\"kern.maxproc\", #)");
10479 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10480 char *osversion = new char[size];
10481 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10482 perror("sysctlbyname(\"kern.osversion\", ?)");
10484 System_ = [NSString stringWithUTF8String:osversion];
10486 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10487 char *machine = new char[size];
10488 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10489 perror("sysctlbyname(\"hw.machine\", ?)");
10491 Machine_ = machine;
10493 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10494 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10495 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10497 UniqueID_ = UniqueIdentifier(device);
10499 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10500 Product_ = [info objectForKey:@"SafariProductVersion"];
10501 Safari_ = [info objectForKey:@"CFBundleVersion"];
10504 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10506 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10507 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10508 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10509 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10510 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10511 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10513 UserAgent_ = agent;
10515 /* Load Database {{{ */
10517 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10519 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10521 if (Metadata_ == NULL)
10522 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10524 Settings_ = [Metadata_ objectForKey:@"Settings"];
10526 Packages_ = [Metadata_ objectForKey:@"Packages"];
10528 Values_ = [Metadata_ objectForKey:@"Values"];
10529 Sections_ = [Metadata_ objectForKey:@"Sections"];
10530 Sources_ = [Metadata_ objectForKey:@"Sources"];
10532 Token_ = [Metadata_ objectForKey:@"Token"];
10534 Version_ = [Metadata_ objectForKey:@"Version"];
10537 if (Settings_ != nil)
10538 Role_ = [Settings_ objectForKey:@"Role"];
10540 if (Values_ == nil) {
10541 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10542 [Metadata_ setObject:Values_ forKey:@"Values"];
10545 if (Sections_ == nil) {
10546 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10547 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10550 if (Sources_ == nil) {
10551 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10552 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10555 if (Version_ == nil) {
10556 Version_ = [NSNumber numberWithUnsignedInt:0];
10557 [Metadata_ setObject:Version_ forKey:@"Version"];
10560 if ([Version_ unsignedIntValue] == 0) {
10561 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10562 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10563 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10564 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10566 Version_ = [NSNumber numberWithUnsignedInt:1];
10567 [Metadata_ setObject:Version_ forKey:@"Version"];
10569 [Metadata_ removeObjectForKey:@"LastUpdate"];
10575 CydiaWriteSources();
10578 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10581 if (Packages_ != nil) {
10583 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10587 [Metadata_ removeObjectForKey:@"Packages"];
10593 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10595 #define MobileSubstrate_(name) \
10596 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10597 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10598 if (handle == NULL) \
10599 NSLog(@"%s", dlerror()); \
10602 MobileSubstrate_(Activator)
10603 MobileSubstrate_(libstatusbar)
10604 MobileSubstrate_(SimulatedKeyEvents)
10605 MobileSubstrate_(WinterBoard)
10607 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10608 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10610 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10612 if (access("/User", F_OK) != 0 || version != 6) {
10614 system("/usr/libexec/cydia/firmware.sh");
10618 _assert([[NSFileManager defaultManager]
10619 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10620 withIntermediateDirectories:YES
10625 if (access("/tmp/cydia.chk", F_OK) == 0) {
10626 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10627 _assert(errno == ENOENT);
10628 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10629 _assert(errno == ENOENT);
10632 /* APT Initialization {{{ */
10633 _assert(pkgInitConfig(*_config));
10634 _assert(pkgInitSystem(*_config, _system));
10637 _config->Set("APT::Acquire::Translation", lang);
10639 // XXX: this timeout might be important :(
10640 //_config->Set("Acquire::http::Timeout", 15);
10642 _config->Set("Acquire::http::MaxParallel", 3);
10644 /* Color Choices {{{ */
10645 space_ = CGColorSpaceCreateDeviceRGB();
10647 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10648 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10649 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10650 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10651 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10652 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10653 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10654 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10655 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10656 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10658 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10659 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10661 /* UIKit Configuration {{{ */
10662 // XXX: I have a feeling this was important
10663 //UIKeyboardDisableAutomaticAppearance();
10666 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10668 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10669 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10670 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10672 PulseInterval_ = fast ? 50000 : 500000;
10674 Colon_ = UCLocalize("COLON_DELIMITED");
10675 Elision_ = UCLocalize("ELISION");
10676 Error_ = UCLocalize("ERROR");
10677 Warning_ = UCLocalize("WARNING");
10680 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10682 CGColorSpaceRelease(space_);
10683 CFRelease(Locale_);