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/TabBarController.h"
116 #include "CyteKit/WebScriptObject-Cyte.h"
117 #include "CyteKit/WebViewController.h"
118 #include "CyteKit/WebViewTableViewCell.h"
119 #include "CyteKit/stringWithUTF8Bytes.h"
121 #include "Cydia/MIMEAddress.h"
122 #include "Cydia/LoadingViewController.h"
123 #include "Cydia/ProgressEvent.h"
125 #include "SDURLCache/SDURLCache.h"
132 #define _timestamp ({ \
134 gettimeofday(&tv, NULL); \
135 tv.tv_sec * 1000000 + tv.tv_usec; \
138 typedef std::vector<class ProfileTime *> TimeList;
148 ProfileTime(const char *name) :
152 times_.push_back(this);
155 void AddTime(uint64_t time) {
162 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
174 ProfileTimer(ProfileTime &time) :
181 time_.AddTime(_timestamp - start_);
186 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
188 std::cerr << "========" << std::endl;
191 #define _profile(name) { \
192 static ProfileTime name(#name); \
193 ProfileTimer _ ## name(name);
198 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
199 #define synchronized(lock) \
200 synchronized(static_cast<NSObject *>(lock))
202 extern NSString *Cydia_;
204 #define lprintf(args...) fprintf(stderr, args)
207 #define TraceLogging (1 && !ForRelease)
208 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
209 #define ProfileTimes (0 && !ForRelease)
210 #define ForSaurik (0 && !ForRelease)
211 #define LogBrowser (0 && !ForRelease)
212 #define TrackResize (0 && !ForRelease)
213 #define ManualRefresh (1 && !ForRelease)
214 #define ShowInternals (0 && !ForRelease)
215 #define AlwaysReload (0 && !ForRelease)
216 #define TryIndexedCollation (0 && !ForRelease)
220 #define _trace(args...)
225 #define _profile(name) {
228 #define PrintTimes() do {} while (false)
231 // Hash Functions/Structures {{{
232 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
240 static NSString *Colon_;
242 static NSString *Error_;
243 static NSString *Warning_;
245 static NSString *Cache_;
247 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
249 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
251 static NSString *UniqueIdentifier(UIDevice *device = nil) {
252 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
253 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
255 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
258 static bool IsReachable(const char *name) {
259 SCNetworkReachabilityFlags flags; {
260 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
261 SCNetworkReachabilityGetFlags(reachability, &flags);
262 CFRelease(reachability);
265 // XXX: this elaborate mess is what Apple is using to determine this? :(
266 // XXX: do we care if the user has to intervene? maybe that's ok?
268 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
269 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
270 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
271 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
272 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
273 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
278 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
280 static _finline NSString *CydiaURL(NSString *path) {
282 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
283 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
284 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
285 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
286 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
288 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
291 static void ReapZombie(pid_t pid) {
294 if (waitpid(pid, &status, 0) == -1)
300 static _finline void UpdateExternalStatus(uint64_t newStatus) {
302 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
303 notify_set_state(notify_token, newStatus);
304 notify_cancel(notify_token);
306 notify_post("com.saurik.Cydia.status");
309 static CGFloat CYStatusBarHeight() {
310 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
311 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
314 /* NSForcedOrderingSearch doesn't work on the iPhone */
315 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
316 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
317 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
319 /* Insertion Sort {{{ */
321 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
322 const char *ptr = (const char *)list;
324 CFIndex half = count / 2;
325 const char *probe = ptr + elementSize * half;
326 CFComparisonResult cr = comparator(element, probe, context);
327 if (0 == cr) return (probe - (const char *)list) / elementSize;
328 ptr = (cr < 0) ? ptr : probe + elementSize;
329 count = (cr < 0) ? half : (half + (count & 1) - 1);
331 return (ptr - (const char *)list) / elementSize;
334 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
335 const char *ptr = (const char *)list;
337 CFIndex half = count / 2;
338 const char *probe = ptr + elementSize * half;
339 CFComparisonResult cr = comparator(element, probe, context);
340 if (0 == cr) return (probe - (const char *)list) / elementSize;
341 ptr = (cr < 0) ? ptr : probe + elementSize;
342 count = (cr < 0) ? half : (half + (count & 1) - 1);
344 return (ptr - (const char *)list) / elementSize;
347 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
348 if (range.length == 0)
350 const void **values(new const void *[range.length]);
351 CFArrayGetValues(array, range, values);
353 #if HistogramInsertionSort > 0
354 uint32_t total(0), *offsets(new uint32_t[range.length]);
357 for (CFIndex index(1); index != range.length; ++index) {
358 const void *value(values[index]);
359 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
360 CFIndex correct(index);
361 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
362 #if HistogramInsertionSort > 1
363 NSLog(@"%@ < %@", value, values[correct - 1]);
368 if (correct != index) {
369 size_t offset(index - correct);
370 #if HistogramInsertionSort
374 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
376 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
377 values[correct] = value;
381 CFArrayReplaceValues(array, range, values, range.length);
384 #if HistogramInsertionSort > 0
385 for (CFIndex index(0); index != range.length; ++index)
386 if (offsets[index] != 0)
387 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
388 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
395 /* Apple Bug Fixes {{{ */
396 @implementation UIWebDocumentView (Cydia)
398 - (void) _setScrollerOffset:(CGPoint)offset {
399 UIScroller *scroller([self _scroller]);
401 CGSize size([scroller contentSize]);
402 CGSize bounds([scroller bounds].size);
405 max.x = size.width - bounds.width;
406 max.y = size.height - bounds.height;
414 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
415 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
417 [scroller setOffset:offset];
423 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
424 size_t length([self length] - state->state);
427 else if (length > count)
429 for (size_t i(0); i != length; ++i)
430 objects[i] = [self item:state->state++];
431 state->itemsPtr = objects;
432 state->mutationsPtr = (unsigned long *) self;
436 /* Cydia NSString Additions {{{ */
437 @interface NSString (Cydia)
438 - (NSComparisonResult) compareByPath:(NSString *)other;
439 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
442 @implementation NSString (Cydia)
444 - (NSComparisonResult) compareByPath:(NSString *)other {
445 NSString *prefix = [self commonPrefixWithString:other options:0];
446 size_t length = [prefix length];
448 NSRange lrange = NSMakeRange(length, [self length] - length);
449 NSRange rrange = NSMakeRange(length, [other length] - length);
451 lrange = [self rangeOfString:@"/" options:0 range:lrange];
452 rrange = [other rangeOfString:@"/" options:0 range:rrange];
454 NSComparisonResult value;
456 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
457 value = NSOrderedSame;
458 else if (lrange.location == NSNotFound)
459 value = NSOrderedAscending;
460 else if (rrange.location == NSNotFound)
461 value = NSOrderedDescending;
463 value = NSOrderedSame;
465 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
466 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
467 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
468 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
470 NSComparisonResult result = [lpath compare:rpath];
471 return result == NSOrderedSame ? value : result;
474 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
475 return [(id)CFURLCreateStringByAddingPercentEscapes(
480 kCFStringEncodingUTF8
487 /* C++ NSString Wrapper Cache {{{ */
488 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
489 return size == 0 ? NULL :
490 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
491 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
494 static _finline CFStringRef CYStringCreate(const char *data) {
495 return CYStringCreate(data, strlen(data));
504 _finline void clear_() {
505 if (cache_ != NULL) {
512 _finline bool empty() const {
516 _finline size_t size() const {
520 _finline char *data() const {
524 _finline void clear() {
529 _finline CYString() :
536 _finline ~CYString() {
540 void operator =(const CYString &rhs) {
544 if (rhs.cache_ == nil)
547 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
550 void copy(apr_pool_t *pool) {
551 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
552 memcpy(temp, data_, size_);
557 void set(apr_pool_t *pool, const char *data, size_t size) {
563 data_ = const_cast<char *>(data);
571 _finline void set(apr_pool_t *pool, const char *data) {
572 set(pool, data, data == NULL ? 0 : strlen(data));
575 _finline void set(apr_pool_t *pool, const std::string &rhs) {
576 set(pool, rhs.data(), rhs.size());
579 bool operator ==(const CYString &rhs) const {
580 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
583 _finline operator CFStringRef() {
585 cache_ = CYStringCreate(data_, size_);
589 _finline operator id() {
590 return (NSString *) static_cast<CFStringRef>(*this);
593 _finline operator const char *() {
594 return reinterpret_cast<const char *>(data_);
598 /* C++ NSString Algorithm Adapters {{{ */
600 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
603 struct NSStringMapHash :
604 std::unary_function<NSString *, size_t>
606 _finline size_t operator ()(NSString *value) const {
607 return CFStringHashNSString((CFStringRef) value);
611 struct NSStringMapLess :
612 std::binary_function<NSString *, NSString *, bool>
614 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
615 return [lhs compare:rhs] == NSOrderedAscending;
619 struct NSStringMapEqual :
620 std::binary_function<NSString *, NSString *, bool>
622 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
623 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
624 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
625 //[lhs isEqualToString:rhs];
630 /* CoreGraphics Primitives {{{ */
635 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
636 CGFloat color[] = {red, green, blue, alpha};
637 return CGColorCreate(space, color);
646 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
647 color_(Create_(space, red, green, blue, alpha))
649 Set(space, red, green, blue, alpha);
654 CGColorRelease(color_);
661 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
663 color_ = Create_(space, red, green, blue, alpha);
666 operator CGColorRef() {
672 /* Random Global Variables {{{ */
673 static int PulseInterval_ = 500000;
675 static const NSString *UI_;
678 static bool RestartSubstrate_;
679 static NSArray *Finishes_;
681 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
682 #define NotifyConfig_ "/etc/notify.conf"
684 static bool Queuing_;
686 static CYColor Blue_;
687 static CYColor Blueish_;
688 static CYColor Black_;
689 static CYColor Folder_;
691 static CYColor White_;
692 static CYColor Gray_;
693 static CYColor Green_;
694 static CYColor Purple_;
695 static CYColor Purplish_;
697 static UIColor *InstallingColor_;
698 static UIColor *RemovingColor_;
700 static NSString *App_;
702 static BOOL Advanced_;
703 static BOOL Ignored_;
705 static _H<UIFont> Font12_;
706 static _H<UIFont> Font12Bold_;
707 static _H<UIFont> Font14_;
708 static _H<UIFont> Font18_;
709 static _H<UIFont> Font18Bold_;
710 static _H<UIFont> Font22Bold_;
712 static const char *Machine_ = NULL;
713 static _H<NSString> System_;
714 static NSString *SerialNumber_ = nil;
715 static NSString *ChipID_ = nil;
716 static NSString *BBSNum_ = nil;
717 static _H<NSString> Token_;
718 static _H<NSString> UniqueID_;
719 static _H<NSString> UserAgent_;
720 static _H<NSString> Product_;
721 static _H<NSString> Safari_;
723 static CFLocaleRef Locale_;
724 static NSArray *Languages_;
725 static CGColorSpaceRef space_;
727 static NSDictionary *SectionMap_;
728 static NSMutableDictionary *Metadata_;
729 static _transient NSMutableDictionary *Settings_;
730 static _transient NSString *Role_;
731 static _transient NSMutableDictionary *Packages_;
732 static _transient NSMutableDictionary *Values_;
733 static _transient NSMutableDictionary *Sections_;
734 _H<NSMutableDictionary> Sources_;
735 static _transient NSNumber *Version_;
740 static CGFloat ScreenScale_;
741 static NSString *Idiom_;
742 static _H<NSString> Firmware_;
743 static NSString *Major_;
745 static _H<NSMutableDictionary> SessionData_;
746 static _H<NSObject> HostConfig_;
747 static _H<NSMutableSet> BridgedHosts_;
748 static _H<NSMutableSet> TokenHosts_;
749 static _H<NSMutableSet> InsecureHosts_;
750 static _H<NSMutableSet> PipelinedHosts_;
751 static _H<NSMutableSet> CachedURLs_;
753 static NSString *kCydiaProgressEventTypeError = @"Error";
754 static NSString *kCydiaProgressEventTypeInformation = @"Information";
755 static NSString *kCydiaProgressEventTypeStatus = @"Status";
756 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
759 /* Display Helpers {{{ */
760 inline float Interpolate(float begin, float end, float fraction) {
761 return (end - begin) * fraction + begin;
764 static _finline const char *StripVersion_(const char *version) {
765 const char *colon(strchr(version, ':'));
766 return colon == NULL ? version : colon + 1;
769 NSString *LocalizeSection(NSString *section) {
770 static Pcre title_r("^(.*?) \\((.*)\\)$");
771 if (title_r(section)) {
772 NSString *parent(title_r[1]);
773 NSString *child(title_r[2]);
775 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
776 LocalizeSection(parent),
777 LocalizeSection(child)
781 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
784 NSString *Simplify(NSString *title) {
785 const char *data = [title UTF8String];
786 size_t size = [title length];
788 static Pcre square_r("^\\[(.*)\\]$");
789 if (square_r(data, size))
790 return Simplify(square_r[1]);
792 static Pcre paren_r("^\\((.*)\\)$");
793 if (paren_r(data, size))
794 return Simplify(paren_r[1]);
796 static Pcre title_r("^(.*?) \\((.*)\\)$");
797 if (title_r(data, size))
798 return Simplify(title_r[1]);
804 NSString *GetLastUpdate() {
805 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
808 return UCLocalize("NEVER_OR_UNKNOWN");
810 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
811 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
813 CFRelease(formatter);
815 return [(NSString *) formatted autorelease];
818 bool isSectionVisible(NSString *section) {
819 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
820 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
821 return hidden == nil || ![hidden boolValue];
824 static NSObject *CYIOGetValue(const char *path, NSString *property) {
825 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
826 if (entry == MACH_PORT_NULL)
829 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
830 IOObjectRelease(entry);
834 return [(id) value autorelease];
837 static NSString *CYHex(NSData *data, bool reverse = false) {
841 size_t length([data length]);
842 uint8_t bytes[length];
843 [data getBytes:bytes];
845 char string[length * 2 + 1];
846 for (size_t i(0); i != length; ++i)
847 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
849 return [NSString stringWithUTF8String:string];
854 /* Delegate Prototypes {{{ */
857 @class CydiaProgressEvent;
859 @protocol DatabaseDelegate
860 - (void) repairWithSelector:(SEL)selector;
861 - (void) setConfigurationData:(NSString *)data;
862 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
865 @class CYPackageController;
867 @protocol CydiaDelegate
868 - (void) returnToCydia;
870 - (void) retainNetworkActivityIndicator;
871 - (void) releaseNetworkActivityIndicator;
872 - (void) clearPackage:(Package *)package;
873 - (void) installPackage:(Package *)package;
874 - (void) installPackages:(NSArray *)packages;
875 - (void) removePackage:(Package *)package;
876 - (void) beginUpdate;
878 - (void) distUpgrade;
881 - (void) _saveConfig;
883 - (void) addSource:(NSDictionary *)source;
884 - (void) addTrivialSource:(NSString *)href;
885 - (void) showSettings;
886 - (UIProgressHUD *) addProgressHUD;
887 - (void) removeProgressHUD:(UIProgressHUD *)hud;
888 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
889 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
893 /* Status Delegation {{{ */
895 public pkgAcquireStatus
898 _transient NSObject<ProgressDelegate> *delegate_;
908 void setDelegate(NSObject<ProgressDelegate> *delegate) {
909 delegate_ = delegate;
912 NSObject<ProgressDelegate> *getDelegate() const {
916 virtual bool MediaChange(std::string media, std::string drive) {
920 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
924 virtual void Fetch(pkgAcquire::ItemDesc &item) {
925 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
926 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
927 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
930 virtual void Done(pkgAcquire::ItemDesc &item) {
931 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
932 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
933 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
936 virtual void Fail(pkgAcquire::ItemDesc &item) {
938 item.Owner->Status == pkgAcquire::Item::StatIdle ||
939 item.Owner->Status == pkgAcquire::Item::StatDone
943 std::string &error(item.Owner->ErrorText);
947 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
948 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
951 virtual bool Pulse(pkgAcquire *Owner) {
952 bool value = pkgAcquireStatus::Pulse(Owner);
955 double(CurrentBytes + CurrentItems) /
956 double(TotalBytes + TotalItems)
959 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
960 [NSNumber numberWithDouble:percent], @"Percent",
962 [NSNumber numberWithDouble:CurrentBytes], @"Current",
963 [NSNumber numberWithDouble:TotalBytes], @"Total",
964 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
965 nil] waitUntilDone:YES];
967 if (value && ![delegate_ isProgressCancelled])
975 _finline bool WasCancelled() const {
979 virtual void Start() {
980 pkgAcquireStatus::Start();
981 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
984 virtual void Stop() {
985 pkgAcquireStatus::Stop();
986 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
987 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
991 /* Database Interface {{{ */
992 typedef std::map< unsigned long, _H<Source> > SourceMap;
994 @interface Database : NSObject {
1000 pkgCacheFile cache_;
1001 pkgDepCache::Policy *policy_;
1002 pkgRecords *records_;
1003 pkgProblemResolver *resolver_;
1004 pkgAcquire *fetcher_;
1006 SPtr<pkgPackageManager> manager_;
1007 pkgSourceList *list_;
1009 SourceMap sourceMap_;
1010 _H<NSMutableArray> sourceList_;
1012 CFMutableArrayRef packages_;
1014 _transient NSObject<DatabaseDelegate> *delegate_;
1015 _transient NSObject<ProgressDelegate> *progress_;
1023 std::map<const char *, _H<NSString> > sections_;
1026 + (Database *) sharedInstance;
1029 - (void) _readCydia:(NSNumber *)fd;
1030 - (void) _readStatus:(NSNumber *)fd;
1031 - (void) _readOutput:(NSNumber *)fd;
1035 - (Package *) packageWithName:(NSString *)name;
1037 - (pkgCacheFile &) cache;
1038 - (pkgDepCache::Policy *) policy;
1039 - (pkgRecords *) records;
1040 - (pkgProblemResolver *) resolver;
1041 - (pkgAcquire &) fetcher;
1042 - (pkgSourceList &) list;
1043 - (NSArray *) packages;
1044 - (NSArray *) sources;
1045 - (Source *) sourceWithKey:(NSString *)key;
1046 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1054 - (void) updateWithStatus:(Status &)status;
1056 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1058 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1059 - (NSObject<ProgressDelegate> *) progressDelegate;
1061 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1063 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1067 /* ProgressEvent Implementation {{{ */
1068 @implementation CydiaProgressEvent
1070 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1071 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1074 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1075 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1076 [event setPackage:package];
1080 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1081 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1083 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1084 NSArray *fields([description componentsSeparatedByString:@" "]);
1085 [event setItem:fields];
1087 if ([fields count] > 3) {
1088 [event setPackage:[fields objectAtIndex:2]];
1089 [event setVersion:[fields objectAtIndex:3]];
1092 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1097 + (NSArray *) _attributeKeys {
1098 return [NSArray arrayWithObjects:
1108 - (NSArray *) attributeKeys {
1109 return [[self class] _attributeKeys];
1112 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1113 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1116 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1117 if ((self = [super init]) != nil) {
1123 - (NSString *) message {
1127 - (NSString *) type {
1131 - (NSArray *) item {
1132 return (id) item_ ?: [NSNull null];
1135 - (void) setItem:(NSArray *)item {
1139 - (NSString *) package {
1140 return (id) package_ ?: [NSNull null];
1143 - (void) setPackage:(NSString *)package {
1147 - (NSString *) url {
1148 return (id) url_ ?: [NSNull null];
1151 - (void) setURL:(NSString *)url {
1155 - (void) setVersion:(NSString *)version {
1159 - (NSString *) version {
1160 return (id) version_ ?: [NSNull null];
1163 - (NSString *) compound:(NSString *)value {
1165 NSString *mode(nil); {
1166 NSString *type([self type]);
1167 if ([type isEqualToString:kCydiaProgressEventTypeError])
1168 mode = UCLocalize("ERROR");
1169 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1170 mode = UCLocalize("WARNING");
1174 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1180 - (NSString *) compoundMessage {
1181 return [self compound:[self message]];
1184 - (NSString *) compoundTitle {
1187 if (package_ == nil)
1189 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1190 title = [package name];
1194 return [self compound:title];
1200 // Cytore Definitions {{{
1201 struct PackageValue :
1204 Cytore::Offset<PackageValue> next_;
1206 uint32_t index_ : 23;
1207 uint32_t subscribed_ : 1;
1224 Cytore::Offset<PackageValue> packages_[1 << 16];
1227 static Cytore::File<MetaValue> MetaFile_;
1229 // Cytore Helper Functions {{{
1230 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1231 SplitHash nhash = { hashlittle(name, length) };
1233 PackageValue *metadata;
1235 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1236 offset: if (offset->IsNull()) {
1237 *offset = MetaFile_.New<PackageValue>(length + 1);
1238 metadata = &MetaFile_.Get(*offset);
1240 if (metadata == NULL) {
1244 metadata = new PackageValue();
1245 memset(metadata, 0, sizeof(*metadata));
1248 memcpy(metadata->name_, name, length + 1);
1249 metadata->nhash_ = nhash.u16[1];
1251 metadata = &MetaFile_.Get(*offset);
1253 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1254 offset = &metadata->next_;
1262 static void PackageImport(const void *key, const void *value, void *context) {
1263 bool &fail(*reinterpret_cast<bool *>(context));
1266 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1267 NSLog(@"failed to import package %@", key);
1271 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1272 NSDictionary *package((NSDictionary *) value);
1274 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1275 if ([subscribed boolValue] && !metadata->subscribed_)
1276 metadata->subscribed_ = true;
1278 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1279 time_t time([date timeIntervalSince1970]);
1280 if (metadata->first_ > time || metadata->first_ == 0)
1281 metadata->first_ = time;
1284 NSDate *date([package objectForKey:@"LastSeen"]);
1285 NSString *version([package objectForKey:@"LastVersion"]);
1287 if (date != nil && version != nil) {
1288 time_t time([date timeIntervalSince1970]);
1289 if (metadata->last_ < time || metadata->last_ == 0)
1290 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1291 size_t length(strlen(buffer));
1292 uint16_t vhash(hashlittle(buffer, length));
1294 size_t capped(std::min<size_t>(8, length));
1295 char *latest(buffer + length - capped);
1297 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1298 metadata->vhash_ = vhash;
1300 metadata->last_ = time;
1306 /* Source Class {{{ */
1307 @interface Source : NSObject {
1309 Database *database_;
1312 CYString depiction_;
1313 CYString description_;
1319 CYString distribution_;
1325 _H<NSString> authority_;
1327 CYString defaultIcon_;
1329 _H<NSMutableDictionary> record_;
1333 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1335 - (NSComparisonResult) compareByName:(Source *)source;
1337 - (NSString *) depictionForPackage:(NSString *)package;
1338 - (NSString *) supportForPackage:(NSString *)package;
1340 - (metaIndex *) metaIndex;
1341 - (NSDictionary *) record;
1344 - (NSString *) rooturi;
1345 - (NSString *) distribution;
1346 - (NSString *) type;
1349 - (NSString *) host;
1351 - (NSString *) name;
1352 - (NSString *) shortDescription;
1353 - (NSString *) label;
1354 - (NSString *) origin;
1355 - (NSString *) version;
1357 - (NSString *) defaultIcon;
1358 - (NSURL *) iconURL;
1362 @implementation Source
1364 + (NSString *) webScriptNameForSelector:(SEL)selector {
1366 else if (selector == @selector(addSection:))
1367 return @"addSection";
1368 else if (selector == @selector(getField:))
1370 else if (selector == @selector(removeSection:))
1371 return @"removeSection";
1372 else if (selector == @selector(remove))
1378 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1379 return [self webScriptNameForSelector:selector] == nil;
1382 + (NSArray *) _attributeKeys {
1383 return [NSArray arrayWithObjects:
1394 @"shortDescription",
1401 - (NSArray *) attributeKeys {
1402 return [[self class] _attributeKeys];
1405 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1406 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1409 - (metaIndex *) metaIndex {
1413 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1414 trusted_ = index->IsTrusted();
1416 uri_.set(pool, index->GetURI());
1417 distribution_.set(pool, index->GetDist());
1418 type_.set(pool, index->GetType());
1420 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1421 if (dindex != NULL) {
1422 base_.set(pool, dindex->MetaIndexURI(""));
1425 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1428 pkgTagFile tags(&fd);
1430 pkgTagSection section;
1437 {"default-icon", &defaultIcon_},
1438 {"depiction", &depiction_},
1439 {"description", &description_},
1441 {"origin", &origin_},
1442 {"support", &support_},
1443 {"version", &version_},
1446 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1447 const char *start, *end;
1449 if (section.Find(names[i].name_, start, end)) {
1450 CYString &value(*names[i].value_);
1451 value.set(pool, start, end - start);
1457 record_ = [Sources_ objectForKey:[self key]];
1459 NSURL *url([NSURL URLWithString:uri_]);
1463 host_ = [host_ lowercaseString];
1468 authority_ = [url path];
1471 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1472 if ((self = [super init]) != nil) {
1473 era_ = [database era];
1474 database_ = database;
1477 [self setMetaIndex:index inPool:pool];
1481 - (NSString *) getField:(NSString *)name {
1482 @synchronized (database_) {
1483 if ([database_ era] != era_ || index_ == NULL)
1486 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1491 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1496 pkgTagFile tags(&fd);
1498 pkgTagSection section;
1501 const char *start, *end;
1502 if (!section.Find([name UTF8String], start, end))
1503 return (NSString *) [NSNull null];
1505 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1508 - (NSComparisonResult) compareByName:(Source *)source {
1509 NSString *lhs = [self name];
1510 NSString *rhs = [source name];
1512 if ([lhs length] != 0 && [rhs length] != 0) {
1513 unichar lhc = [lhs characterAtIndex:0];
1514 unichar rhc = [rhs characterAtIndex:0];
1516 if (isalpha(lhc) && !isalpha(rhc))
1517 return NSOrderedAscending;
1518 else if (!isalpha(lhc) && isalpha(rhc))
1519 return NSOrderedDescending;
1522 return [lhs compare:rhs options:LaxCompareOptions_];
1525 - (NSString *) depictionForPackage:(NSString *)package {
1526 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1529 - (NSString *) supportForPackage:(NSString *)package {
1530 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1533 - (NSArray *) sections {
1534 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1537 - (void) _addSection:(NSString *)section {
1540 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1541 if (![sections containsObject:section]) {
1542 [sections addObject:section];
1546 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1551 - (bool) addSection:(NSString *)section {
1555 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1559 - (void) _removeSection:(NSString *)section {
1563 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1564 if ([sections containsObject:section]) {
1565 [sections removeObject:section];
1570 - (bool) removeSection:(NSString *)section {
1574 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1579 [Sources_ removeObjectForKey:[self key]];
1584 bool value(record_ != nil);
1585 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1589 - (NSDictionary *) record {
1597 - (NSString *) rooturi {
1601 - (NSString *) distribution {
1602 return distribution_;
1605 - (NSString *) type {
1609 - (NSString *) baseuri {
1610 return base_.empty() ? nil : (id) base_;
1613 - (NSString *) iconuri {
1614 if (NSString *base = [self baseuri])
1615 return [base stringByAppendingString:@"CydiaIcon.png"];
1620 - (NSURL *) iconURL {
1621 if (NSString *uri = [self iconuri])
1622 return [NSURL URLWithString:uri];
1626 - (NSString *) key {
1627 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1630 - (NSString *) host {
1634 - (NSString *) name {
1635 return origin_.empty() ? (id) authority_ : origin_;
1638 - (NSString *) shortDescription {
1639 return description_;
1642 - (NSString *) label {
1643 return label_.empty() ? (id) authority_ : label_;
1646 - (NSString *) origin {
1650 - (NSString *) version {
1654 - (NSString *) defaultIcon {
1655 return defaultIcon_;
1660 /* CydiaOperation Class {{{ */
1661 @interface CydiaOperation : NSObject {
1662 _H<NSString> operator_;
1663 _H<NSString> value_;
1666 - (NSString *) operator;
1667 - (NSString *) value;
1671 @implementation CydiaOperation
1673 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1674 if ((self = [super init]) != nil) {
1675 operator_ = [NSString stringWithUTF8String:_operator];
1676 value_ = [NSString stringWithUTF8String:value];
1680 + (NSArray *) _attributeKeys {
1681 return [NSArray arrayWithObjects:
1687 - (NSArray *) attributeKeys {
1688 return [[self class] _attributeKeys];
1691 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1692 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1695 - (NSString *) operator {
1699 - (NSString *) value {
1705 /* CydiaClause Class {{{ */
1706 @interface CydiaClause : NSObject {
1707 _H<NSString> package_;
1708 _H<CydiaOperation> version_;
1711 - (NSString *) package;
1712 - (CydiaOperation *) version;
1716 @implementation CydiaClause
1718 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1719 if ((self = [super init]) != nil) {
1720 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1722 if (const char *version = dep.TargetVer())
1723 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1725 version_ = (id) [NSNull null];
1729 + (NSArray *) _attributeKeys {
1730 return [NSArray arrayWithObjects:
1736 - (NSArray *) attributeKeys {
1737 return [[self class] _attributeKeys];
1740 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1741 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1744 - (NSString *) package {
1748 - (CydiaOperation *) version {
1754 /* CydiaRelation Class {{{ */
1755 @interface CydiaRelation : NSObject {
1756 _H<NSString> relationship_;
1757 _H<NSMutableArray> clauses_;
1760 - (NSString *) relationship;
1761 - (NSArray *) clauses;
1765 @implementation CydiaRelation
1767 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1768 if ((self = [super init]) != nil) {
1769 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1770 clauses_ = [NSMutableArray arrayWithCapacity:8];
1772 pkgCache::DepIterator start;
1773 pkgCache::DepIterator end;
1774 dep.GlobOr(start, end); // ++dep
1777 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1779 // yes, seriously. (wtf?)
1787 + (NSArray *) _attributeKeys {
1788 return [NSArray arrayWithObjects:
1794 - (NSArray *) attributeKeys {
1795 return [[self class] _attributeKeys];
1798 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1799 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1802 - (NSString *) relationship {
1803 return relationship_;
1806 - (NSArray *) clauses {
1810 - (void) addClause:(CydiaClause *)clause {
1811 [clauses_ addObject:clause];
1816 /* Package Class {{{ */
1817 struct ParsedPackage {
1821 CYString architecture_;
1824 CYString depiction_;
1831 @interface Package : NSObject {
1834 uint32_t essential_ : 1;
1835 uint32_t obsolete_ : 1;
1836 uint32_t ignored_ : 1;
1837 uint32_t pooled_ : 1;
1843 _transient Database *database_;
1845 pkgCache::VerIterator version_;
1846 pkgCache::PkgIterator iterator_;
1847 pkgCache::VerFileIterator file_;
1853 CYString installed_;
1855 const char *section_;
1856 _transient NSString *section$_;
1860 PackageValue *metadata_;
1861 ParsedPackage *parsed_;
1863 _H<NSMutableArray> tags_;
1866 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1867 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1869 - (pkgCache::PkgIterator) iterator;
1872 - (NSString *) section;
1873 - (NSString *) simpleSection;
1875 - (NSString *) longSection;
1876 - (NSString *) shortSection;
1880 - (MIMEAddress *) maintainer;
1882 - (NSString *) longDescription;
1883 - (NSString *) shortDescription;
1886 - (PackageValue *) metadata;
1889 - (bool) subscribed;
1890 - (bool) setSubscribed:(bool)subscribed;
1894 - (NSString *) latest;
1895 - (NSString *) installed;
1896 - (BOOL) uninstalled;
1899 - (BOOL) upgradableAndEssential:(BOOL)essential;
1902 - (BOOL) unfiltered;
1906 - (BOOL) halfConfigured;
1907 - (BOOL) halfInstalled;
1909 - (NSString *) mode;
1912 - (NSString *) name;
1914 - (NSString *) homepage;
1915 - (NSString *) depiction;
1916 - (MIMEAddress *) author;
1918 - (NSString *) support;
1920 - (NSArray *) files;
1921 - (NSArray *) warnings;
1922 - (NSArray *) applications;
1924 - (Source *) source;
1927 - (BOOL) matches:(NSArray *)query;
1929 - (bool) hasSupportingRole;
1930 - (BOOL) hasTag:(NSString *)tag;
1931 - (NSString *) primaryPurpose;
1932 - (NSArray *) purposes;
1933 - (bool) isCommercial;
1935 - (void) setIndex:(size_t)index;
1937 - (CYString &) cyname;
1939 - (uint32_t) compareBySection:(NSArray *)sections;
1944 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1945 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1946 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1947 - (bool) isVisibleInSection:(NSString *)section;
1948 - (bool) isVisibleInSource:(Source *)source;
1952 uint32_t PackageChangesRadix(Package *self, void *) {
1957 uint32_t timestamp : 30;
1958 uint32_t ignored : 1;
1959 uint32_t upgradable : 1;
1963 bool upgradable([self upgradableAndEssential:YES]);
1964 value.bits.upgradable = upgradable ? 1 : 0;
1967 value.bits.timestamp = 0;
1968 value.bits.ignored = [self ignored] ? 0 : 1;
1969 value.bits.upgradable = 1;
1971 value.bits.timestamp = [self seen] >> 2;
1972 value.bits.ignored = 0;
1973 value.bits.upgradable = 0;
1976 return _not(uint32_t) - value.key;
1979 uint32_t PackagePrefixRadix(Package *self, void *context) {
1980 size_t offset(reinterpret_cast<size_t>(context));
1981 CYString &name([self cyname]);
1983 size_t size(name.size());
1986 char *text(name.data());
1989 if (!isdigit(text[0]))
1993 while (size != digits && isdigit(text[digits]))
2001 if (offset == 0 && zeros != 0) {
2002 memset(data, '0', zeros);
2003 memcpy(data + zeros, text, 4 - zeros);
2005 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2006 if (size <= offset - zeros)
2009 text += offset - zeros;
2010 size -= offset - zeros;
2013 memcpy(data, text, 4);
2015 memcpy(data, text, size);
2016 memset(data + size, 0, 4 - size);
2019 for (size_t i(0); i != 4; ++i)
2020 if (isalpha(data[i]))
2028 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2030 /* XXX: ntohl may be more honest */
2031 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2034 CYString &(*PackageName)(Package *self, SEL sel);
2036 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2037 _profile(PackageNameCompare)
2038 CYString &lhi(PackageName(lhs, @selector(cyname)));
2039 CYString &rhi(PackageName(rhs, @selector(cyname)));
2040 CFStringRef lhn(lhi), rhn(rhi);
2043 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2044 else if (rhn == NULL)
2045 return NSOrderedDescending;
2047 _profile(PackageNameCompare$NumbersLast)
2048 if (!lhi.empty() && !rhi.empty()) {
2049 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2050 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2051 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2052 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2053 return lha ? NSOrderedAscending : NSOrderedDescending;
2057 CFIndex length = CFStringGetLength(lhn);
2059 _profile(PackageNameCompare$Compare)
2060 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2065 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2066 return PackageNameCompare(*lhs, *rhs, context);
2069 struct PackageNameOrdering :
2070 std::binary_function<Package *, Package *, bool>
2072 _finline bool operator ()(Package *lhs, Package *rhs) const {
2073 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2077 @implementation Package
2079 - (NSString *) description {
2080 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2085 apr_pool_destroy(pool_);
2086 if (parsed_ != NULL)
2091 + (NSString *) webScriptNameForSelector:(SEL)selector {
2093 else if (selector == @selector(clear))
2095 else if (selector == @selector(getField:))
2097 else if (selector == @selector(getRecord))
2098 return @"getRecord";
2099 else if (selector == @selector(hasTag:))
2101 else if (selector == @selector(install))
2103 else if (selector == @selector(remove))
2109 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2110 return [self webScriptNameForSelector:selector] == nil;
2113 + (NSArray *) _attributeKeys {
2114 return [NSArray arrayWithObjects:
2135 @"shortDescription",
2147 - (NSArray *) attributeKeys {
2148 return [[self class] _attributeKeys];
2151 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2152 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2155 - (NSArray *) relations {
2156 @synchronized (database_) {
2157 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2158 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2159 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2163 - (NSString *) architecture {
2165 @synchronized (database_) {
2166 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2169 - (NSString *) getField:(NSString *)name {
2170 @synchronized (database_) {
2171 if ([database_ era] != era_ || file_.end())
2174 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2176 const char *start, *end;
2177 if (!parser.Find([name UTF8String], start, end))
2178 return (NSString *) [NSNull null];
2180 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2183 - (NSString *) getRecord {
2184 @synchronized (database_) {
2185 if ([database_ era] != era_ || file_.end())
2188 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2190 const char *start, *end;
2191 parser.GetRec(start, end);
2193 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2197 if (parsed_ != NULL)
2199 @synchronized (database_) {
2200 if ([database_ era] != era_ || file_.end())
2203 ParsedPackage *parsed(new ParsedPackage);
2206 _profile(Package$parse)
2207 pkgRecords::Parser *parser;
2209 _profile(Package$parse$Lookup)
2210 parser = &[database_ records]->Lookup(file_);
2216 _profile(Package$parse$Find)
2221 {"architecture", &parsed->architecture_},
2222 {"icon", &parsed->icon_},
2223 {"depiction", &parsed->depiction_},
2224 {"homepage", &parsed->homepage_},
2225 {"website", &website},
2227 {"support", &parsed->support_},
2228 {"author", &parsed->author_},
2229 {"md5sum", &parsed->md5sum_},
2232 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2233 const char *start, *end;
2235 if (parser->Find(names[i].name_, start, end)) {
2236 CYString &value(*names[i].value_);
2237 _profile(Package$parse$Value)
2238 value.set(pool_, start, end - start);
2244 _profile(Package$parse$Tagline)
2245 const char *start, *end;
2246 if (parser->ShortDesc(start, end)) {
2247 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2250 while (stop != start && stop[-1] == '\r')
2252 parsed->tagline_.set(pool_, start, stop - start);
2256 _profile(Package$parse$Retain)
2257 if (parsed->homepage_.empty())
2258 parsed->homepage_ = website;
2259 if (parsed->homepage_ == parsed->depiction_)
2260 parsed->homepage_.clear();
2261 if (parsed->support_.empty())
2262 parsed->support_ = bugs;
2267 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2268 if ((self = [super init]) != nil) {
2269 _profile(Package$initWithVersion)
2271 apr_pool_create(&pool_, NULL);
2277 database_ = database;
2278 era_ = [database era];
2282 pkgCache::PkgIterator iterator(version.ParentPkg());
2283 iterator_ = iterator;
2285 _profile(Package$initWithVersion$Version)
2286 if (!version_.end())
2287 file_ = version_.FileList();
2289 pkgCache &cache([database_ cache]);
2290 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2294 _profile(Package$initWithVersion$Cache)
2295 name_.set(NULL, iterator.Display());
2297 latest_.set(NULL, StripVersion_(version_.VerStr()));
2299 pkgCache::VerIterator current(iterator.CurrentVer());
2301 installed_.set(NULL, StripVersion_(current.VerStr()));
2304 _profile(Package$initWithVersion$Tags)
2305 pkgCache::TagIterator tag(iterator.TagList());
2307 tags_ = [NSMutableArray arrayWithCapacity:8];
2309 goto tag; for (; !tag.end(); ++tag) tag: {
2310 const char *name(tag.Name());
2311 NSString *string((NSString *) CYStringCreate(name));
2315 [tags_ addObject:[string autorelease]];
2317 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2318 if (strcmp(name + 6, "enduser") == 0)
2320 else if (strcmp(name + 6, "hacker") == 0)
2322 else if (strcmp(name + 6, "developer") == 0)
2324 else if (strcmp(name + 6, "cydia") == 0)
2330 if (strncmp(name, "cydia::", 7) == 0) {
2331 if (strcmp(name + 7, "essential") == 0)
2333 else if (strcmp(name + 7, "obsolete") == 0)
2340 _profile(Package$initWithVersion$Metadata)
2341 const char *mixed(iterator.Name());
2342 size_t size(strlen(mixed));
2343 char lower[size + 1];
2345 for (size_t i(0); i != size; ++i)
2346 lower[i] = mixed[i] | 0x20;
2349 PackageValue *metadata(PackageFind(lower, size));
2350 metadata_ = metadata;
2352 id_.set(NULL, metadata->name_, size);
2354 const char *latest(version_.VerStr());
2355 size_t length(strlen(latest));
2357 uint16_t vhash(hashlittle(latest, length));
2359 size_t capped(std::min<size_t>(8, length));
2360 latest = latest + length - capped;
2362 if (metadata->first_ == 0)
2363 metadata->first_ = now_;
2365 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2366 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2367 metadata->vhash_ = vhash;
2368 metadata->last_ = now_;
2369 } else if (metadata->last_ == 0)
2370 metadata->last_ = metadata->first_;
2373 _profile(Package$initWithVersion$Section)
2374 section_ = version_.Section();
2377 _profile(Package$initWithVersion$Flags)
2378 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2379 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2384 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2385 pkgCache::VerIterator version;
2387 _profile(Package$packageWithIterator$GetCandidateVer)
2388 version = [database policy]->GetCandidateVer(iterator);
2396 _profile(Package$packageWithIterator$Allocate)
2397 package = [Package allocWithZone:zone];
2400 _profile(Package$packageWithIterator$Initialize)
2402 initWithVersion:version
2409 _profile(Package$packageWithIterator$Autorelease)
2410 package = [package autorelease];
2416 - (pkgCache::PkgIterator) iterator {
2420 - (NSString *) section {
2421 if (section$_ == nil) {
2422 if (section_ == NULL)
2425 _profile(Package$section$mappedSectionForPointer)
2426 section$_ = [database_ mappedSectionForPointer:section_];
2431 - (NSString *) simpleSection {
2432 if (NSString *section = [self section])
2433 return Simplify(section);
2438 - (NSString *) longSection {
2439 return LocalizeSection([self section]);
2442 - (NSString *) shortSection {
2443 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2446 - (NSString *) uri {
2449 pkgIndexFile *index;
2450 pkgCache::PkgFileIterator file(file_.File());
2451 if (![database_ list].FindIndex(file, index))
2453 return [NSString stringWithUTF8String:iterator_->Path];
2454 //return [NSString stringWithUTF8String:file.Site()];
2455 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2459 - (MIMEAddress *) maintainer {
2460 @synchronized (database_) {
2461 if ([database_ era] != era_ || file_.end())
2464 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2465 const std::string &maintainer(parser->Maintainer());
2466 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2469 - (NSString *) md5sum {
2470 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2474 @synchronized (database_) {
2475 if ([database_ era] != era_ || version_.end())
2478 return version_->InstalledSize;
2481 - (NSString *) longDescription {
2482 @synchronized (database_) {
2483 if ([database_ era] != era_ || file_.end())
2486 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2487 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2489 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2490 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2491 if ([lines count] < 2)
2494 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2495 for (size_t i(1), e([lines count]); i != e; ++i) {
2496 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2497 [trimmed addObject:trim];
2500 return [trimmed componentsJoinedByString:@"\n"];
2503 - (NSString *) shortDescription {
2504 if (parsed_ != NULL)
2505 return static_cast<NSString *>(parsed_->tagline_);
2507 @synchronized (database_) {
2508 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2510 const char *start, *end;
2511 if (!parser.ShortDesc(start, end))
2514 if (end - start > 200)
2518 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2521 while (end != start && end[-1] == '\r')
2525 return [(id) CYStringCreate(start, end - start) autorelease];
2529 _profile(Package$index)
2530 CFStringRef name((CFStringRef) [self name]);
2531 if (CFStringGetLength(name) == 0)
2533 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2534 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2536 return toupper(character);
2540 - (PackageValue *) metadata {
2545 PackageValue *metadata([self metadata]);
2546 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2549 - (bool) subscribed {
2550 return [self metadata]->subscribed_;
2553 - (bool) setSubscribed:(bool)subscribed {
2554 PackageValue *metadata([self metadata]);
2555 if (metadata->subscribed_ == subscribed)
2557 metadata->subscribed_ = subscribed;
2565 - (NSString *) latest {
2569 - (NSString *) installed {
2573 - (BOOL) uninstalled {
2574 return installed_.empty();
2578 return !version_.end();
2581 - (BOOL) upgradableAndEssential:(BOOL)essential {
2582 _profile(Package$upgradableAndEssential)
2583 pkgCache::VerIterator current(iterator_.CurrentVer());
2585 return essential && essential_;
2587 return !version_.end() && version_ != current;
2591 - (BOOL) essential {
2596 return [database_ cache][iterator_].InstBroken();
2599 - (BOOL) unfiltered {
2600 _profile(Package$unfiltered$obsolete)
2601 if (_unlikely(obsolete_))
2605 _profile(Package$unfiltered$hasSupportingRole)
2606 if (_unlikely(![self hasSupportingRole]))
2614 if (![self unfiltered])
2619 _profile(Package$visible$section)
2620 section = [self section];
2623 _profile(Package$visible$isSectionVisible)
2624 if (!isSectionVisible(section))
2632 unsigned char current(iterator_->CurrentState);
2633 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2636 - (BOOL) halfConfigured {
2637 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2640 - (BOOL) halfInstalled {
2641 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2645 @synchronized (database_) {
2646 if ([database_ era] != era_ || iterator_.end())
2649 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2650 return state.Mode != pkgDepCache::ModeKeep;
2653 - (NSString *) mode {
2654 @synchronized (database_) {
2655 if ([database_ era] != era_ || iterator_.end())
2658 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2660 switch (state.Mode) {
2661 case pkgDepCache::ModeDelete:
2662 if ((state.iFlags & pkgDepCache::Purge) != 0)
2666 case pkgDepCache::ModeKeep:
2667 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2668 return @"REINSTALL";
2669 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2673 case pkgDepCache::ModeInstall:
2674 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2675 return @"REINSTALL";
2676 else*/ switch (state.Status) {
2678 return @"DOWNGRADE";
2684 return @"NEW_INSTALL";
2695 - (NSString *) name {
2696 return name_.empty() ? id_ : name_;
2699 - (UIImage *) icon {
2700 NSString *section = [self simpleSection];
2703 if (parsed_ != NULL)
2704 if (NSString *href = parsed_->icon_)
2705 if ([href hasPrefix:@"file:///"])
2706 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2707 if (icon == nil) if (section != nil)
2708 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2709 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2710 if ([dicon hasPrefix:@"file:///"])
2711 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2713 icon = [UIImage applicationImageNamed:@"unknown.png"];
2717 - (NSString *) homepage {
2718 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2721 - (NSString *) depiction {
2722 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2725 - (MIMEAddress *) author {
2726 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2729 - (NSString *) support {
2730 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
2733 - (NSArray *) files {
2734 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2735 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2738 fin.open([path UTF8String]);
2743 while (std::getline(fin, line))
2744 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2749 - (NSString *) state {
2750 @synchronized (database_) {
2751 if ([database_ era] != era_ || file_.end())
2754 switch (iterator_->CurrentState) {
2755 case pkgCache::State::NotInstalled:
2756 return @"NotInstalled";
2757 case pkgCache::State::UnPacked:
2759 case pkgCache::State::HalfConfigured:
2760 return @"HalfConfigured";
2761 case pkgCache::State::HalfInstalled:
2762 return @"HalfInstalled";
2763 case pkgCache::State::ConfigFiles:
2764 return @"ConfigFiles";
2765 case pkgCache::State::Installed:
2766 return @"Installed";
2767 case pkgCache::State::TriggersAwaited:
2768 return @"TriggersAwaited";
2769 case pkgCache::State::TriggersPending:
2770 return @"TriggersPending";
2773 return (NSString *) [NSNull null];
2776 - (NSString *) selection {
2777 @synchronized (database_) {
2778 if ([database_ era] != era_ || file_.end())
2781 switch (iterator_->SelectedState) {
2782 case pkgCache::State::Unknown:
2784 case pkgCache::State::Install:
2786 case pkgCache::State::Hold:
2788 case pkgCache::State::DeInstall:
2789 return @"DeInstall";
2790 case pkgCache::State::Purge:
2794 return (NSString *) [NSNull null];
2797 - (NSArray *) warnings {
2798 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2799 const char *name(iterator_.Name());
2801 size_t length(strlen(name));
2802 if (length < 2) invalid:
2803 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2804 else for (size_t i(0); i != length; ++i)
2806 /* XXX: technically this is not allowed */
2807 (name[i] < 'A' || name[i] > 'Z') &&
2808 (name[i] < 'a' || name[i] > 'z') &&
2809 (name[i] < '0' || name[i] > '9') &&
2810 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2813 if (strcmp(name, "cydia") != 0) {
2816 bool _private = false;
2819 bool repository = [[self section] isEqualToString:@"Repositories"];
2821 if (NSArray *files = [self files])
2822 for (NSString *file in files)
2823 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2825 else if (!user && [file isEqualToString:@"/User"])
2827 else if (!_private && [file isEqualToString:@"/private"])
2829 else if (!stash && [file isEqualToString:@"/var/stash"])
2832 /* XXX: this is not sensitive enough. only some folders are valid. */
2833 if (cydia && !repository)
2834 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2836 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2838 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2840 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2843 return [warnings count] == 0 ? nil : warnings;
2846 - (NSArray *) applications {
2847 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2849 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2851 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2852 if (NSArray *files = [self files])
2853 for (NSString *file in files)
2854 if (application_r(file)) {
2855 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2856 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2857 if ([id isEqualToString:me])
2860 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2862 display = application_r[1];
2864 NSString *bundle([file stringByDeletingLastPathComponent]);
2865 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2866 // XXX: maybe this should check if this is really a string, not just for length
2867 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
2869 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2871 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2872 [applications addObject:application];
2874 [application addObject:id];
2875 [application addObject:display];
2876 [application addObject:url];
2879 return [applications count] == 0 ? nil : applications;
2882 - (Source *) source {
2883 if (source_ == nil) {
2884 @synchronized (database_) {
2885 if ([database_ era] != era_ || file_.end())
2886 source_ = (Source *) [NSNull null];
2888 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2892 return source_ == (Source *) [NSNull null] ? nil : source_;
2899 - (BOOL) matches:(NSArray *)query {
2900 if (query == nil || [query count] == 0)
2909 string = [self name];
2910 length = [string length];
2912 for (NSString *term in query) {
2913 range = [string rangeOfString:term options:MatchCompareOptions_];
2914 if (range.location != NSNotFound)
2915 rank_ -= 6 * 1000000 / length;
2920 length = [string length];
2922 for (NSString *term in query) {
2923 range = [string rangeOfString:term options:MatchCompareOptions_];
2924 if (range.location != NSNotFound)
2925 rank_ -= 6 * 1000000 / length;
2929 string = [self shortDescription];
2930 length = [string length];
2931 NSUInteger stop(std::min<NSUInteger>(length, 200));
2933 for (NSString *term in query) {
2934 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2935 if (range.location != NSNotFound)
2936 rank_ -= 2 * 100000;
2942 - (bool) hasSupportingRole {
2947 if ([Role_ isEqualToString:@"User"])
2951 if ([Role_ isEqualToString:@"Hacker"])
2955 if ([Role_ isEqualToString:@"Developer"])
2960 - (NSArray *) tags {
2964 - (BOOL) hasTag:(NSString *)tag {
2965 return tags_ == nil ? NO : [tags_ containsObject:tag];
2968 - (NSString *) primaryPurpose {
2969 for (NSString *tag in (NSArray *) tags_)
2970 if ([tag hasPrefix:@"purpose::"])
2971 return [tag substringFromIndex:9];
2975 - (NSArray *) purposes {
2976 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2977 for (NSString *tag in (NSArray *) tags_)
2978 if ([tag hasPrefix:@"purpose::"])
2979 [purposes addObject:[tag substringFromIndex:9]];
2980 return [purposes count] == 0 ? nil : purposes;
2983 - (bool) isCommercial {
2984 return [self hasTag:@"cydia::commercial"];
2987 - (void) setIndex:(size_t)index {
2988 if (metadata_->index_ != index)
2989 metadata_->index_ = index;
2992 - (CYString &) cyname {
2993 return name_.empty() ? id_ : name_;
2996 - (uint32_t) compareBySection:(NSArray *)sections {
2997 NSString *section([self section]);
2998 for (size_t i(0), e([sections count]); i != e; ++i) {
2999 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3003 return _not(uint32_t);
3007 @synchronized (database_) {
3008 pkgProblemResolver *resolver = [database_ resolver];
3009 resolver->Clear(iterator_);
3011 pkgCacheFile &cache([database_ cache]);
3012 cache->SetReInstall(iterator_, false);
3013 cache->MarkKeep(iterator_, false);
3017 @synchronized (database_) {
3018 pkgProblemResolver *resolver = [database_ resolver];
3019 resolver->Clear(iterator_);
3020 resolver->Protect(iterator_);
3022 pkgCacheFile &cache([database_ cache]);
3023 cache->SetReInstall(iterator_, false);
3024 cache->MarkInstall(iterator_, false);
3026 pkgDepCache::StateCache &state((*cache)[iterator_]);
3027 if (!state.Install())
3028 cache->SetReInstall(iterator_, true);
3032 @synchronized (database_) {
3033 pkgProblemResolver *resolver = [database_ resolver];
3034 resolver->Clear(iterator_);
3035 resolver->Remove(iterator_);
3036 resolver->Protect(iterator_);
3038 pkgCacheFile &cache([database_ cache]);
3039 cache->SetReInstall(iterator_, false);
3040 cache->MarkDelete(iterator_, true);
3043 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3044 _profile(Package$isUnfilteredAndSearchedForBy)
3047 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3048 value &= [self unfiltered];
3051 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3052 value &= [self matches:query];
3059 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3060 if ([search length] == 0)
3063 _profile(Package$isUnfilteredAndSelectedForBy)
3066 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3067 value &= [self unfiltered];
3070 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3071 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3078 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3079 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3082 - (bool) isVisibleInSection:(NSString *)name {
3083 NSString *section([self section]);
3087 section == nil && [name length] == 0 ||
3088 [name isEqualToString:section]
3089 ) && [self visible];
3092 - (bool) isVisibleInSource:(Source *)source {
3093 return [self source] == source && [self visible];
3098 /* Section Class {{{ */
3099 @interface Section : NSObject {
3104 _H<NSString> localized_;
3107 - (NSComparisonResult) compareByLocalized:(Section *)section;
3108 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3109 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3110 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3111 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3112 - (NSString *) name;
3119 - (void) addToCount;
3121 - (void) setCount:(size_t)count;
3122 - (NSString *) localized;
3126 @implementation Section
3128 - (NSComparisonResult) compareByLocalized:(Section *)section {
3129 NSString *lhs(localized_);
3130 NSString *rhs([section localized]);
3132 /*if ([lhs length] != 0 && [rhs length] != 0) {
3133 unichar lhc = [lhs characterAtIndex:0];
3134 unichar rhc = [rhs characterAtIndex:0];
3136 if (isalpha(lhc) && !isalpha(rhc))
3137 return NSOrderedAscending;
3138 else if (!isalpha(lhc) && isalpha(rhc))
3139 return NSOrderedDescending;
3142 return [lhs compare:rhs options:LaxCompareOptions_];
3145 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3146 if ((self = [self initWithName:name localize:NO]) != nil) {
3147 if (localized != nil)
3148 localized_ = localized;
3152 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3153 return [self initWithName:name row:0 localize:localize];
3156 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3157 if ((self = [super init]) != nil) {
3162 localized_ = LocalizeSection(name_);
3166 /* XXX: localize the index thingees */
3167 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3168 if ((self = [super init]) != nil) {
3169 name_ = [NSString stringWithCharacters:&index length:1];
3175 - (NSString *) name {
3195 - (void) addToCount {
3199 - (void) setCount:(size_t)count {
3203 - (NSString *) localized {
3210 class CydiaLogCleaner :
3211 public pkgArchiveCleaner
3214 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3219 /* Database Implementation {{{ */
3220 @implementation Database
3222 + (Database *) sharedInstance {
3223 static _H<Database> instance;
3224 if (instance == nil)
3225 instance = [[[Database alloc] init] autorelease];
3233 - (void) releasePackages {
3234 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3235 CFArrayRemoveAllValues(packages_);
3239 // XXX: actually implement this thing
3241 [self releasePackages];
3242 apr_pool_destroy(pool_);
3243 NSRecycleZone(zone_);
3247 - (void) _readCydia:(NSNumber *)fd {
3248 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3249 std::istream is(&ib);
3252 static Pcre finish_r("^finish:([^:]*)$");
3254 while (std::getline(is, line)) {
3255 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3257 const char *data(line.c_str());
3258 size_t size = line.size();
3259 lprintf("C:%s\n", data);
3261 if (finish_r(data, size)) {
3262 NSString *finish = finish_r[1];
3263 int index = [Finishes_ indexOfObject:finish];
3264 if (index != INT_MAX && index > Finish_)
3274 - (void) _readStatus:(NSNumber *)fd {
3275 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3276 std::istream is(&ib);
3279 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3280 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3282 while (std::getline(is, line)) {
3283 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3285 const char *data(line.c_str());
3286 size_t size(line.size());
3287 lprintf("S:%s\n", data);
3289 if (conffile_r(data, size)) {
3290 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3291 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3292 } else if (strncmp(data, "status: ", 8) == 0) {
3293 // status: <package>: {unpacked,half-configured,installed}
3294 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3295 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3296 } else if (strncmp(data, "processing: ", 12) == 0) {
3297 // processing: configure: config-test
3298 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3299 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3300 } else if (pmstatus_r(data, size)) {
3301 std::string type([pmstatus_r[1] UTF8String]);
3303 NSString *package = pmstatus_r[2];
3304 if ([package isEqualToString:@"dpkg-exec"])
3307 float percent([pmstatus_r[3] floatValue]);
3308 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3310 NSString *string = pmstatus_r[4];
3312 if (type == "pmerror") {
3313 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3314 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3315 } else if (type == "pmstatus") {
3316 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3317 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3318 } else if (type == "pmconffile")
3319 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3321 lprintf("E:unknown pmstatus\n");
3323 lprintf("E:unknown status\n");
3331 - (void) _readOutput:(NSNumber *)fd {
3332 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3333 std::istream is(&ib);
3336 while (std::getline(is, line)) {
3337 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3339 lprintf("O:%s\n", line.c_str());
3341 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3342 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3354 - (Package *) packageWithName:(NSString *)name {
3357 @synchronized (self) {
3358 if (static_cast<pkgDepCache *>(cache_) == NULL)
3360 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3361 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3365 if ((self = [super init]) != nil) {
3372 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3373 apr_pool_create(&pool_, NULL);
3375 size_t capacity(MetaFile_->active_);
3381 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3382 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3386 _assert(pipe(fds) != -1);
3389 _config->Set("APT::Keep-Fds::", cydiafd_);
3390 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3393 detachNewThreadSelector:@selector(_readCydia:)
3395 withObject:[NSNumber numberWithInt:fds[0]]
3398 _assert(pipe(fds) != -1);
3402 detachNewThreadSelector:@selector(_readStatus:)
3404 withObject:[NSNumber numberWithInt:fds[0]]
3407 _assert(pipe(fds) != -1);
3408 _assert(dup2(fds[0], 0) != -1);
3409 _assert(close(fds[0]) != -1);
3411 input_ = fdopen(fds[1], "a");
3413 _assert(pipe(fds) != -1);
3414 _assert(dup2(fds[1], 1) != -1);
3415 _assert(close(fds[1]) != -1);
3418 detachNewThreadSelector:@selector(_readOutput:)
3420 withObject:[NSNumber numberWithInt:fds[0]]
3425 - (pkgCacheFile &) cache {
3429 - (pkgDepCache::Policy *) policy {
3433 - (pkgRecords *) records {
3437 - (pkgProblemResolver *) resolver {
3441 - (pkgAcquire &) fetcher {
3445 - (pkgSourceList &) list {
3449 - (NSArray *) packages {
3450 return (NSArray *) packages_;
3453 - (NSArray *) sources {
3457 - (Source *) sourceWithKey:(NSString *)key {
3458 for (Source *source in [self sources]) {
3459 if ([[source key] isEqualToString:key])
3464 - (bool) popErrorWithTitle:(NSString *)title {
3467 while (!_error->empty()) {
3469 bool warning(!_error->PopMessage(error));
3474 size_t size(error.size());
3475 if (size == 0 || error[size - 1] != '\n')
3477 error.resize(size - 1);
3480 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3482 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3483 if (warning && no_pubkey(error.c_str()))
3486 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3492 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3493 return [self popErrorWithTitle:title] || !success;
3496 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3497 @synchronized (self) {
3500 [self releasePackages];
3503 [sourceList_ removeAllObjects];
3523 apr_pool_clear(pool_);
3525 NSRecycleZone(zone_);
3526 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3528 int chk(creat("/tmp/cydia.chk", 0644));
3532 if (invocation != nil)
3533 [invocation invoke];
3535 NSString *title(UCLocalize("DATABASE"));
3537 list_ = new pkgSourceList();
3538 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3541 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3542 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3543 [sourceList_ addObject:object];
3547 OpProgress progress;
3549 if (!cache_.Open(progress, true)) {
3550 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3551 while (!_error->empty()) {
3553 bool warning(!_error->PopMessage(error));
3555 lprintf("cache_.Open():[%s]\n", error.c_str());
3557 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3561 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3562 repair = @selector(configure);
3563 //else if (error == "The package lists or status file could not be parsed or opened.")
3564 // repair = @selector(update);
3565 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3566 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3567 // else if (error == "Malformed Status line")
3568 // else if (error == "The list of sources could not be read.")
3570 if (repair != NULL) {
3572 [delegate_ repairWithSelector:repair];
3581 unlink("/tmp/cydia.chk");
3583 now_ = [[NSDate date] timeIntervalSince1970];
3585 policy_ = new pkgDepCache::Policy();
3586 records_ = new pkgRecords(cache_);
3587 resolver_ = new pkgProblemResolver(cache_);
3588 fetcher_ = new pkgAcquire(&status_);
3591 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3592 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3596 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3599 if (cache_->BrokenCount() != 0) {
3600 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3603 if (cache_->BrokenCount() != 0) {
3604 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3608 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3612 for (Source *object in (id) sourceList_) {
3613 metaIndex *source([object metaIndex]);
3614 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3615 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3616 // XXX: this could be more intelligent
3617 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3618 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3620 sourceMap_[cached->ID] = object;
3625 /*std::vector<Package *> packages;
3626 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3631 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3632 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3633 //packages.push_back(package);
3634 CFArrayAppendValue(packages_, CFRetain(package));
3638 /*if (packages.empty())
3639 packages_ = [[NSArray alloc] init];
3641 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3644 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3645 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3646 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3654 /*if (!packages.empty())
3655 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3656 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3658 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3660 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3662 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3666 size_t count(CFArrayGetCount(packages_));
3667 MetaFile_->active_ = count;
3669 for (size_t index(0); index != count; ++index)
3670 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3677 @synchronized (self) {
3679 resolver_ = new pkgProblemResolver(cache_);
3681 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3682 if (!cache_[iterator].Keep())
3683 cache_->MarkKeep(iterator, false);
3684 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3685 cache_->SetReInstall(iterator, false);
3688 - (void) configure {
3689 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3691 system([dpkg UTF8String]);
3696 @synchronized (self) {
3697 // XXX: I don't remember this condition
3702 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3704 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3706 if ([self popErrorWithTitle:title])
3710 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3712 CydiaLogCleaner cleaner;
3713 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3720 fetcher_->Shutdown();
3722 pkgRecords records(cache_);
3724 lock_ = new FileFd();
3725 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3727 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3729 if ([self popErrorWithTitle:title])
3733 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3736 manager_ = (_system->CreatePM(cache_));
3737 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3744 bool substrate(RestartSubstrate_);
3745 RestartSubstrate_ = false;
3747 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3749 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3751 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3753 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3754 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3757 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3759 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3761 [self popErrorWithTitle:title];
3765 bool failed = false;
3766 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3767 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3769 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3772 std::string uri = (*item)->DescURI();
3773 std::string error = (*item)->ErrorText;
3775 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3778 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3779 [delegate_ addProgressEventOnMainThread:event forTask:title];
3782 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3790 RestartSubstrate_ = true;
3793 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3794 if ([self popErrorWithTitle:title])
3797 if (result == pkgPackageManager::Failed) {
3802 if (result != pkgPackageManager::Completed) {
3807 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3809 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3811 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3812 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3815 if (![before isEqualToArray:after])
3820 NSString *title(UCLocalize("UPGRADE"));
3821 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3827 [self updateWithStatus:status_];
3830 - (void) updateWithStatus:(Status &)status {
3831 NSString *title(UCLocalize("REFRESHING_DATA"));
3834 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3838 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3839 if ([self popErrorWithTitle:title])
3842 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3844 bool success(ListUpdate(status, list, PulseInterval_));
3845 if (status.WasCancelled())
3848 [self popErrorWithTitle:title forOperation:success];
3849 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3853 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3856 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3857 delegate_ = delegate;
3860 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3861 progress_ = delegate;
3862 status_.setDelegate(delegate);
3865 - (NSObject<ProgressDelegate> *) progressDelegate {
3869 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3870 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3871 return i == sourceMap_.end() ? nil : i->second;
3874 - (NSString *) mappedSectionForPointer:(const char *)section {
3875 _H<NSString> *mapped;
3877 _profile(Database$mappedSectionForPointer$Cache)
3878 mapped = §ions_[section];
3881 if (*mapped == NULL) {
3882 size_t length(strlen(section));
3883 char spaced[length + 1];
3885 _profile(Database$mappedSectionForPointer$Replace)
3886 for (size_t index(0); index != length; ++index)
3887 spaced[index] = section[index] == '_' ? ' ' : section[index];
3888 spaced[length] = '\0';
3893 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3894 string = [NSString stringWithUTF8String:spaced];
3897 _profile(Database$mappedSectionForPointer$Map)
3898 string = [SectionMap_ objectForKey:string] ?: string;
3908 static _H<NSMutableSet> Diversions_;
3910 @interface Diversion : NSObject {
3913 _H<NSString> format_;
3918 @implementation Diversion
3920 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3921 if ((self = [super init]) != nil) {
3922 pattern_ = [from UTF8String];
3928 - (NSString *) divert:(NSString *)url {
3929 return !pattern_(url) ? nil : pattern_->*format_;
3932 + (NSURL *) divertURL:(NSURL *)url {
3934 NSString *href([url absoluteString]);
3936 for (Diversion *diversion in (id) Diversions_)
3937 if (NSString *diverted = [diversion divert:href]) {
3939 NSLog(@"div: %@", diverted);
3941 url = [NSURL URLWithString:diverted];
3948 - (NSString *) key {
3952 - (NSUInteger) hash {
3956 - (BOOL) isEqual:(Diversion *)object {
3957 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3962 @interface CydiaObject : NSObject {
3963 _H<CyteWebViewController> indirect_;
3964 _transient id delegate_;
3967 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3973 @interface CydiaWebViewController : CyteWebViewController {
3974 _H<CydiaObject> cydia_;
3977 + (void) addDiversion:(Diversion *)diversion;
3978 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
3979 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
3980 - (void) setDelegate:(id)delegate;
3984 /* Web Scripting {{{ */
3985 @implementation CydiaObject
3987 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3988 if ((self = [super init]) != nil) {
3989 indirect_ = (CyteWebViewController *) indirect;
3993 - (void) setDelegate:(id)delegate {
3994 delegate_ = delegate;
3997 + (NSArray *) _attributeKeys {
3998 return [NSArray arrayWithObjects:
4001 @"coreFoundationVersionNumber",
4018 - (NSArray *) attributeKeys {
4019 return [[self class] _attributeKeys];
4022 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4023 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4026 - (NSString *) version {
4030 - (NSString *) build {
4034 - (NSString *) coreFoundationVersionNumber {
4035 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4038 - (NSString *) device {
4039 return UniqueIdentifier();
4042 - (NSString *) firmware {
4043 return [[UIDevice currentDevice] systemVersion];
4046 - (NSString *) hostname {
4047 return [[UIDevice currentDevice] name];
4050 - (NSString *) idiom {
4051 return (id) Idiom_ ?: [NSNull null];
4054 - (NSString *) mcc {
4055 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4056 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4060 - (NSString *) mnc {
4061 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4062 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4066 - (NSString *) operator {
4067 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4068 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4072 - (NSString *) bbsnum {
4073 return (id) BBSNum_ ?: [NSNull null];
4076 - (NSString *) ecid {
4077 return (id) ChipID_ ?: [NSNull null];
4080 - (NSString *) serial {
4081 return SerialNumber_;
4084 - (NSString *) role {
4085 return (id) Role_ ?: [NSNull null];
4088 - (NSString *) model {
4089 return [NSString stringWithUTF8String:Machine_];
4092 - (NSString *) token {
4093 return (id) Token_ ?: [NSNull null];
4096 + (NSString *) webScriptNameForSelector:(SEL)selector {
4098 else if (selector == @selector(addBridgedHost:))
4099 return @"addBridgedHost";
4100 else if (selector == @selector(addInsecureHost:))
4101 return @"addInsecureHost";
4102 else if (selector == @selector(addInternalRedirect::))
4103 return @"addInternalRedirect";
4104 else if (selector == @selector(addPipelinedHost:scheme:))
4105 return @"addPipelinedHost";
4106 else if (selector == @selector(addSource:::))
4107 return @"addSource";
4108 else if (selector == @selector(addTokenHost:))
4109 return @"addTokenHost";
4110 else if (selector == @selector(addTrivialSource:))
4111 return @"addTrivialSource";
4112 else if (selector == @selector(close))
4114 else if (selector == @selector(du:))
4116 else if (selector == @selector(stringWithFormat:arguments:))
4118 else if (selector == @selector(getAllSources))
4119 return @"getAllSources";
4120 else if (selector == @selector(getApplicationInfo:value:))
4121 return @"getApplicationInfoValue";
4122 else if (selector == @selector(getKernelNumber:))
4123 return @"getKernelNumber";
4124 else if (selector == @selector(getKernelString:))
4125 return @"getKernelString";
4126 else if (selector == @selector(getInstalledPackages))
4127 return @"getInstalledPackages";
4128 else if (selector == @selector(getIORegistryEntry::))
4129 return @"getIORegistryEntry";
4130 else if (selector == @selector(getLocaleIdentifier))
4131 return @"getLocaleIdentifier";
4132 else if (selector == @selector(getPreferredLanguages))
4133 return @"getPreferredLanguages";
4134 else if (selector == @selector(getPackageById:))
4135 return @"getPackageById";
4136 else if (selector == @selector(getMetadataKeys))
4137 return @"getMetadataKeys";
4138 else if (selector == @selector(getMetadataValue:))
4139 return @"getMetadataValue";
4140 else if (selector == @selector(getSessionValue:))
4141 return @"getSessionValue";
4142 else if (selector == @selector(installPackages:))
4143 return @"installPackages";
4144 else if (selector == @selector(isReachable:))
4145 return @"isReachable";
4146 else if (selector == @selector(localizedStringForKey:value:table:))
4148 else if (selector == @selector(popViewController:))
4149 return @"popViewController";
4150 else if (selector == @selector(refreshSources))
4151 return @"refreshSources";
4152 else if (selector == @selector(registerFrame:))
4153 return @"registerFrame";
4154 else if (selector == @selector(removeButton))
4155 return @"removeButton";
4156 else if (selector == @selector(saveConfig))
4157 return @"saveConfig";
4158 else if (selector == @selector(setMetadataValue::))
4159 return @"setMetadataValue";
4160 else if (selector == @selector(setSessionValue::))
4161 return @"setSessionValue";
4162 else if (selector == @selector(substitutePackageNames:))
4163 return @"substitutePackageNames";
4164 else if (selector == @selector(scrollToBottom:))
4165 return @"scrollToBottom";
4166 else if (selector == @selector(setAllowsNavigationAction:))
4167 return @"setAllowsNavigationAction";
4168 else if (selector == @selector(setBadgeValue:))
4169 return @"setBadgeValue";
4170 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4171 return @"setButtonImage";
4172 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4173 return @"setButtonTitle";
4174 else if (selector == @selector(setHidesBackButton:))
4175 return @"setHidesBackButton";
4176 else if (selector == @selector(setHidesNavigationBar:))
4177 return @"setHidesNavigationBar";
4178 else if (selector == @selector(setNavigationBarStyle:))
4179 return @"setNavigationBarStyle";
4180 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4181 return @"setNavigationBarTintColor";
4182 else if (selector == @selector(setPasteboardString:))
4183 return @"setPasteboardString";
4184 else if (selector == @selector(setPasteboardURL:))
4185 return @"setPasteboardURL";
4186 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4187 return @"setScrollAlwaysBounceVertical";
4188 else if (selector == @selector(setScrollIndicatorStyle:))
4189 return @"setScrollIndicatorStyle";
4190 else if (selector == @selector(setToken:))
4192 else if (selector == @selector(setViewportWidth:))
4193 return @"setViewportWidth";
4194 else if (selector == @selector(statfs:))
4196 else if (selector == @selector(supports:))
4198 else if (selector == @selector(unload))
4204 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4205 return [self webScriptNameForSelector:selector] == nil;
4208 - (BOOL) supports:(NSString *)feature {
4209 return [feature isEqualToString:@"window.open"];
4213 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4216 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4217 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4220 - (void) setScrollIndicatorStyle:(NSString *)style {
4221 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4224 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4225 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4228 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4230 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4231 return (id) [NSNull null];
4232 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4234 return (id) [NSNull null];
4235 return [info objectForKey:key];
4238 - (NSNumber *) getKernelNumber:(NSString *)name {
4239 const char *string([name UTF8String]);
4242 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4243 return (id) [NSNull null];
4245 if (size != sizeof(int))
4246 return (id) [NSNull null];
4249 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4250 return (id) [NSNull null];
4252 return [NSNumber numberWithInt:value];
4255 - (NSString *) getKernelString:(NSString *)name {
4256 const char *string([name UTF8String]);
4259 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4260 return (id) [NSNull null];
4262 char value[size + 1];
4263 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4264 return (id) [NSNull null];
4266 // XXX: just in case you request something ludicrous
4269 return [NSString stringWithCString:value];
4272 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4273 NSObject *value(CYIOGetValue([path UTF8String], entry));
4276 if ([value isKindOfClass:[NSData class]])
4277 value = CYHex((NSData *) value);
4282 - (NSArray *) getMetadataKeys {
4283 @synchronized (Values_) {
4284 return [Values_ allKeys];
4287 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4288 WebFrame *frame([iframe contentFrame]);
4289 [indirect_ registerFrame:frame];
4292 - (id) getMetadataValue:(NSString *)key {
4293 @synchronized (Values_) {
4294 return [Values_ objectForKey:key];
4297 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4298 @synchronized (Values_) {
4299 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4300 [Values_ removeObjectForKey:key];
4302 [Values_ setObject:value forKey:key];
4304 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4307 - (id) getSessionValue:(NSString *)key {
4308 @synchronized (SessionData_) {
4309 return [SessionData_ objectForKey:key];
4312 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4313 @synchronized (SessionData_) {
4314 if (value == (id) [WebUndefined undefined])
4315 [SessionData_ removeObjectForKey:key];
4317 [SessionData_ setObject:value forKey:key];
4320 - (void) addBridgedHost:(NSString *)host {
4321 @synchronized (HostConfig_) {
4322 [BridgedHosts_ addObject:host];
4325 - (void) addInsecureHost:(NSString *)host {
4326 @synchronized (HostConfig_) {
4327 [InsecureHosts_ addObject:host];
4330 - (void) addTokenHost:(NSString *)host {
4331 @synchronized (HostConfig_) {
4332 [TokenHosts_ addObject:host];
4335 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4336 @synchronized (HostConfig_) {
4337 if (scheme != (id) [WebUndefined undefined])
4338 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4340 [PipelinedHosts_ addObject:host];
4343 - (void) popViewController:(NSNumber *)value {
4344 if (value == (id) [WebUndefined undefined])
4345 value = [NSNumber numberWithBool:YES];
4346 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4349 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4350 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4352 for (NSString *section in sections)
4353 [array addObject:section];
4355 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4358 distribution, @"Distribution",
4360 nil] waitUntilDone:NO];
4363 - (void) addTrivialSource:(NSString *)href {
4364 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4367 - (void) refreshSources {
4368 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4371 - (void) saveConfig {
4372 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4375 - (NSArray *) getAllSources {
4376 return [[Database sharedInstance] sources];
4379 - (NSArray *) getInstalledPackages {
4380 Database *database([Database sharedInstance]);
4381 @synchronized (database) {
4382 NSArray *packages([database packages]);
4383 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4384 for (Package *package in packages)
4385 if (![package uninstalled])
4386 [installed addObject:package];
4390 - (Package *) getPackageById:(NSString *)id {
4391 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4395 return (Package *) [NSNull null];
4398 - (NSString *) getLocaleIdentifier {
4399 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4402 - (NSArray *) getPreferredLanguages {
4406 - (NSArray *) statfs:(NSString *)path {
4409 if (path == nil || statfs([path UTF8String], &stat) == -1)
4412 return [NSArray arrayWithObjects:
4413 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4414 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4415 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4419 - (NSNumber *) du:(NSString *)path {
4420 NSNumber *value(nil);
4423 _assert(pipe(fds) != -1);
4425 pid_t pid(ExecFork());
4427 _assert(dup2(fds[1], 1) != -1);
4428 _assert(close(fds[0]) != -1);
4429 _assert(close(fds[1]) != -1);
4430 /* XXX: this should probably not use du */
4431 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4434 _assert(close(fds[1]) != -1);
4436 if (FILE *du = fdopen(fds[0], "r")) {
4438 while (fgets(line, sizeof(line), du) != NULL) {
4439 size_t length(strlen(line));
4440 while (length != 0 && line[length - 1] == '\n')
4441 line[--length] = '\0';
4442 if (char *tab = strchr(line, '\t')) {
4444 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4450 _assert(close(fds[0]) != -1);
4457 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4460 - (NSNumber *) isReachable:(NSString *)name {
4461 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4464 - (void) installPackages:(NSArray *)packages {
4465 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4468 - (NSString *) substitutePackageNames:(NSString *)message {
4469 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4470 for (size_t i(0), e([words count]); i != e; ++i) {
4471 NSString *word([words objectAtIndex:i]);
4472 if (Package *package = [[Database sharedInstance] packageWithName:word])
4473 [words replaceObjectAtIndex:i withObject:[package name]];
4476 return [words componentsJoinedByString:@" "];
4479 - (void) removeButton {
4480 [indirect_ removeButton];
4483 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4484 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4487 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4488 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4491 - (void) setBadgeValue:(id)value {
4492 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4495 - (void) setAllowsNavigationAction:(NSString *)value {
4496 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4499 - (void) setHidesBackButton:(NSString *)value {
4500 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4503 - (void) setHidesNavigationBar:(NSString *)value {
4504 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4507 - (void) setNavigationBarStyle:(NSString *)value {
4508 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4511 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4512 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4513 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4514 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4517 - (void) setPasteboardString:(NSString *)value {
4518 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4521 - (void) setPasteboardURL:(NSString *)value {
4522 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4525 - (void) _setToken:(NSString *)token {
4529 [Metadata_ removeObjectForKey:@"Token"];
4531 [Metadata_ setObject:Token_ forKey:@"Token"];
4536 - (void) setToken:(NSString *)token {
4537 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4540 - (void) scrollToBottom:(NSNumber *)animated {
4541 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4544 - (void) setViewportWidth:(float)width {
4545 [indirect_ setViewportWidthOnMainThread:width];
4548 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4549 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4550 unsigned count([arguments count]);
4552 for (unsigned i(0); i != count; ++i)
4553 values[i] = [arguments objectAtIndex:i];
4554 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4557 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4558 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4560 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4562 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4568 @interface NSURL (CydiaSecure)
4571 @implementation NSURL (CydiaSecure)
4573 - (bool) isCydiaSecure {
4574 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4577 @synchronized (HostConfig_) {
4578 if ([InsecureHosts_ containsObject:[self host]])
4587 /* Cydia Browser Controller {{{ */
4588 @implementation CydiaWebViewController
4590 - (NSURL *) navigationURL {
4591 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4594 + (void) _initialize {
4595 [super _initialize];
4597 Diversions_ = [NSMutableSet setWithCapacity:0];
4600 + (void) addDiversion:(Diversion *)diversion {
4601 [Diversions_ addObject:diversion];
4604 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4605 [super webView:view didClearWindowObject:window forFrame:frame];
4606 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4609 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4610 WebDataSource *source([frame dataSource]);
4611 NSURLResponse *response([source response]);
4612 NSURL *url([response URL]);
4613 NSString *scheme([[url scheme] lowercaseString]);
4615 bool bridged(false);
4617 @synchronized (HostConfig_) {
4618 if ([scheme isEqualToString:@"file"])
4620 else if ([scheme isEqualToString:@"https"])
4621 if ([BridgedHosts_ containsObject:[url host]])
4626 [window setValue:cydia forKey:@"cydia"];
4629 - (void) _setupMail:(MFMailComposeViewController *)controller {
4630 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4632 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4633 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4636 - (NSURL *) URLWithURL:(NSURL *)url {
4637 return [Diversion divertURL:url];
4640 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4641 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4644 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4645 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4647 NSURL *url([copy URL]);
4648 NSString *href([url absoluteString]);
4649 NSString *host([url host]);
4651 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4652 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4653 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4654 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4657 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4658 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4660 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4664 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4665 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4666 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4667 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4672 @synchronized (HostConfig_) {
4673 bridged = [BridgedHosts_ containsObject:host];
4674 token = [TokenHosts_ containsObject:host];
4677 if ([url isCydiaSecure]) {
4679 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4680 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4682 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4683 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4690 - (void) setDelegate:(id)delegate {
4691 [super setDelegate:delegate];
4692 [cydia_ setDelegate:delegate];
4695 - (NSString *) applicationNameForUserAgent {
4700 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4701 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4707 @interface AppCacheController : CydiaWebViewController {
4712 @implementation AppCacheController
4714 - (void) didReceiveMemoryWarning {
4715 // XXX: this doesn't work
4718 - (bool) retainsNetworkActivityIndicator {
4726 @interface NSObject (CydiaScript)
4727 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4730 @implementation NSObject (CydiaScript)
4732 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4738 @implementation NSArray (CydiaScript)
4740 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4741 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4742 for (size_t i(0), e([self count]); i != e; ++i)
4743 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4749 @implementation NSDictionary (CydiaScript)
4751 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4752 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4754 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4761 /* Confirmation Controller {{{ */
4762 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4763 if (!iterator.end())
4764 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4765 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4767 pkgCache::PkgIterator package(dep.TargetPkg());
4770 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4777 @protocol ConfirmationControllerDelegate
4778 - (void) cancelAndClear:(bool)clear;
4779 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4783 @interface ConfirmationController : CydiaWebViewController {
4784 _transient Database *database_;
4786 _H<UIAlertView> essential_;
4788 _H<NSDictionary> changes_;
4789 _H<NSMutableArray> issues_;
4790 _H<NSDictionary> sizes_;
4795 - (id) initWithDatabase:(Database *)database;
4799 @implementation ConfirmationController
4803 RestartSubstrate_ = true;
4804 [delegate_ confirmWithNavigationController:[self navigationController]];
4807 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4808 NSString *context([alert context]);
4810 if ([context isEqualToString:@"remove"]) {
4811 if (button == [alert cancelButtonIndex])
4812 [self dismissModalViewControllerAnimated:YES];
4813 else if (button == [alert firstOtherButtonIndex]) {
4814 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
4817 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4818 } else if ([context isEqualToString:@"unable"]) {
4819 [self dismissModalViewControllerAnimated:YES];
4820 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4822 [super alertView:alert clickedButtonAtIndex:button];
4826 - (void) _doContinue {
4827 [delegate_ cancelAndClear:NO];
4828 [self dismissModalViewControllerAnimated:YES];
4831 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4832 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4836 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4837 [super webView:view didClearWindowObject:window forFrame:frame];
4839 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4840 (id) changes_, @"changes",
4841 (id) issues_, @"issues",
4842 (id) sizes_, @"sizes",
4844 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4847 - (id) initWithDatabase:(Database *)database {
4848 if ((self = [super init]) != nil) {
4849 database_ = database;
4851 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4852 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4853 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4854 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4855 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4859 pkgCacheFile &cache([database_ cache]);
4860 NSArray *packages([database_ packages]);
4861 pkgDepCache::Policy *policy([database_ policy]);
4863 issues_ = [NSMutableArray arrayWithCapacity:4];
4865 for (Package *package in packages) {
4866 pkgCache::PkgIterator iterator([package iterator]);
4867 NSString *name([package id]);
4869 if ([package broken]) {
4870 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4872 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4874 reasons, @"reasons",
4877 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4881 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4882 pkgCache::DepIterator start;
4883 pkgCache::DepIterator end;
4884 dep.GlobOr(start, end); // ++dep
4886 if (!cache->IsImportantDep(end))
4888 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4891 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4893 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4894 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4895 clauses, @"clauses",
4899 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4901 pkgCache::PkgIterator target(start.TargetPkg());
4902 if (target->ProvidesList != 0)
4903 reason = @"missing";
4905 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4907 reason = @"installed";
4908 installed = [NSString stringWithUTF8String:ver.VerStr()];
4909 } else if (!cache[target].CandidateVerIter(cache).end())
4910 reason = @"uninstalled";
4911 else if (target->ProvidesList == 0)
4912 reason = @"uninstallable";
4914 reason = @"virtual";
4917 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4918 [NSString stringWithUTF8String:start.CompType()], @"operator",
4919 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4922 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4923 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4924 version, @"version",
4926 installed, @"installed",
4929 // yes, seriously. (wtf?)
4937 pkgDepCache::StateCache &state(cache[iterator]);
4939 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4941 if (state.NewInstall())
4942 [installs addObject:name];
4943 // XXX: else if (state.Install())
4944 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4945 [reinstalls addObject:name];
4946 // XXX: move before previous if
4947 else if (state.Upgrade())
4948 [upgrades addObject:name];
4949 else if (state.Downgrade())
4950 [downgrades addObject:name];
4951 else if (!state.Delete())
4952 // XXX: _assert(state.Keep());
4954 else if (special_r(name))
4955 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4956 [NSNull null], @"package",
4957 [NSArray arrayWithObjects:
4958 [NSDictionary dictionaryWithObjectsAndKeys:
4959 @"Conflicts", @"relationship",
4960 [NSArray arrayWithObjects:
4961 [NSDictionary dictionaryWithObjectsAndKeys:
4963 [NSNull null], @"version",
4964 @"installed", @"reason",
4971 if ([package essential])
4973 [removes addObject:name];
4976 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4977 substrate_ |= DepSubstrate(iterator.CurrentVer());
4982 else if (Advanced_) {
4983 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4985 essential_ = [[[UIAlertView alloc]
4986 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4987 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4989 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4991 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4995 [essential_ setContext:@"remove"];
4996 [essential_ setNumberOfRows:2];
4998 essential_ = [[[UIAlertView alloc]
4999 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5000 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5002 cancelButtonTitle:UCLocalize("OKAY")
5003 otherButtonTitles:nil
5006 [essential_ setContext:@"unable"];
5009 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5010 installs, @"installs",
5011 reinstalls, @"reinstalls",
5012 upgrades, @"upgrades",
5013 downgrades, @"downgrades",
5014 removes, @"removes",
5017 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5018 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5019 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5022 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5026 - (UIBarButtonItem *) leftButton {
5027 return [[[UIBarButtonItem alloc]
5028 initWithTitle:UCLocalize("CANCEL")
5029 style:UIBarButtonItemStylePlain
5031 action:@selector(cancelButtonClicked)
5036 - (void) applyRightButton {
5037 if ([issues_ count] == 0 && ![self isLoading])
5038 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5039 initWithTitle:UCLocalize("CONFIRM")
5040 style:UIBarButtonItemStyleDone
5042 action:@selector(confirmButtonClicked)
5045 [[self navigationItem] setRightBarButtonItem:nil];
5049 - (void) cancelButtonClicked {
5050 [delegate_ cancelAndClear:YES];
5051 [self dismissModalViewControllerAnimated:YES];
5055 - (void) confirmButtonClicked {
5056 if (essential_ != nil)
5066 /* Progress Data {{{ */
5067 @interface CydiaProgressData : NSObject {
5068 _transient id delegate_;
5077 _H<NSMutableArray> events_;
5078 _H<NSString> title_;
5080 _H<NSString> status_;
5081 _H<NSString> finish_;
5086 @implementation CydiaProgressData
5088 + (NSArray *) _attributeKeys {
5089 return [NSArray arrayWithObjects:
5101 - (NSArray *) attributeKeys {
5102 return [[self class] _attributeKeys];
5105 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5106 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5110 if ((self = [super init]) != nil) {
5111 events_ = [NSMutableArray arrayWithCapacity:32];
5119 - (void) setDelegate:(id)delegate {
5120 delegate_ = delegate;
5123 - (void) setPercent:(float)value {
5127 - (NSNumber *) percent {
5128 return [NSNumber numberWithFloat:percent_];
5131 - (void) setCurrent:(float)value {
5135 - (NSNumber *) current {
5136 return [NSNumber numberWithFloat:current_];
5139 - (void) setTotal:(float)value {
5143 - (NSNumber *) total {
5144 return [NSNumber numberWithFloat:total_];
5147 - (void) setSpeed:(float)value {
5151 - (NSNumber *) speed {
5152 return [NSNumber numberWithFloat:speed_];
5155 - (NSArray *) events {
5159 - (void) removeAllEvents {
5160 [events_ removeAllObjects];
5163 - (void) addEvent:(CydiaProgressEvent *)event {
5164 [events_ addObject:event];
5167 - (void) setTitle:(NSString *)text {
5171 - (NSString *) title {
5175 - (void) setFinish:(NSString *)text {
5179 - (NSString *) finish {
5180 return (id) finish_ ?: [NSNull null];
5183 - (void) setRunning:(bool)running {
5187 - (NSNumber *) running {
5188 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5193 /* Progress Controller {{{ */
5194 @interface ProgressController : CydiaWebViewController <
5197 _transient Database *database_;
5198 _H<CydiaProgressData, 1> progress_;
5202 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5204 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5206 - (void) setTitle:(NSString *)title;
5207 - (void) setCancellable:(bool)cancellable;
5211 @implementation ProgressController
5214 [database_ setProgressDelegate:nil];
5218 - (UIBarButtonItem *) leftButton {
5219 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5220 initWithTitle:UCLocalize("CANCEL")
5221 style:UIBarButtonItemStylePlain
5223 action:@selector(cancel)
5224 ] autorelease] : nil;
5227 - (void) updateCancel {
5228 [super applyLeftButton];
5231 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5232 if ((self = [super init]) != nil) {
5233 database_ = database;
5234 delegate_ = delegate;
5236 [database_ setProgressDelegate:self];
5238 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5239 [progress_ setDelegate:self];
5241 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5243 [scroller_ setBackgroundColor:[UIColor blackColor]];
5245 [[self navigationItem] setHidesBackButton:YES];
5247 [self updateCancel];
5251 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5252 [super webView:view didClearWindowObject:window forFrame:frame];
5253 [window setValue:progress_ forKey:@"cydiaProgress"];
5256 - (void) updateProgress {
5257 [self dispatchEvent:@"CydiaProgressUpdate"];
5260 - (void) viewWillAppear:(BOOL)animated {
5261 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5262 [super viewWillAppear:animated];
5265 - (void) reloadSpringBoard {
5266 if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
5267 system("/bin/launchctl stop com.apple.backboardd");
5269 system("/usr/bin/killall backboardd SpringBoard sbreload");
5273 pid_t pid(ExecFork());
5278 pid_t pid(ExecFork());
5280 execl("/usr/bin/sbreload", "sbreload", NULL);
5290 system("/usr/bin/killall backboardd SpringBoard sbreload");
5294 UpdateExternalStatus(0);
5297 [delegate_ saveState];
5301 [delegate_ returnToCydia];
5305 [delegate_ terminateWithSuccess];
5306 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5307 [delegate_ suspendWithAnimation:YES];
5309 [delegate_ suspend];*/
5321 UIProgressHUD *hud([delegate_ addProgressHUD]);
5322 [hud setText:UCLocalize("LOADING")];
5323 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5329 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5330 SBReboot(SBSSpringBoardServerPort());
5332 reboot2(RB_AUTOBOOT);
5339 - (void) setTitle:(NSString *)title {
5340 [progress_ setTitle:title];
5341 [self updateProgress];
5344 - (UIBarButtonItem *) rightButton {
5345 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5346 initWithTitle:UCLocalize("CLOSE")
5347 style:UIBarButtonItemStylePlain
5349 action:@selector(close)
5353 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5354 UpdateExternalStatus(1);
5356 [progress_ setRunning:true];
5357 [self setTitle:title];
5358 // implicit updateProgress
5360 SHA1SumValue notifyconf; {
5362 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5365 MMap mmap(file, MMap::ReadOnly);
5367 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5368 notifyconf = sha1.Result();
5372 SHA1SumValue springlist; {
5374 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5377 MMap mmap(file, MMap::ReadOnly);
5379 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5380 springlist = sha1.Result();
5384 if (invocation != nil) {
5385 [invocation yieldToSelector:@selector(invoke)];
5386 [self setTitle:@"COMPLETE"];
5391 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5394 MMap mmap(file, MMap::ReadOnly);
5396 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5397 if (!(notifyconf == sha1.Result()))
5404 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5407 MMap mmap(file, MMap::ReadOnly);
5409 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5410 if (!(springlist == sha1.Result()))
5416 if (RestartSubstrate_)
5420 RestartSubstrate_ = false;
5423 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5424 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5425 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5426 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5427 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5430 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5432 [progress_ setRunning:false];
5433 [self updateProgress];
5435 [self applyRightButton];
5438 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5439 [progress_ addEvent:event];
5440 [self updateProgress];
5443 - (bool) isProgressCancelled {
5444 return cancel_ == 2;
5449 [self updateCancel];
5452 - (void) setCancellable:(bool)cancellable {
5453 unsigned cancel(cancel_);
5457 else if (cancel_ == 0)
5460 if (cancel != cancel_)
5461 [self updateCancel];
5464 - (void) setProgressCancellable:(NSNumber *)cancellable {
5465 [self setCancellable:[cancellable boolValue]];
5468 - (void) setProgressPercent:(NSNumber *)percent {
5469 [progress_ setPercent:[percent floatValue]];
5470 [self updateProgress];
5473 - (void) setProgressStatus:(NSDictionary *)status {
5474 if (status == nil) {
5475 [progress_ setCurrent:0];
5476 [progress_ setTotal:0];
5477 [progress_ setSpeed:0];
5479 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5481 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5482 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5483 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5486 [self updateProgress];
5492 /* Package Cell {{{ */
5493 @interface PackageCell : CyteTableViewCell <
5494 CyteTableViewCellDelegate
5498 _H<NSString> description_;
5500 _H<NSString> source_;
5502 _H<UIImage> placard_;
5506 - (PackageCell *) init;
5507 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5509 - (void) drawContentRect:(CGRect)rect;
5513 @implementation PackageCell
5515 - (PackageCell *) init {
5516 CGRect frame(CGRectMake(0, 0, 320, 74));
5517 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5518 UIView *content([self contentView]);
5519 CGRect bounds([content bounds]);
5521 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5522 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5523 [content addSubview:content_];
5525 [content_ setDelegate:self];
5526 [content_ setOpaque:YES];
5530 - (NSString *) accessibilityLabel {
5534 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5535 summarized_ = summary;
5545 [content_ setBackgroundColor:[UIColor whiteColor]];
5549 Source *source = [package source];
5551 icon_ = [package icon];
5553 if (NSString *name = [package name])
5554 name_ = [NSString stringWithString:name];
5556 if (NSString *description = [package shortDescription])
5557 description_ = [NSString stringWithString:description];
5559 commercial_ = [package isCommercial];
5561 NSString *label = nil;
5562 bool trusted = false;
5564 if (source != nil) {
5565 label = [source label];
5566 trusted = [source trusted];
5567 } else if ([[package id] isEqualToString:@"firmware"])
5568 label = UCLocalize("APPLE");
5570 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5572 NSString *from(label);
5574 NSString *section = [package simpleSection];
5575 if (section != nil && ![section isEqualToString:label]) {
5576 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5577 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5580 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5582 if (NSString *purpose = [package primaryPurpose])
5583 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5588 if (NSString *mode = [package mode]) {
5589 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5590 color = RemovingColor_;
5591 placard = @"removing";
5593 color = InstallingColor_;
5594 placard = @"installing";
5597 color = [UIColor whiteColor];
5599 if ([package installed] != nil)
5600 placard = @"installed";
5605 [content_ setBackgroundColor:color];
5608 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5611 [self setNeedsDisplay];
5612 [content_ setNeedsDisplay];
5615 - (void) drawSummaryContentRect:(CGRect)rect {
5616 bool highlighted(highlighted_);
5617 float width([self bounds].size.width);
5621 rect.size = [(UIImage *) icon_ size];
5623 while (rect.size.width > 16 || rect.size.height > 16) {
5624 rect.size.width /= 2;
5625 rect.size.height /= 2;
5628 rect.origin.x = 19 - rect.size.width / 2;
5629 rect.origin.y = 19 - rect.size.height / 2;
5631 [icon_ drawInRect:rect];
5634 if (badge_ != nil) {
5636 rect.size = [(UIImage *) badge_ size];
5638 rect.size.width /= 4;
5639 rect.size.height /= 4;
5641 rect.origin.x = 25 - rect.size.width / 2;
5642 rect.origin.y = 25 - rect.size.height / 2;
5644 [badge_ drawInRect:rect];
5647 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5651 UISetColor(commercial_ ? Purple_ : Black_);
5652 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5654 if (placard_ != nil)
5655 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5658 - (void) drawNormalContentRect:(CGRect)rect {
5659 bool highlighted(highlighted_);
5660 float width([self bounds].size.width);
5664 rect.size = [(UIImage *) icon_ size];
5666 while (rect.size.width > 32 || rect.size.height > 32) {
5667 rect.size.width /= 2;
5668 rect.size.height /= 2;
5671 rect.origin.x = 25 - rect.size.width / 2;
5672 rect.origin.y = 25 - rect.size.height / 2;
5674 [icon_ drawInRect:rect];
5677 if (badge_ != nil) {
5679 rect.size = [(UIImage *) badge_ size];
5681 rect.size.width /= 2;
5682 rect.size.height /= 2;
5684 rect.origin.x = 36 - rect.size.width / 2;
5685 rect.origin.y = 36 - rect.size.height / 2;
5687 [badge_ drawInRect:rect];
5690 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5694 UISetColor(commercial_ ? Purple_ : Black_);
5695 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5696 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5699 UISetColor(commercial_ ? Purplish_ : Gray_);
5700 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5702 if (placard_ != nil)
5703 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5706 - (void) drawContentRect:(CGRect)rect {
5708 [self drawSummaryContentRect:rect];
5710 [self drawNormalContentRect:rect];
5715 /* Section Cell {{{ */
5716 @interface SectionCell : CyteTableViewCell <
5717 CyteTableViewCellDelegate
5719 _H<NSString> basic_;
5720 _H<NSString> section_;
5722 _H<NSString> count_;
5724 _H<UISwitch> switch_;
5728 - (void) setSection:(Section *)section editing:(BOOL)editing;
5732 @implementation SectionCell
5734 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5735 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5736 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5737 // XXX: this initial frame is wrong, but is fixed later
5738 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5739 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5741 UIView *content([self contentView]);
5742 CGRect bounds([content bounds]);
5744 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5745 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5746 [content addSubview:content_];
5747 [content_ setBackgroundColor:[UIColor whiteColor]];
5749 [content_ setDelegate:self];
5753 - (void) onSwitch:(id)sender {
5754 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5755 if (metadata == nil) {
5756 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5757 [Sections_ setObject:metadata forKey:basic_];
5760 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5764 - (void) setSection:(Section *)section editing:(BOOL)editing {
5765 if (editing != editing_) {
5767 [switch_ removeFromSuperview];
5769 [self addSubview:switch_];
5778 if (section == nil) {
5779 name_ = UCLocalize("ALL_PACKAGES");
5782 basic_ = [section name];
5783 section_ = [section localized];
5785 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5786 count_ = [NSString stringWithFormat:@"%d", [section count]];
5789 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5792 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5793 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5795 [content_ setNeedsDisplay];
5798 - (void) setFrame:(CGRect)frame {
5799 [super setFrame:frame];
5801 CGRect rect([switch_ frame]);
5802 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
5805 - (NSString *) accessibilityLabel {
5809 - (void) drawContentRect:(CGRect)rect {
5810 bool highlighted(highlighted_ && !editing_);
5812 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
5814 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5817 float width(rect.size.width);
5819 width -= 9 + [switch_ frame].size.width;
5823 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:UILineBreakModeTailTruncation];
5825 CGSize size = [count_ sizeWithFont:Font14_];
5827 UISetColor(Folder_);
5829 [count_ drawAtPoint:CGPointMake(10 + (30 - size.width) / 2, 18) withFont:Font12Bold_];
5835 /* File Table {{{ */
5836 @interface FileTable : CyteViewController <
5837 UITableViewDataSource,
5840 _transient Database *database_;
5841 _H<Package> package_;
5843 _H<NSMutableArray> files_;
5844 _H<UITableView, 2> list_;
5847 - (id) initWithDatabase:(Database *)database;
5848 - (void) setPackage:(Package *)package;
5852 @implementation FileTable
5854 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5855 return files_ == nil ? 0 : [files_ count];
5858 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5862 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5863 static NSString *reuseIdentifier = @"Cell";
5865 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5867 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5868 [cell setFont:[UIFont systemFontOfSize:16]];
5870 [cell setText:[files_ objectAtIndex:indexPath.row]];
5871 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5876 - (NSURL *) navigationURL {
5877 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5881 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5882 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5883 [list_ setRowHeight:24.0f];
5884 [(UITableView *) list_ setDataSource:self];
5885 [list_ setDelegate:self];
5886 [self setView:list_];
5889 - (void) viewDidLoad {
5890 [super viewDidLoad];
5892 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5895 - (void) releaseSubviews {
5901 [super releaseSubviews];
5904 - (id) initWithDatabase:(Database *)database {
5905 if ((self = [super init]) != nil) {
5906 database_ = database;
5910 - (void) setPackage:(Package *)package {
5914 files_ = [NSMutableArray arrayWithCapacity:32];
5916 if (package != nil) {
5918 name_ = [package id];
5920 if (NSArray *files = [package files])
5921 [files_ addObjectsFromArray:files];
5923 if ([files_ count] != 0) {
5924 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5925 [files_ removeObjectAtIndex:0];
5926 [files_ sortUsingSelector:@selector(compareByPath:)];
5928 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5929 [stack addObject:@"/"];
5931 for (int i(0), e([files_ count]); i != e; ++i) {
5932 NSString *file = [files_ objectAtIndex:i];
5933 while (![file hasPrefix:[stack lastObject]])
5934 [stack removeLastObject];
5935 NSString *directory = [stack lastObject];
5936 [stack addObject:[file stringByAppendingString:@"/"]];
5937 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5938 ([stack count] - 2) * 3, "",
5939 [file substringFromIndex:[directory length]]
5948 - (void) reloadData {
5951 [self setPackage:[database_ packageWithName:name_]];
5956 /* Package Controller {{{ */
5957 @interface CYPackageController : CydiaWebViewController <
5958 UIActionSheetDelegate
5960 _transient Database *database_;
5961 _H<Package> package_;
5964 _H<NSMutableArray> buttons_;
5965 _H<UIBarButtonItem> button_;
5968 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
5972 @implementation CYPackageController
5974 - (NSURL *) navigationURL {
5975 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5978 /* XXX: this is not safe at all... localization of /fail/ */
5979 - (void) _clickButtonWithName:(NSString *)name {
5980 if ([name isEqualToString:UCLocalize("CLEAR")])
5981 [delegate_ clearPackage:package_];
5982 else if ([name isEqualToString:UCLocalize("INSTALL")])
5983 [delegate_ installPackage:package_];
5984 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5985 [delegate_ installPackage:package_];
5986 else if ([name isEqualToString:UCLocalize("REMOVE")])
5987 [delegate_ removePackage:package_];
5988 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5989 [delegate_ installPackage:package_];
5990 else _assert(false);
5993 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5994 NSString *context([sheet context]);
5996 if ([context isEqualToString:@"modify"]) {
5997 if (button != [sheet cancelButtonIndex]) {
5998 NSString *buttonName = [buttons_ objectAtIndex:button];
5999 [self _clickButtonWithName:buttonName];
6002 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6006 - (bool) _allowJavaScriptPanel {
6011 - (void) _customButtonClicked {
6012 int count([buttons_ count]);
6017 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6019 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6020 [buttons addObjectsFromArray:buttons_];
6022 UIActionSheet *sheet = [[[UIActionSheet alloc]
6025 cancelButtonTitle:nil
6026 destructiveButtonTitle:nil
6027 otherButtonTitles:nil
6030 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6032 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6033 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6035 [sheet setContext:@"modify"];
6037 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6041 - (void) reloadButtonClicked {
6042 if (commercial_ && function_ == nil && [package_ uninstalled])
6044 [self customButtonClicked];
6047 - (void) applyLoadingTitle {
6048 // Don't show "Loading" as the title. Ever.
6051 - (UIBarButtonItem *) rightButton {
6056 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6057 if ((self = [super init]) != nil) {
6058 database_ = database;
6059 buttons_ = [NSMutableArray arrayWithCapacity:4];
6060 name_ = name == nil ? @"" : [NSString stringWithString:name];
6061 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6065 - (void) reloadData {
6068 package_ = [database_ packageWithName:name_];
6070 [buttons_ removeAllObjects];
6072 if (package_ != nil) {
6073 [(Package *) package_ parse];
6075 commercial_ = [package_ isCommercial];
6077 if ([package_ mode] != nil)
6078 [buttons_ addObject:UCLocalize("CLEAR")];
6079 if ([package_ source] == nil);
6080 else if ([package_ upgradableAndEssential:NO])
6081 [buttons_ addObject:UCLocalize("UPGRADE")];
6082 else if ([package_ uninstalled])
6083 [buttons_ addObject:UCLocalize("INSTALL")];
6085 [buttons_ addObject:UCLocalize("REINSTALL")];
6086 if (![package_ uninstalled])
6087 [buttons_ addObject:UCLocalize("REMOVE")];
6091 switch ([buttons_ count]) {
6092 case 0: title = nil; break;
6093 case 1: title = [buttons_ objectAtIndex:0]; break;
6094 default: title = UCLocalize("MODIFY"); break;
6097 button_ = [[[UIBarButtonItem alloc]
6099 style:UIBarButtonItemStylePlain
6101 action:@selector(customButtonClicked)
6105 - (bool) isLoading {
6106 return commercial_ ? [super isLoading] : false;
6112 /* Package List Controller {{{ */
6113 @interface PackageListController : CyteViewController <
6114 UITableViewDataSource,
6117 _transient Database *database_;
6119 _H<NSArray> packages_;
6120 _H<NSMutableArray> sections_;
6121 _H<UITableView, 2> list_;
6122 _H<NSMutableArray> index_;
6123 _H<NSMutableDictionary> indices_;
6124 _H<NSString> title_;
6125 unsigned reloading_;
6128 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6129 - (void) setDelegate:(id)delegate;
6130 - (void) resetCursor;
6135 @implementation PackageListController
6137 - (NSURL *) referrerURL {
6138 return [self navigationURL];
6141 - (bool) isSummarized {
6145 - (bool) showsSections {
6149 - (void) deselectWithAnimation:(BOOL)animated {
6150 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6153 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6154 CGRect base = [[self view] bounds];
6155 base.size.height -= bounds.size.height;
6156 base.origin = [list_ frame].origin;
6158 [UIView beginAnimations:nil context:NULL];
6159 [UIView setAnimationBeginsFromCurrentState:YES];
6160 [UIView setAnimationCurve:curve];
6161 [UIView setAnimationDuration:duration];
6162 [list_ setFrame:base];
6163 [UIView commitAnimations];
6166 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6167 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6170 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6171 [self resizeForKeyboardBounds:bounds duration:0];
6174 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6175 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6176 *curve = UIViewAnimationCurveEaseInOut;
6178 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6180 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6183 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6186 - (void) keyboardWillShow:(NSNotification *)notification {
6189 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6190 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6192 NSTimeInterval duration;
6193 UIViewAnimationCurve curve;
6194 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6196 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);
6197 UIViewController *base = self;
6198 while ([base parentOrPresentingViewController] != nil)
6199 base = [base parentOrPresentingViewController];
6200 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6201 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6203 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6204 intersection.size.height += CYStatusBarHeight();
6206 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6209 - (void) keyboardWillHide:(NSNotification *)notification {
6210 NSTimeInterval duration;
6211 UIViewAnimationCurve curve;
6212 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6214 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6217 - (void) viewWillAppear:(BOOL)animated {
6218 [super viewWillAppear:animated];
6220 [self resizeForKeyboardBounds:CGRectZero];
6221 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6222 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6225 - (void) viewWillDisappear:(BOOL)animated {
6226 [super viewWillDisappear:animated];
6228 [self resizeForKeyboardBounds:CGRectZero];
6229 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6230 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6233 - (void) viewDidAppear:(BOOL)animated {
6234 [super viewDidAppear:animated];
6235 [self deselectWithAnimation:animated];
6238 - (void) didSelectPackage:(Package *)package {
6239 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6240 [view setDelegate:delegate_];
6241 [[self navigationController] pushViewController:view animated:YES];
6244 #if TryIndexedCollation
6245 + (BOOL) hasIndexedCollation {
6246 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6250 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6251 NSInteger count([sections_ count]);
6252 return count == 0 ? 1 : count;
6255 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6256 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6258 return [[sections_ objectAtIndex:section] name];
6261 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6262 if ([sections_ count] == 0)
6264 return [[sections_ objectAtIndex:section] count];
6267 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6268 @synchronized (database_) {
6269 if ([database_ era] != era_)
6272 Section *section([sections_ objectAtIndex:[path section]]);
6273 NSInteger row([path row]);
6274 Package *package([packages_ objectAtIndex:([section row] + row)]);
6275 return [[package retain] autorelease];
6278 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6279 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6281 cell = [[[PackageCell alloc] init] autorelease];
6283 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6284 [cell setPackage:package asSummary:[self isSummarized]];
6288 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6289 Package *package([self packageAtIndexPath:path]);
6290 package = [database_ packageWithName:[package id]];
6291 [self didSelectPackage:package];
6294 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6295 if (![self showsSections])
6301 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6302 #if TryIndexedCollation
6303 if ([[self class] hasIndexedCollation]) {
6304 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6311 - (void) updateHeight {
6312 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6315 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6316 if ((self = [super init]) != nil) {
6317 database_ = database;
6318 title_ = [title copy];
6319 [[self navigationItem] setTitle:title_];
6324 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6325 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6326 [self setView:view];
6328 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6329 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6330 [view addSubview:list_];
6332 // XXX: is 20 the most optimal number here?
6333 [list_ setSectionIndexMinimumDisplayRowCount:20];
6335 [(UITableView *) list_ setDataSource:self];
6336 [list_ setDelegate:self];
6338 [self updateHeight];
6341 - (void) releaseSubviews {
6349 [super releaseSubviews];
6352 - (void) setDelegate:(id)delegate {
6353 delegate_ = delegate;
6356 - (bool) shouldYield {
6360 - (bool) shouldBlock {
6364 - (NSMutableArray *) _reloadPackages {
6365 @synchronized (database_) {
6366 era_ = [database_ era];
6367 NSArray *packages([database_ packages]);
6369 return [NSMutableArray arrayWithArray:packages];
6372 - (void) _reloadData {
6373 if (reloading_ != 0) {
6381 if ([self shouldYield]) {
6385 if (![self shouldBlock])
6388 hud = [delegate_ addProgressHUD];
6389 [hud setText:UCLocalize("LOADING")];
6393 packages = [self yieldToSelector:@selector(_reloadPackages)];
6396 [delegate_ removeProgressHUD:hud];
6397 } while (reloading_ == 2);
6399 packages = [self _reloadPackages];
6402 @synchronized (database_) {
6403 if (era_ != [database_ era])
6407 packages_ = packages;
6409 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6410 sections_ = [NSMutableArray arrayWithCapacity:16];
6412 Section *section = nil;
6414 #if TryIndexedCollation
6415 if ([[self class] hasIndexedCollation]) {
6416 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6418 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6419 NSArray *titles = [collation sectionIndexTitles];
6422 _profile(PackageTable$reloadData$Section)
6423 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6427 _profile(PackageTable$reloadData$Section$Package)
6428 package = [packages_ objectAtIndex:offset];
6429 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6432 while (secidx < index) {
6435 _profile(PackageTable$reloadData$Section$Allocate)
6436 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6439 _profile(PackageTable$reloadData$Section$Add)
6440 [sections_ addObject:section];
6444 [section addToCount];
6450 index_ = [NSMutableArray arrayWithCapacity:32];
6452 bool sectioned([self showsSections]);
6454 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6455 [sections_ addObject:section];
6458 _profile(PackageTable$reloadData$Section)
6459 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6463 _profile(PackageTable$reloadData$Section$Package)
6464 package = [packages_ objectAtIndex:offset];
6465 index = [package index];
6468 if (sectioned && (section == nil || [section index] != index)) {
6469 _profile(PackageTable$reloadData$Section$Allocate)
6470 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6473 [index_ addObject:[section name]];
6474 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6476 _profile(PackageTable$reloadData$Section$Add)
6477 [sections_ addObject:section];
6481 [section addToCount];
6486 [self updateHeight];
6488 _profile(PackageTable$reloadData$List)
6489 [(UITableView *) list_ setDataSource:self];
6494 - (void) reloadData {
6497 if ([self shouldYield])
6498 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6503 - (void) resetCursor {
6504 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6507 - (void) clearData {
6508 [self updateHeight];
6510 [list_ setDataSource:nil];
6518 /* Filtered Package List Controller {{{ */
6519 @interface FilteredPackageListController : PackageListController {
6522 _H<NSObject> object_;
6525 - (void) setObject:(id)object;
6526 - (void) setObject:(id)object forFilter:(SEL)filter;
6529 - (void) setFilter:(SEL)filter;
6531 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6535 @implementation FilteredPackageListController
6541 - (void) setFilter:(SEL)filter {
6542 @synchronized (self) {
6545 /* XXX: this is an unsafe optimization of doomy hell */
6546 Method method(class_getInstanceMethod([Package class], filter));
6547 _assert(method != NULL);
6548 imp_ = method_getImplementation(method);
6549 _assert(imp_ != NULL);
6552 - (void) setObject:(id)object {
6553 @synchronized (self) {
6557 - (void) setObject:(id)object forFilter:(SEL)filter {
6558 @synchronized (self) {
6559 [self setFilter:filter];
6560 [self setObject:object];
6563 - (NSMutableArray *) _reloadPackages {
6564 @synchronized (database_) {
6565 era_ = [database_ era];
6566 NSArray *packages([database_ packages]);
6568 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6572 _H<NSObject> object;
6574 @synchronized (self) {
6580 _profile(PackageTable$reloadData$Filter)
6581 for (Package *package in packages)
6582 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6583 [filtered addObject:package];
6589 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6590 if ((self = [super initWithDatabase:database title:title]) != nil) {
6591 [self setFilter:filter];
6592 [self setObject:object];
6599 /* Home Controller {{{ */
6600 @interface HomeController : CydiaWebViewController {
6601 CFRunLoopRef runloop_;
6602 SCNetworkReachabilityRef reachability_;
6607 @implementation HomeController
6609 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6610 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6614 if ((self = [super init]) != nil) {
6615 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6618 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6619 if (reachability_ != NULL) {
6620 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6621 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6623 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6624 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6631 if (reachability_ != NULL && runloop_ != NULL)
6632 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6636 - (NSURL *) navigationURL {
6637 return [NSURL URLWithString:@"cydia://home"];
6640 - (void) aboutButtonClicked {
6641 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6643 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6644 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6645 [alert setCancelButtonIndex:0];
6648 @"Copyright \u00a9 2008-2013\n"
6651 "Jay Freeman (saurik)\n"
6652 "saurik@saurik.com\n"
6653 "http://www.saurik.com/"
6659 - (UIBarButtonItem *) leftButton {
6660 return [[[UIBarButtonItem alloc]
6661 initWithTitle:UCLocalize("ABOUT")
6662 style:UIBarButtonItemStylePlain
6664 action:@selector(aboutButtonClicked)
6670 /* Manage Controller {{{ */
6671 @interface ManageController : CydiaWebViewController {
6674 - (void) queueStatusDidChange;
6678 @implementation ManageController
6681 if ((self = [super init]) != nil) {
6682 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6686 - (NSURL *) navigationURL {
6687 return [NSURL URLWithString:@"cydia://manage"];
6690 - (UIBarButtonItem *) leftButton {
6691 return [[[UIBarButtonItem alloc]
6692 initWithTitle:UCLocalize("SETTINGS")
6693 style:UIBarButtonItemStylePlain
6695 action:@selector(settingsButtonClicked)
6699 - (void) settingsButtonClicked {
6700 [delegate_ showSettings];
6703 - (void) queueButtonClicked {
6707 - (UIBarButtonItem *) rightButton {
6708 return Queuing_ ? [[[UIBarButtonItem alloc]
6709 initWithTitle:UCLocalize("QUEUE")
6710 style:UIBarButtonItemStyleDone
6712 action:@selector(queueButtonClicked)
6713 ] autorelease] : nil;
6716 - (void) queueStatusDidChange {
6717 [self applyRightButton];
6720 - (bool) isLoading {
6721 return !Queuing_ && [super isLoading];
6727 /* Refresh Bar {{{ */
6728 @interface RefreshBar : UINavigationBar {
6729 _H<UIProgressIndicator> indicator_;
6730 _H<UITextLabel> prompt_;
6731 _H<UINavigationButton> cancel_;
6736 @implementation RefreshBar
6738 - (void) positionViews {
6739 CGRect frame = [cancel_ frame];
6740 frame.size = [cancel_ sizeThatFits:frame.size];
6741 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6742 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6743 [cancel_ setFrame:frame];
6745 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6746 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6747 CGRect indrect = {{indoffset, indoffset}, indsize};
6748 [indicator_ setFrame:indrect];
6750 CGSize prmsize = {215, indsize.height + 4};
6752 indoffset * 2 + indsize.width,
6753 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6755 [prompt_ setFrame:prmrect];
6758 - (void) setFrame:(CGRect)frame {
6759 [super setFrame:frame];
6760 [self positionViews];
6763 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6764 if ((self = [super initWithFrame:frame]) != nil) {
6765 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6767 [self setBarStyle:UIBarStyleBlack];
6769 UIBarStyle barstyle([self _barStyle:NO]);
6770 bool ugly(barstyle == UIBarStyleDefault);
6772 UIProgressIndicatorStyle style = ugly ?
6773 UIProgressIndicatorStyleMediumBrown :
6774 UIProgressIndicatorStyleMediumWhite;
6776 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6777 [(UIProgressIndicator *) indicator_ setStyle:style];
6778 [indicator_ startAnimation];
6779 [self addSubview:indicator_];
6781 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6782 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6783 [prompt_ setBackgroundColor:[UIColor clearColor]];
6784 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6785 [self addSubview:prompt_];
6787 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6788 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6789 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6790 [cancel_ setBarStyle:barstyle];
6792 [self positionViews];
6796 - (void) setCancellable:(bool)cancellable {
6798 [self addSubview:cancel_];
6800 [cancel_ removeFromSuperview];
6804 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6808 [self setCancellable:NO];
6811 - (void) setPrompt:(NSString *)prompt {
6812 [prompt_ setText:prompt];
6815 - (void) setProgress:(float)progress {
6821 /* Cydia Navigation Controller Interface {{{ */
6822 @interface UINavigationController (Cydia)
6824 - (NSArray *) navigationURLCollection;
6825 - (void) unloadData;
6830 /* Cydia Tab Bar Controller {{{ */
6831 @interface CydiaTabBarController : CyteTabBarController <
6832 UITabBarControllerDelegate,
6835 _transient Database *database_;
6836 _H<RefreshBar, 1> refreshbar_;
6840 // XXX: ok, "updatedelegate_"?...
6841 _transient NSObject<CydiaDelegate> *updatedelegate_;
6844 - (NSArray *) navigationURLCollection;
6845 - (void) dropBar:(BOOL)animated;
6846 - (void) beginUpdate;
6847 - (void) raiseBar:(BOOL)animated;
6852 @implementation CydiaTabBarController
6854 - (NSArray *) navigationURLCollection {
6855 NSMutableArray *items([NSMutableArray array]);
6857 // XXX: Should this deal with transient view controllers?
6858 for (id navigation in [self viewControllers]) {
6859 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6861 [items addObject:stack];
6868 [[NSNotificationCenter defaultCenter] removeObserver:self];
6873 - (id) initWithDatabase:(Database *)database {
6874 if ((self = [super init]) != nil) {
6875 database_ = database;
6876 [self setDelegate:self];
6878 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6879 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6881 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6885 - (void) setUpdate:(NSDate *)date {
6889 - (void) beginUpdate {
6890 [(RefreshBar *) refreshbar_ start];
6893 [updatedelegate_ retainNetworkActivityIndicator];
6897 detachNewThreadSelector:@selector(performUpdate)
6903 - (void) performUpdate {
6904 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6907 status.setDelegate(self);
6908 [database_ updateWithStatus:status];
6911 performSelectorOnMainThread:@selector(completeUpdate)
6919 - (void) stopUpdateWithSelector:(SEL)selector {
6921 [updatedelegate_ releaseNetworkActivityIndicator];
6923 [self raiseBar:YES];
6926 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6929 - (void) completeUpdate {
6932 [self stopUpdateWithSelector:@selector(reloadData)];
6935 - (void) cancelUpdate {
6936 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
6939 - (void) cancelPressed {
6940 [self cancelUpdate];
6947 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6948 [refreshbar_ setPrompt:[event compoundMessage]];
6951 - (bool) isProgressCancelled {
6955 - (void) setProgressCancellable:(NSNumber *)cancellable {
6956 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6959 - (void) setProgressPercent:(NSNumber *)percent {
6960 [refreshbar_ setProgress:[percent floatValue]];
6963 - (void) setProgressStatus:(NSDictionary *)status {
6965 [self setProgressPercent:[status objectForKey:@"Percent"]];
6968 - (void) setUpdateDelegate:(id)delegate {
6969 updatedelegate_ = delegate;
6972 - (UIView *) transitionView {
6973 if (![self respondsToSelector:@selector(_transitionView)])
6974 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6975 else if (kCFCoreFoundationVersionNumber < 800)
6976 return [self _transitionView];
6978 return [[[self _transitionView] superview] superview];
6981 - (void) dropBar:(BOOL)animated {
6986 UIView *transition([self transitionView]);
6987 [[self view] addSubview:refreshbar_];
6989 CGRect barframe([refreshbar_ frame]);
6991 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6992 barframe.origin.y = 0;
6993 else if (kCFCoreFoundationVersionNumber < 800)
6994 barframe.origin.y = CYStatusBarHeight();
6996 barframe.origin.y = 0; //-barframe.size.height + CYStatusBarHeight();
6998 [refreshbar_ setFrame:barframe];
7000 CGRect viewframe = [transition frame];
7002 if (kCFCoreFoundationVersionNumber < 800) {
7004 [UIView beginAnimations:nil context:NULL];
7006 float adjust(barframe.size.height);
7007 if (kCFCoreFoundationVersionNumber >= 800)
7008 adjust -= CYStatusBarHeight();
7009 viewframe.origin.y += adjust;
7010 viewframe.size.height -= adjust;
7011 [transition setFrame:viewframe];
7014 [UIView commitAnimations];
7017 // Ensure bar has the proper width for our view, it might have changed
7018 barframe.size.width = viewframe.size.width;
7019 [refreshbar_ setFrame:barframe];
7022 - (void) raiseBar:(BOOL)animated {
7027 UIView *transition([self transitionView]);
7028 [refreshbar_ removeFromSuperview];
7030 CGRect barframe([refreshbar_ frame]);
7032 if (kCFCoreFoundationVersionNumber < 800) {
7034 [UIView beginAnimations:nil context:NULL];
7036 CGRect viewframe = [transition frame];
7037 float adjust(barframe.size.height);
7038 if (kCFCoreFoundationVersionNumber >= 800)
7039 adjust -= CYStatusBarHeight();
7040 viewframe.origin.y -= adjust;
7041 viewframe.size.height += adjust;
7042 [transition setFrame:viewframe];
7045 [UIView commitAnimations];
7049 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7050 bool dropped(dropped_);
7055 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7061 - (void) statusBarFrameChanged:(NSNotification *)notification {
7071 /* Cydia Navigation Controller Implementation {{{ */
7072 @implementation UINavigationController (Cydia)
7074 - (NSArray *) navigationURLCollection {
7075 NSMutableArray *stack([NSMutableArray array]);
7077 for (CyteViewController *controller in [self viewControllers]) {
7078 NSString *url = [[controller navigationURL] absoluteString];
7080 [stack addObject:url];
7086 - (void) reloadData {
7089 UIViewController *visible([self visibleViewController]);
7091 [visible reloadData];
7093 // on the iPad, this view controller is ALSO visible. :(
7095 if (UIViewController *top = [self topViewController])
7100 - (void) unloadData {
7101 for (CyteViewController *page in [self viewControllers])
7110 /* Cydia:// Protocol {{{ */
7111 @interface CydiaURLProtocol : NSURLProtocol {
7116 @implementation CydiaURLProtocol
7118 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7119 NSURL *url([request URL]);
7123 NSString *scheme([[url scheme] lowercaseString]);
7124 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7126 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7132 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7136 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7137 id<NSURLProtocolClient> client([self client]);
7139 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7141 NSData *data(UIImagePNGRepresentation(icon));
7143 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7144 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7145 [client URLProtocol:self didLoadData:data];
7146 [client URLProtocolDidFinishLoading:self];
7150 - (void) startLoading {
7151 id<NSURLProtocolClient> client([self client]);
7152 NSURLRequest *request([self request]);
7154 NSURL *url([request URL]);
7155 NSString *href([url absoluteString]);
7156 NSString *scheme([[url scheme] lowercaseString]);
7160 if ([scheme isEqualToString:@"cydia"])
7161 path = [href substringFromIndex:8];
7162 else if ([scheme isEqualToString:@"about"])
7163 path = [href substringFromIndex:12];
7164 else _assert(false);
7166 NSRange slash([path rangeOfString:@"/"]);
7169 if (slash.location == NSNotFound) {
7173 command = [path substringToIndex:slash.location];
7174 path = [path substringFromIndex:(slash.location + 1)];
7177 Database *database([Database sharedInstance]);
7179 if ([command isEqualToString:@"package-icon"]) {
7182 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7183 Package *package([database packageWithName:path]);
7187 UIImage *icon([package icon]);
7188 [self _returnPNGWithImage:icon forRequest:request];
7189 } else if ([command isEqualToString:@"uikit-image"]) {
7192 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7193 UIImage *icon(_UIImageWithName(path));
7194 [self _returnPNGWithImage:icon forRequest:request];
7195 } else if ([command isEqualToString:@"section-icon"]) {
7198 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7199 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7201 icon = [UIImage applicationImageNamed:@"unknown.png"];
7202 [self _returnPNGWithImage:icon forRequest:request];
7204 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7208 - (void) stopLoading {
7214 /* Section Controller {{{ */
7215 @interface SectionController : FilteredPackageListController {
7216 _H<NSString> section_;
7219 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7223 @implementation SectionController
7225 - (NSURL *) referrerURL {
7226 NSString *name = section_;
7230 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@", UI_, [name stringByAddingPercentEscapesIncludingReserved]]];
7233 - (NSURL *) navigationURL {
7234 NSString *name = section_;
7238 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", [name stringByAddingPercentEscapesIncludingReserved]]];
7241 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7244 title = UCLocalize("ALL_PACKAGES");
7245 else if (![name isEqual:@""])
7246 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7248 title = UCLocalize("NO_SECTION");
7250 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7257 /* Sections Controller {{{ */
7258 @interface SectionsController : CyteViewController <
7259 UITableViewDataSource,
7262 _transient Database *database_;
7263 _H<NSMutableArray> sections_;
7264 _H<NSMutableArray> filtered_;
7265 _H<UITableView, 2> list_;
7268 - (id) initWithDatabase:(Database *)database;
7269 - (void) editButtonClicked;
7273 @implementation SectionsController
7275 - (NSURL *) navigationURL {
7276 return [NSURL URLWithString:@"cydia://sections"];
7279 - (void) updateNavigationItem {
7280 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7281 if ([sections_ count] == 0) {
7282 [[self navigationItem] setRightBarButtonItem:nil];
7284 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7285 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7287 action:@selector(editButtonClicked)
7288 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7292 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7293 [super setEditing:editing animated:animated];
7298 [delegate_ updateData];
7300 [self updateNavigationItem];
7303 - (void) viewDidAppear:(BOOL)animated {
7304 [super viewDidAppear:animated];
7305 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7308 - (void) viewWillDisappear:(BOOL)animated {
7309 [super viewWillDisappear:animated];
7310 [self setEditing:NO];
7313 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7314 Section *section = nil;
7315 int index = [indexPath row];
7316 if (![self isEditing]) {
7319 section = [filtered_ objectAtIndex:index];
7321 section = [sections_ objectAtIndex:index];
7326 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7327 if ([self isEditing])
7328 return [sections_ count];
7330 return [filtered_ count] + 1;
7333 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7337 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7338 static NSString *reuseIdentifier = @"SectionCell";
7340 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7342 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7344 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7349 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7350 if ([self isEditing])
7353 Section *section = [self sectionAtIndexPath:indexPath];
7355 SectionController *controller = [[[SectionController alloc]
7356 initWithDatabase:database_
7357 section:[section name]
7359 [controller setDelegate:delegate_];
7361 [[self navigationController] pushViewController:controller animated:YES];
7365 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7366 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7367 [list_ setRowHeight:46];
7368 [(UITableView *) list_ setDataSource:self];
7369 [list_ setDelegate:self];
7370 [self setView:list_];
7373 - (void) viewDidLoad {
7374 [super viewDidLoad];
7376 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7379 - (void) releaseSubviews {
7385 [super releaseSubviews];
7388 - (id) initWithDatabase:(Database *)database {
7389 if ((self = [super init]) != nil) {
7390 database_ = database;
7394 - (void) reloadData {
7397 NSArray *packages = [database_ packages];
7399 sections_ = [NSMutableArray arrayWithCapacity:16];
7400 filtered_ = [NSMutableArray arrayWithCapacity:16];
7402 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7405 for (Package *package in packages) {
7406 NSString *name([package section]);
7407 NSString *key(name == nil ? @"" : name);
7411 _profile(SectionsView$reloadData$Section)
7412 section = [sections objectForKey:key];
7413 if (section == nil) {
7414 _profile(SectionsView$reloadData$Section$Allocate)
7415 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7416 [sections setObject:section forKey:key];
7421 [section addToCount];
7423 _profile(SectionsView$reloadData$Filter)
7424 if (![package valid] || ![package visible])
7432 [sections_ addObjectsFromArray:[sections allValues]];
7434 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7436 for (Section *section in (id) sections_) {
7437 size_t count([section row]);
7441 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7442 [section setCount:count];
7443 [filtered_ addObject:section];
7446 [self updateNavigationItem];
7451 - (void) editButtonClicked {
7452 [self setEditing:![self isEditing] animated:YES];
7458 /* Changes Controller {{{ */
7459 @interface ChangesController : CyteViewController <
7460 UITableViewDataSource,
7463 _transient Database *database_;
7465 _H<NSMutableArray> packages_;
7466 _H<NSMutableArray> sections_;
7467 _H<UITableView, 2> list_;
7471 - (id) initWithDatabase:(Database *)database;
7475 @implementation ChangesController
7477 - (NSURL *) navigationURL {
7478 return [NSURL URLWithString:@"cydia://changes"];
7481 - (void) viewDidAppear:(BOOL)animated {
7482 [super viewDidAppear:animated];
7483 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7486 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7487 NSInteger count([sections_ count]);
7488 return count == 0 ? 1 : count;
7491 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7492 if ([sections_ count] == 0)
7494 return [[sections_ objectAtIndex:section] name];
7497 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7498 if ([sections_ count] == 0)
7500 return [[sections_ objectAtIndex:section] count];
7503 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7504 @synchronized (database_) {
7505 if ([database_ era] != era_)
7508 NSUInteger sectionIndex([path section]);
7509 if (sectionIndex >= [sections_ count])
7511 Section *section([sections_ objectAtIndex:sectionIndex]);
7512 NSInteger row([path row]);
7513 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7516 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7517 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7519 cell = [[[PackageCell alloc] init] autorelease];
7521 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7522 [cell setPackage:package asSummary:false];
7526 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7527 Package *package([self packageAtIndexPath:path]);
7528 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[NSString stringWithFormat:@"%@/#!/changes/", UI_]] autorelease]);
7529 [view setDelegate:delegate_];
7530 [[self navigationController] pushViewController:view animated:YES];
7534 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7535 NSString *context([alert context]);
7537 if ([context isEqualToString:@"norefresh"])
7538 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7541 - (void) refreshButtonClicked {
7542 if (IsReachable("cydia.saurik.com")) {
7543 [delegate_ beginUpdate];
7544 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7546 UIAlertView *alert = [[[UIAlertView alloc]
7547 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
7548 message:@"Host Unreachable" // XXX: Localize
7550 cancelButtonTitle:UCLocalize("OK")
7551 otherButtonTitles:nil
7554 [alert setContext:@"norefresh"];
7559 - (void) upgradeButtonClicked {
7560 [delegate_ distUpgrade];
7561 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7565 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7566 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7567 [self setView:view];
7569 list_ = [[[UITableView alloc] initWithFrame:[view bounds] style:UITableViewStylePlain] autorelease];
7570 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7571 [list_ setRowHeight:73];
7572 [(UITableView *) list_ setDataSource:self];
7573 [list_ setDelegate:self];
7574 [view addSubview:list_];
7577 - (void) viewDidLoad {
7578 [super viewDidLoad];
7580 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7583 - (void) releaseSubviews {
7589 [super releaseSubviews];
7592 - (id) initWithDatabase:(Database *)database {
7593 if ((self = [super init]) != nil) {
7594 database_ = database;
7598 - (NSMutableArray *) _reloadPackages {
7599 @synchronized (database_) {
7600 era_ = [database_ era];
7601 NSArray *packages([database_ packages]);
7603 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7606 _profile(ChangesController$_reloadPackages$Filter)
7607 for (Package *package in packages)
7608 if ([package upgradableAndEssential:YES] || [package visible])
7609 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7612 _profile(ChangesController$_reloadPackages$radixSort)
7613 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7620 - (void) _reloadData {
7621 NSMutableArray *packages;
7625 UIProgressHUD *hud([delegate_ addProgressHUD]);
7626 [hud setText:UCLocalize("LOADING")];
7627 //NSLog(@"HUD:%@::%@", delegate_, hud);
7628 packages = [self yieldToSelector:@selector(_reloadPackages)];
7629 [delegate_ removeProgressHUD:hud];
7631 packages = [self _reloadPackages];
7634 @synchronized (database_) {
7635 if (era_ != [database_ era])
7638 packages_ = packages;
7639 sections_ = [NSMutableArray arrayWithCapacity:16];
7641 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7642 Section *ignored = nil;
7643 Section *section = nil;
7647 bool unseens = false;
7649 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7651 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7652 Package *package = [packages_ objectAtIndex:offset];
7654 BOOL uae = [package upgradableAndEssential:YES];
7658 time_t seen([package seen]);
7660 if (section == nil || last != seen) {
7664 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7667 _profile(ChangesController$reloadData$Allocate)
7668 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7669 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7670 [sections_ addObject:section];
7674 [section addToCount];
7675 } else if ([package ignored]) {
7676 if (ignored == nil) {
7677 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7679 [ignored addToCount];
7682 [upgradable addToCount];
7687 CFRelease(formatter);
7690 Section *last = [sections_ lastObject];
7691 size_t count = [last count];
7692 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7693 [sections_ removeLastObject];
7696 if ([ignored count] != 0)
7697 [sections_ insertObject:ignored atIndex:0];
7699 [sections_ insertObject:upgradable atIndex:0];
7703 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7704 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7705 style:UIBarButtonItemStylePlain
7707 action:@selector(upgradeButtonClicked)
7708 ] autorelease]) animated:YES];
7710 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7711 initWithTitle:UCLocalize("REFRESH")
7712 style:UIBarButtonItemStylePlain
7714 action:@selector(refreshButtonClicked)
7715 ] autorelease]) animated:YES];
7720 - (void) reloadData {
7722 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7727 /* Search Controller {{{ */
7728 @interface SearchController : FilteredPackageListController <
7731 _H<UISearchBar, 1> search_;
7735 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7736 - (void) reloadData;
7740 @implementation SearchController
7742 - (NSURL *) referrerURL {
7743 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7746 - (NSURL *) navigationURL {
7747 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7748 return [NSURL URLWithString:@"cydia://search"];
7750 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7753 - (NSArray *) termsForQuery:(NSString *)query {
7754 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7755 for (NSString *component in [query componentsSeparatedByString:@" "])
7756 if ([component length] != 0)
7757 [terms addObject:component];
7762 - (void) useSearch {
7763 [self setObject:[self termsForQuery:[search_ text]] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7768 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7769 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7774 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7775 [search_ resignFirstResponder];
7779 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7780 [search_ setText:@""];
7781 [self searchBarButtonClicked:searchBar];
7784 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7785 [self searchBarButtonClicked:searchBar];
7788 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7789 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7793 - (bool) shouldYield {
7797 - (bool) shouldBlock {
7798 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7801 - (bool) isSummarized {
7802 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7805 - (bool) showsSections {
7809 - (NSMutableArray *) _reloadPackages {
7810 NSMutableArray *packages([super _reloadPackages]);
7811 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7812 [packages radixSortUsingSelector:@selector(rank)];
7816 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7817 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[self termsForQuery:query]])) {
7818 search_ = [[[UISearchBar alloc] init] autorelease];
7819 [search_ setDelegate:self];
7822 [search_ setText:query];
7826 - (void) viewDidAppear:(BOOL)animated {
7827 [super viewDidAppear:animated];
7829 if (!searchloaded_) {
7830 searchloaded_ = YES;
7831 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7832 [search_ layoutSubviews];
7833 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7835 UITextField *textField;
7836 if ([search_ respondsToSelector:@selector(searchField)])
7837 textField = [search_ searchField];
7839 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7841 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7842 [textField setEnablesReturnKeyAutomatically:NO];
7843 [[self navigationItem] setTitleView:textField];
7846 if ([self isSummarized])
7847 [search_ becomeFirstResponder];
7850 - (void) reloadData {
7851 id object([search_ text]);
7852 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7853 object = [self termsForQuery:object];
7855 [self setObject:object];
7861 - (void) didSelectPackage:(Package *)package {
7862 [search_ resignFirstResponder];
7863 [super didSelectPackage:package];
7868 /* Package Settings Controller {{{ */
7869 @interface PackageSettingsController : CyteViewController <
7870 UITableViewDataSource,
7873 _transient Database *database_;
7875 _H<Package> package_;
7876 _H<UITableView, 2> table_;
7877 _H<UISwitch> subscribedSwitch_;
7878 _H<UISwitch> ignoredSwitch_;
7879 _H<UITableViewCell> subscribedCell_;
7880 _H<UITableViewCell> ignoredCell_;
7883 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7887 @implementation PackageSettingsController
7889 - (NSURL *) navigationURL {
7890 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7893 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7894 if (package_ == nil)
7897 if ([package_ installed] == nil)
7903 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7904 if (package_ == nil)
7907 // both sections contain just one item right now.
7911 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7915 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7917 return UCLocalize("SHOW_ALL_CHANGES_EX");
7919 return UCLocalize("IGNORE_UPGRADES_EX");
7922 - (void) onSubscribed:(id)control {
7923 bool value([control isOn]);
7924 if (package_ == nil)
7926 if ([package_ setSubscribed:value])
7927 [delegate_ updateData];
7930 - (void) _updateIgnored {
7931 const char *package([name_ UTF8String]);
7932 bool on([ignoredSwitch_ isOn]);
7934 pid_t pid(ExecFork());
7936 FILE *dpkg(popen("dpkg --set-selections", "w"));
7937 fwrite(package, strlen(package), 1, dpkg);
7940 fwrite(" hold\n", 6, 1, dpkg);
7942 fwrite(" install\n", 9, 1, dpkg);
7950 - (void) onIgnored:(id)control {
7951 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7952 [invocation setTarget:self];
7953 [invocation setSelector:@selector(_updateIgnored)];
7955 [delegate_ reloadDataWithInvocation:invocation];
7958 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7959 if (package_ == nil)
7962 switch ([indexPath section]) {
7963 case 0: return subscribedCell_;
7964 case 1: return ignoredCell_;
7973 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7974 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7975 [self setView:view];
7977 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7978 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7979 [(UITableView *) table_ setDataSource:self];
7980 [table_ setDelegate:self];
7981 [view addSubview:table_];
7983 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7984 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7985 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7987 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7988 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7989 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7991 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7992 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7993 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7994 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7996 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7997 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7998 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7999 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8002 - (void) viewDidLoad {
8003 [super viewDidLoad];
8005 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8008 - (void) releaseSubviews {
8010 subscribedCell_ = nil;
8012 ignoredSwitch_ = nil;
8013 subscribedSwitch_ = nil;
8015 [super releaseSubviews];
8018 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8019 if ((self = [super init]) != nil) {
8020 database_ = database;
8025 - (void) reloadData {
8028 package_ = [database_ packageWithName:name_];
8030 if (package_ != nil) {
8031 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8032 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8033 } // XXX: what now, G?
8035 [table_ reloadData];
8041 /* Installed Controller {{{ */
8042 @interface InstalledController : FilteredPackageListController {
8046 - (id) initWithDatabase:(Database *)database;
8048 - (void) updateRoleButton;
8049 - (void) queueStatusDidChange;
8053 @implementation InstalledController
8055 - (NSURL *) referrerURL {
8056 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8059 - (NSURL *) navigationURL {
8060 return [NSURL URLWithString:@"cydia://installed"];
8063 - (id) initWithDatabase:(Database *)database {
8064 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8065 [self updateRoleButton];
8066 [self queueStatusDidChange];
8071 - (void) queueButtonClicked {
8076 - (void) queueStatusDidChange {
8080 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8081 initWithTitle:UCLocalize("QUEUE")
8082 style:UIBarButtonItemStyleDone
8084 action:@selector(queueButtonClicked)
8087 [[self navigationItem] setLeftBarButtonItem:nil];
8093 - (void) updateRoleButton {
8094 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8095 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8096 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8097 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8099 action:@selector(roleButtonClicked)
8103 - (void) roleButtonClicked {
8104 [self setObject:[NSNumber numberWithBool:expert_]];
8108 [self updateRoleButton];
8114 /* Source Cell {{{ */
8115 @interface SourceCell : CyteTableViewCell <
8116 CyteTableViewCellDelegate
8120 _H<NSString> origin_;
8121 _H<NSString> label_;
8124 - (void) setSource:(Source *)source;
8128 @implementation SourceCell
8130 - (void) _setImage:(NSArray *)data {
8131 if ([url_ isEqual:[data objectAtIndex:0]]) {
8132 icon_ = [data objectAtIndex:1];
8133 [content_ setNeedsDisplay];
8137 - (void) _setSource:(NSURL *) url {
8138 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8140 if (NSData *data = [NSURLConnection
8141 sendSynchronousRequest:[NSURLRequest
8143 cachePolicy:NSURLRequestUseProtocolCachePolicy
8147 returningResponse:NULL
8150 if (UIImage *image = [UIImage imageWithData:data])
8151 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8156 - (void) setSource:(Source *)source {
8157 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8159 origin_ = [source name];
8160 label_ = [source rooturi];
8162 [content_ setNeedsDisplay];
8164 url_ = [source iconURL];
8165 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8168 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8169 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8170 UIView *content([self contentView]);
8171 CGRect bounds([content bounds]);
8173 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8174 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8175 [content_ setBackgroundColor:[UIColor whiteColor]];
8176 [content addSubview:content_];
8178 [content_ setDelegate:self];
8179 [content_ setOpaque:YES];
8181 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8185 - (NSString *) accessibilityLabel {
8189 - (void) drawContentRect:(CGRect)rect {
8190 bool highlighted(highlighted_);
8191 float width(rect.size.width);
8195 rect.size = [(UIImage *) icon_ size];
8197 while (rect.size.width > 32 || rect.size.height > 32) {
8198 rect.size.width /= 2;
8199 rect.size.height /= 2;
8202 rect.origin.x = 26 - rect.size.width / 2;
8203 rect.origin.y = 26 - rect.size.height / 2;
8205 [icon_ drawInRect:rect];
8208 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8213 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 61) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8217 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 61) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8222 /* Source Controller {{{ */
8223 @interface SourceController : FilteredPackageListController {
8224 _transient Source *source_;
8228 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8232 @implementation SourceController
8234 - (NSURL *) referrerURL {
8235 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sources/%@", UI_, [key_ stringByAddingPercentEscapesIncludingReserved]]];
8238 - (NSURL *) navigationURL {
8239 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8242 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8243 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8245 key_ = [source key];
8249 - (void) reloadData {
8250 source_ = [database_ sourceWithKey:key_];
8251 key_ = [source_ key];
8252 [self setObject:source_];
8254 [[self navigationItem] setTitle:[source_ label]];
8261 /* Sources Controller {{{ */
8262 @interface SourcesController : CyteViewController <
8263 UITableViewDataSource,
8266 _transient Database *database_;
8269 _H<UITableView, 2> list_;
8270 _H<NSMutableArray> sources_;
8274 _H<UIProgressHUD> hud_;
8277 //NSURLConnection *installer_;
8278 NSURLConnection *trivial_bz2_;
8279 NSURLConnection *trivial_gz_;
8280 //NSURLConnection *automatic_;
8285 - (id) initWithDatabase:(Database *)database;
8286 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8290 @implementation SourcesController
8292 - (void) _releaseConnection:(NSURLConnection *)connection {
8293 if (connection != nil) {
8294 [connection cancel];
8295 //[connection setDelegate:nil];
8296 [connection release];
8301 //[self _releaseConnection:installer_];
8302 [self _releaseConnection:trivial_gz_];
8303 [self _releaseConnection:trivial_bz2_];
8304 //[self _releaseConnection:automatic_];
8309 - (NSURL *) navigationURL {
8310 return [NSURL URLWithString:@"cydia://sources"];
8313 - (void) viewDidAppear:(BOOL)animated {
8314 [super viewDidAppear:animated];
8315 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8318 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8322 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8326 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8327 return [sources_ count];
8330 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8331 @synchronized (database_) {
8332 if ([database_ era] != era_)
8335 NSUInteger index([indexPath row]);
8336 return index < [sources_ count] ? [sources_ objectAtIndex:index] : nil;
8339 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8340 static NSString *cellIdentifier = @"SourceCell";
8342 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8343 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8344 [cell setSource:[self sourceAtIndexPath:indexPath]];
8345 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8350 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8351 Source *source = [self sourceAtIndexPath:indexPath];
8352 if (source == nil) return;
8354 SourceController *controller = [[[SourceController alloc]
8355 initWithDatabase:database_
8359 [controller setDelegate:delegate_];
8361 [[self navigationController] pushViewController:controller animated:YES];
8364 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8365 Source *source = [self sourceAtIndexPath:indexPath];
8366 return [source record] != nil;
8369 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8370 if (editingStyle == UITableViewCellEditingStyleDelete) {
8371 Source *source = [self sourceAtIndexPath:indexPath];
8372 if (source == nil) return;
8374 [Sources_ removeObjectForKey:[source key]];
8377 [delegate_ _saveConfig];
8378 [delegate_ reloadDataWithInvocation:nil];
8383 [delegate_ addTrivialSource:href_];
8386 [delegate_ syncData];
8389 - (NSString *) getWarning {
8390 NSString *href(href_);
8391 NSRange colon([href rangeOfString:@"://"]);
8392 if (colon.location != NSNotFound)
8393 href = [href substringFromIndex:(colon.location + 3)];
8394 href = [href stringByAddingPercentEscapes];
8395 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8397 NSURL *url([NSURL URLWithString:href]);
8399 NSStringEncoding encoding;
8400 NSError *error(nil);
8402 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8403 return [warning length] == 0 ? nil : warning;
8407 - (void) _endConnection:(NSURLConnection *)connection {
8408 // XXX: the memory management in this method is horribly awkward
8410 NSURLConnection **field = NULL;
8411 if (connection == trivial_bz2_)
8412 field = &trivial_bz2_;
8413 else if (connection == trivial_gz_)
8414 field = &trivial_gz_;
8415 _assert(field != NULL);
8416 [connection release];
8420 trivial_bz2_ == nil &&
8423 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8425 [delegate_ releaseNetworkActivityIndicator];
8427 [delegate_ removeProgressHUD:hud_];
8431 if (warning != nil) {
8432 UIAlertView *alert = [[[UIAlertView alloc]
8433 initWithTitle:UCLocalize("SOURCE_WARNING")
8436 cancelButtonTitle:UCLocalize("CANCEL")
8438 UCLocalize("ADD_ANYWAY"),
8442 [alert setContext:@"warning"];
8443 [alert setNumberOfRows:1];
8446 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8452 } else if (error_ != nil) {
8453 UIAlertView *alert = [[[UIAlertView alloc]
8454 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8455 message:[error_ localizedDescription]
8457 cancelButtonTitle:UCLocalize("OK")
8458 otherButtonTitles:nil
8461 [alert setContext:@"urlerror"];
8466 UIAlertView *alert = [[[UIAlertView alloc]
8467 initWithTitle:UCLocalize("NOT_REPOSITORY")
8468 message:UCLocalize("NOT_REPOSITORY_EX")
8470 cancelButtonTitle:UCLocalize("OK")
8471 otherButtonTitles:nil
8474 [alert setContext:@"trivial"];
8484 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8485 switch ([response statusCode]) {
8491 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8492 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8494 [self _endConnection:connection];
8497 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8498 [self _endConnection:connection];
8501 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8502 NSURL *url([NSURL URLWithString:href]);
8504 NSMutableURLRequest *request = [NSMutableURLRequest
8506 cachePolicy:NSURLRequestUseProtocolCachePolicy
8510 [request setHTTPMethod:method];
8512 if (Machine_ != NULL)
8513 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8515 if (UniqueID_ != nil)
8516 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8518 if ([url isCydiaSecure]) {
8519 if (UniqueID_ != nil)
8520 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8523 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8526 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8527 NSString *context([alert context]);
8529 if ([context isEqualToString:@"source"]) {
8532 NSString *href = [[alert textField] text];
8534 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8536 if (![href hasSuffix:@"/"])
8537 href_ = [href stringByAppendingString:@"/"];
8541 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8542 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8543 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8547 // XXX: this is stupid
8548 hud_ = [delegate_ addProgressHUD];
8549 [hud_ setText:UCLocalize("VERIFYING_URL")];
8550 [delegate_ retainNetworkActivityIndicator];
8559 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8560 } else if ([context isEqualToString:@"trivial"])
8561 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8562 else if ([context isEqualToString:@"urlerror"])
8563 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8564 else if ([context isEqualToString:@"warning"]) {
8567 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8576 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8581 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8582 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8583 [list_ setRowHeight:53];
8584 [(UITableView *) list_ setDataSource:self];
8585 [list_ setDelegate:self];
8586 [self setView:list_];
8589 - (void) viewDidLoad {
8590 [super viewDidLoad];
8592 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8593 [self updateButtonsForEditingStatusAnimated:NO];
8596 - (void) viewWillAppear:(BOOL)animated {
8597 [super viewWillAppear:animated];
8599 [list_ setEditing:NO];
8600 [self updateButtonsForEditingStatusAnimated:NO];
8603 - (void) releaseSubviews {
8608 [super releaseSubviews];
8611 - (id) initWithDatabase:(Database *)database {
8612 if ((self = [super init]) != nil) {
8613 database_ = database;
8617 - (void) reloadData {
8620 @synchronized (database_) {
8621 era_ = [database_ era];
8623 sources_ = [NSMutableArray arrayWithCapacity:16];
8624 [sources_ addObjectsFromArray:[database_ sources]];
8626 [sources_ sortUsingSelector:@selector(compareByName:)];
8629 int count([sources_ count]);
8631 for (int i = 0; i != count; i++) {
8632 if ([[sources_ objectAtIndex:i] record] == nil)
8640 - (void) showAddSourcePrompt {
8641 UIAlertView *alert = [[[UIAlertView alloc]
8642 initWithTitle:UCLocalize("ENTER_APT_URL")
8645 cancelButtonTitle:UCLocalize("CANCEL")
8647 UCLocalize("ADD_SOURCE"),
8651 [alert setContext:@"source"];
8653 [alert setNumberOfRows:1];
8654 [alert addTextFieldWithValue:@"http://" label:@""];
8656 UITextInputTraits *traits = [[alert textField] textInputTraits];
8657 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8658 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8659 [traits setKeyboardType:UIKeyboardTypeURL];
8660 // XXX: UIReturnKeyDone
8661 [traits setReturnKeyType:UIReturnKeyNext];
8666 - (void) addButtonClicked {
8667 [self showAddSourcePrompt];
8670 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8671 BOOL editing([list_ isEditing]);
8673 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8674 initWithTitle:UCLocalize("ADD")
8675 style:UIBarButtonItemStylePlain
8677 action:@selector(addButtonClicked)
8678 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8680 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8681 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8682 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8684 action:@selector(editButtonClicked)
8685 ] autorelease] animated:animated];
8687 if (IsWildcat_ && !editing)
8688 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8689 initWithTitle:UCLocalize("SETTINGS")
8690 style:UIBarButtonItemStylePlain
8692 action:@selector(settingsButtonClicked)
8696 - (void) settingsButtonClicked {
8697 [delegate_ showSettings];
8700 - (void) editButtonClicked {
8701 [list_ setEditing:![list_ isEditing] animated:YES];
8702 [self updateButtonsForEditingStatusAnimated:YES];
8708 /* Settings Controller {{{ */
8709 @interface SettingsController : CyteViewController <
8710 UITableViewDataSource,
8713 _transient Database *database_;
8714 // XXX: ok, "roledelegate_"?...
8715 _transient id roledelegate_;
8716 _H<UITableView, 2> table_;
8717 _H<UISegmentedControl> segment_;
8718 _H<UIView> container_;
8721 - (void) showDoneButton;
8722 - (void) resizeSegmentedControl;
8726 @implementation SettingsController
8729 table_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
8730 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8731 [table_ setDelegate:self];
8732 [(UITableView *) table_ setDataSource:self];
8733 [self setView:table_];
8735 NSArray *items = [NSArray arrayWithObjects:
8737 UCLocalize("HACKER"),
8738 UCLocalize("DEVELOPER"),
8740 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8741 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8742 [container_ addSubview:segment_];
8745 - (void) viewDidLoad {
8746 [super viewDidLoad];
8748 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8751 if ([Role_ isEqualToString:@"User"]) index = 0;
8752 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8753 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8755 [segment_ setSelectedSegmentIndex:index];
8756 [self showDoneButton];
8759 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8760 [self resizeSegmentedControl];
8763 - (void) releaseSubviews {
8768 [super releaseSubviews];
8771 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8772 if ((self = [super init]) != nil) {
8773 database_ = database;
8774 roledelegate_ = delegate;
8778 - (void) resizeSegmentedControl {
8779 CGFloat width = [[self view] frame].size.width;
8780 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8783 - (void) viewWillAppear:(BOOL)animated {
8784 [super viewWillAppear:animated];
8785 [self resizeSegmentedControl];
8788 - (void) viewDidAppear:(BOOL)animated {
8789 [super viewDidAppear:animated];
8790 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
8791 [self resizeSegmentedControl];
8794 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8795 [self resizeSegmentedControl];
8798 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8799 [self resizeSegmentedControl];
8803 NSString *role(nil);
8805 switch ([segment_ selectedSegmentIndex]) {
8806 case 0: role = @"User"; break;
8807 case 1: role = @"Hacker"; break;
8808 case 2: role = @"Developer"; break;
8813 if (![role isEqualToString:Role_]) {
8814 bool rolling(Role_ == nil);
8817 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8821 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8825 [roledelegate_ loadData];
8827 [roledelegate_ updateData];
8831 - (void) segmentChanged:(UISegmentedControl *)control {
8832 [self showDoneButton];
8835 - (void) saveAndClose {
8838 [[self navigationItem] setRightBarButtonItem:nil];
8839 [[self navigationController] dismissModalViewControllerAnimated:YES];
8842 - (void) doneButtonClicked {
8843 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8844 [spinner startAnimating];
8845 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8846 [[self navigationItem] setRightBarButtonItem:spinItem];
8848 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8851 - (void) showDoneButton {
8852 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8853 initWithTitle:UCLocalize("DONE")
8854 style:UIBarButtonItemStyleDone
8856 action:@selector(doneButtonClicked)
8857 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8860 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8861 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8865 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8869 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8870 return nil; // This method is required by the protocol.
8873 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8875 return UCLocalize("ROLE_EX");
8877 return [NSString stringWithFormat:
8878 @"%@: %@\n%@: %@\n%@: %@",
8879 UCLocalize("USER"), UCLocalize("USER_EX"),
8880 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8881 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8886 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8887 return section == 3 ? 44.0f : 0;
8890 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8891 return section == 3 ? container_ : nil;
8894 - (void) reloadData {
8897 [table_ reloadData];
8902 /* Stash Controller {{{ */
8903 @interface StashController : CyteViewController {
8904 _H<UIActivityIndicatorView> spinner_;
8905 _H<UILabel> status_;
8906 _H<UILabel> caption_;
8911 @implementation StashController
8914 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8915 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8916 [self setView:view];
8918 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8920 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8921 CGRect spinrect = [spinner_ frame];
8922 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8923 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8924 [spinner_ setFrame:spinrect];
8925 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8926 [view addSubview:spinner_];
8927 [spinner_ startAnimating];
8930 captrect.size.width = [[self view] frame].size.width;
8931 captrect.size.height = 40.0f;
8932 captrect.origin.x = 0;
8933 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8934 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8935 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8936 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8937 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8938 [caption_ setTextColor:[UIColor whiteColor]];
8939 [caption_ setBackgroundColor:[UIColor clearColor]];
8940 [caption_ setShadowColor:[UIColor blackColor]];
8941 [caption_ setTextAlignment:UITextAlignmentCenter];
8942 [view addSubview:caption_];
8945 statusrect.size.width = [[self view] frame].size.width;
8946 statusrect.size.height = 30.0f;
8947 statusrect.origin.x = 0;
8948 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8949 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8950 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8951 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8952 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8953 [status_ setTextColor:[UIColor whiteColor]];
8954 [status_ setBackgroundColor:[UIColor clearColor]];
8955 [status_ setShadowColor:[UIColor blackColor]];
8956 [status_ setTextAlignment:UITextAlignmentCenter];
8957 [view addSubview:status_];
8960 - (void) releaseSubviews {
8965 [super releaseSubviews];
8971 @interface CYURLCache : SDURLCache {
8976 @implementation CYURLCache
8978 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8981 else if ([event isEqualToString:@"no-cache"])
8983 else if ([event isEqualToString:@"store"])
8985 else if ([event isEqualToString:@"invalid"])
8987 else if ([event isEqualToString:@"memory"])
8989 else if ([event isEqualToString:@"disk"])
8991 else if ([event isEqualToString:@"miss"])
8994 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8998 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8999 if (NSURLResponse *response = [cached response])
9000 if (NSString *mime = [response MIMEType])
9001 if ([mime isEqualToString:@"text/cache-manifest"]) {
9002 NSURL *url([response URL]);
9005 NSLog(@"###: %@", [url absoluteString]);
9008 @synchronized (HostConfig_) {
9009 [CachedURLs_ addObject:url];
9013 [super storeCachedResponse:cached forRequest:request];
9018 @interface Cydia : UIApplication <
9019 ConfirmationControllerDelegate,
9022 UINavigationControllerDelegate,
9023 UITabBarControllerDelegate
9025 _H<UIWindow> window_;
9026 _H<CydiaTabBarController> tabbar_;
9027 _H<CydiaLoadingViewController> emulated_;
9029 _H<NSMutableArray> essential_;
9030 _H<NSMutableArray> broken_;
9032 Database *database_;
9034 _H<NSURL> starturl_;
9039 _H<StashController> stash_;
9048 @implementation Cydia
9050 - (void) lockSuspend {
9051 if (locked_++ == 0) {
9052 if ($SBSSetInterceptsMenuButtonForever != NULL)
9053 (*$SBSSetInterceptsMenuButtonForever)(true);
9055 [self setIdleTimerDisabled:YES];
9059 - (void) unlockSuspend {
9060 if (--locked_ == 0) {
9061 [self setIdleTimerDisabled:NO];
9063 if ($SBSSetInterceptsMenuButtonForever != NULL)
9064 (*$SBSSetInterceptsMenuButtonForever)(false);
9068 - (void) beginUpdate {
9069 [tabbar_ beginUpdate];
9073 return [tabbar_ updating];
9077 if ([broken_ count] != 0) {
9078 int count = [broken_ count];
9080 UIAlertView *alert = [[[UIAlertView alloc]
9081 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9082 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9084 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9086 UCLocalize("TEMPORARY_IGNORE"),
9090 [alert setContext:@"fixhalf"];
9091 [alert setNumberOfRows:2];
9093 } else if (!Ignored_ && [essential_ count] != 0) {
9094 int count = [essential_ count];
9096 UIAlertView *alert = [[[UIAlertView alloc]
9097 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9098 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9100 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9102 UCLocalize("UPGRADE_ESSENTIAL"),
9103 UCLocalize("COMPLETE_UPGRADE"),
9107 [alert setContext:@"upgrade"];
9112 - (void) returnToCydia {
9116 - (void) _saveConfig {
9117 @synchronized (database_) {
9124 NSString *error(nil);
9126 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9128 NSError *error(nil);
9129 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9130 NSLog(@"failure to save metadata data: %@", error);
9135 NSLog(@"failure to serialize metadata: %@", error);
9139 CydiaWriteSources();
9142 // Navigation controller for the queuing badge.
9143 - (UINavigationController *) queueNavigationController {
9144 NSArray *controllers = [tabbar_ viewControllers];
9145 return [controllers objectAtIndex:3];
9148 - (void) unloadData {
9149 [tabbar_ unloadData];
9152 - (void) _updateData {
9156 UINavigationController *navigation = [self queueNavigationController];
9158 id queuedelegate = nil;
9159 if ([[navigation viewControllers] count] > 0)
9160 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9162 [queuedelegate queueStatusDidChange];
9163 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9166 - (void) _refreshIfPossible:(NSDate *)update {
9167 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9169 bool recently = false;
9170 if (update != nil) {
9171 NSTimeInterval interval([update timeIntervalSinceNow]);
9172 if (interval <= 0 && interval > -(15*60))
9176 // Don't automatic refresh if:
9177 // - We already refreshed recently.
9178 // - We already auto-refreshed this launch.
9179 // - Auto-refresh is disabled.
9180 // - Cydia's server is not reachable
9181 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9182 // If we are cancelling, we need to make sure it knows it's already loaded.
9185 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9187 // We are going to load, so remember that.
9190 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9196 - (void) refreshIfPossible {
9197 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9200 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9201 @synchronized (self) {
9202 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9204 [hud setText:UCLocalize("RELOADING_DATA")];
9206 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9210 [essential_ removeAllObjects];
9211 [broken_ removeAllObjects];
9213 NSArray *packages([database_ packages]);
9214 for (Package *package in packages) {
9216 [broken_ addObject:package];
9217 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9218 if ([package essential] && [package installed] != nil)
9219 [essential_ addObject:package];
9224 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9227 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9228 [changesItem setBadgeValue:badge];
9229 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9230 [self setApplicationIconBadgeNumber:changes];
9233 [changesItem setBadgeValue:nil];
9234 [changesItem setAnimatedBadge:NO];
9235 [self setApplicationIconBadgeNumber:0];
9241 [self removeProgressHUD:hud];
9244 - (void) updateData {
9248 - (void) updateDataAndLoad {
9250 if ([database_ progressDelegate] == nil)
9256 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9259 - (void) disemulate {
9260 if (emulated_ == nil)
9263 [window_ addSubview:[tabbar_ view]];
9264 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9265 [window_ setRootViewController:tabbar_];
9266 [[emulated_ view] removeFromSuperview];
9268 [window_ setUserInteractionEnabled:YES];
9271 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9272 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9274 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9276 UIViewController *parent;
9277 if (emulated_ == nil)
9286 [parent presentModalViewController:navigation animated:YES];
9289 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9290 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9292 if (navigation != nil)
9293 [navigation pushViewController:progress animated:YES];
9295 [self presentModalViewController:progress force:YES];
9297 [progress invoke:invocation withTitle:title];
9301 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9302 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9305 - (void) repairWithInvocation:(NSInvocation *)invocation {
9307 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9311 - (void) repairWithSelector:(SEL)selector {
9312 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9315 - (void) reloadData {
9316 [self reloadDataWithInvocation:nil];
9317 if ([database_ progressDelegate] == nil)
9323 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9326 - (void) addSource:(NSDictionary *) source {
9327 CydiaAddSource(source);
9330 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9331 CydiaAddSource(href, distribution, sections);
9334 - (void) addTrivialSource:(NSString *)href {
9335 CydiaAddSource(href, @"./");
9338 - (void) updateValues {
9343 pkgProblemResolver *resolver = [database_ resolver];
9345 resolver->InstallProtect();
9346 if (!resolver->Resolve(true))
9351 // XXX: this is a really crappy way of doing this.
9352 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9353 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9354 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9355 if ([tabbar_ updating])
9356 [tabbar_ cancelUpdate];
9358 if (![database_ prepare])
9361 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9362 [page setDelegate:self];
9363 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9366 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9367 [tabbar_ presentModalViewController:confirm_ animated:YES];
9373 @synchronized (self) {
9378 - (void) clearPackage:(Package *)package {
9379 @synchronized (self) {
9386 - (void) installPackages:(NSArray *)packages {
9387 @synchronized (self) {
9388 for (Package *package in packages)
9395 - (void) installPackage:(Package *)package {
9396 @synchronized (self) {
9403 - (void) removePackage:(Package *)package {
9404 @synchronized (self) {
9411 - (void) distUpgrade {
9412 @synchronized (self) {
9413 if (![database_ upgrade])
9421 system("su -c /usr/bin/uicache mobile");
9426 UIProgressHUD *hud([self addProgressHUD]);
9427 [hud setText:UCLocalize("LOADING")];
9428 [self yieldToSelector:@selector(_uicache)];
9429 [self removeProgressHUD:hud];
9433 [database_ perform];
9434 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9435 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9438 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9441 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9442 [self unlockSuspend];
9445 - (void) showSettings {
9446 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9449 - (void) retainNetworkActivityIndicator {
9450 if (activity_++ == 0)
9451 [self setNetworkActivityIndicatorVisible:YES];
9454 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9458 - (void) releaseNetworkActivityIndicator {
9459 if (--activity_ == 0)
9460 [self setNetworkActivityIndicatorVisible:NO];
9463 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9468 - (void) cancelAndClear:(bool)clear {
9469 @synchronized (self) {
9481 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9482 NSString *context([alert context]);
9484 if ([context isEqualToString:@"conffile"]) {
9485 FILE *input = [database_ input];
9486 if (button == [alert cancelButtonIndex])
9487 fprintf(input, "N\n");
9488 else if (button == [alert firstOtherButtonIndex])
9489 fprintf(input, "Y\n");
9492 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9493 } else if ([context isEqualToString:@"fixhalf"]) {
9494 if (button == [alert cancelButtonIndex]) {
9495 @synchronized (self) {
9496 for (Package *broken in (id) broken_) {
9499 NSString *id = [broken id];
9500 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9501 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9502 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9503 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9509 } else if (button == [alert firstOtherButtonIndex]) {
9510 [broken_ removeAllObjects];
9514 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9515 } else if ([context isEqualToString:@"upgrade"]) {
9516 if (button == [alert firstOtherButtonIndex]) {
9517 @synchronized (self) {
9518 for (Package *essential in (id) essential_)
9519 [essential install];
9524 } else if (button == [alert firstOtherButtonIndex] + 1) {
9526 } else if (button == [alert cancelButtonIndex]) {
9530 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9534 - (void) system:(NSString *)command {
9535 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9538 system([command UTF8String]);
9544 - (void) applicationWillSuspend {
9546 [super applicationWillSuspend];
9549 - (BOOL) isSafeToSuspend {
9552 NSLog(@"isSafeToSuspend: locked_ != 0");
9557 // Use external process status API internally.
9558 // This is probably a really bad idea.
9559 // XXX: what is the point of this? does this solve anything at all?
9560 uint64_t status = 0;
9562 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9563 notify_get_state(notify_token, &status);
9564 notify_cancel(notify_token);
9569 NSLog(@"isSafeToSuspend: status != 0");
9575 NSLog(@"isSafeToSuspend: -> true");
9580 - (void) applicationSuspend:(__GSEvent *)event {
9581 if ([self isSafeToSuspend])
9582 [super applicationSuspend:event];
9585 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9586 if ([self isSafeToSuspend])
9587 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9590 - (void) _setSuspended:(BOOL)value {
9591 if ([self isSafeToSuspend])
9592 [super _setSuspended:value];
9595 - (UIProgressHUD *) addProgressHUD {
9596 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9597 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9599 [window_ setUserInteractionEnabled:NO];
9601 UIViewController *target(tabbar_);
9602 if (UIViewController *modal = [target modalViewController])
9605 [hud showInView:[target view]];
9611 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9612 [self unlockSuspend];
9614 [hud removeFromSuperview];
9615 [window_ setUserInteractionEnabled:YES];
9618 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9619 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9622 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9623 NSString *scheme([[url scheme] lowercaseString]);
9624 if ([[url absoluteString] length] <= [scheme length] + 3)
9626 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9627 NSArray *components([path componentsSeparatedByString:@"/"]);
9629 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9630 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9631 if (controller != nil)
9632 [controller setDelegate:self];
9636 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9639 NSString *base([components objectAtIndex:0]);
9641 CyteViewController *controller = nil;
9643 if ([base isEqualToString:@"url"]) {
9644 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9645 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9646 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9647 } else if (!external && [components count] == 1) {
9648 if ([base isEqualToString:@"manage"]) {
9649 controller = [[[ManageController alloc] init] autorelease];
9652 if ([base isEqualToString:@"storage"]) {
9653 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9656 if ([base isEqualToString:@"sources"]) {
9657 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9660 if ([base isEqualToString:@"home"]) {
9661 controller = [[[HomeController alloc] init] autorelease];
9664 if ([base isEqualToString:@"sections"]) {
9665 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9668 if ([base isEqualToString:@"search"]) {
9669 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9672 if ([base isEqualToString:@"changes"]) {
9673 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9676 if ([base isEqualToString:@"installed"]) {
9677 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9679 } else if ([components count] == 2) {
9680 NSString *argument = [components objectAtIndex:1];
9682 if ([base isEqualToString:@"package"]) {
9683 controller = [self pageForPackage:argument withReferrer:referrer];
9686 if (!external && [base isEqualToString:@"search"]) {
9687 controller = [[[SearchController alloc] initWithDatabase:database_ query:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9690 if (!external && [base isEqualToString:@"sections"]) {
9691 if ([argument isEqualToString:@"all"])
9693 controller = [[[SectionController alloc] initWithDatabase:database_ section:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9696 if (!external && [base isEqualToString:@"sources"]) {
9697 if ([argument isEqualToString:@"add"]) {
9698 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9699 [(SourcesController *)controller showAddSourcePrompt];
9701 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9702 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9706 if (!external && [base isEqualToString:@"launch"]) {
9707 [self launchApplicationWithIdentifier:argument suspended:NO];
9710 } else if (!external && [components count] == 3) {
9711 NSString *arg1 = [components objectAtIndex:1];
9712 NSString *arg2 = [components objectAtIndex:2];
9714 if ([base isEqualToString:@"package"]) {
9715 if ([arg2 isEqualToString:@"settings"]) {
9716 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9717 } else if ([arg2 isEqualToString:@"files"]) {
9718 if (Package *package = [database_ packageWithName:arg1]) {
9719 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9720 [(FileTable *)controller setPackage:package];
9726 [controller setDelegate:self];
9730 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9731 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9734 [tabbar_ setUnselectedViewController:page];
9739 - (void) applicationOpenURL:(NSURL *)url {
9740 [super applicationOpenURL:url];
9745 [self openCydiaURL:url forExternal:YES];
9748 - (void) applicationWillResignActive:(UIApplication *)application {
9749 // Stop refreshing if you get a phone call or lock the device.
9750 if ([tabbar_ updating])
9751 [tabbar_ cancelUpdate];
9753 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9754 [super applicationWillResignActive:application];
9757 - (void) saveState {
9758 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9759 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9760 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9766 - (void) applicationWillTerminate:(UIApplication *)application {
9770 - (void) setConfigurationData:(NSString *)data {
9771 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9773 if (!conffile_r(data)) {
9774 lprintf("E:invalid conffile\n");
9778 NSString *ofile = conffile_r[1];
9779 //NSString *nfile = conffile_r[2];
9781 UIAlertView *alert = [[[UIAlertView alloc]
9782 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9783 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9785 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9787 UCLocalize("ACCEPT_NEW_COPY"),
9788 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9792 [alert setContext:@"conffile"];
9793 [alert setNumberOfRows:2];
9797 - (void) addStashController {
9799 stash_ = [[[StashController alloc] init] autorelease];
9800 [window_ addSubview:[stash_ view]];
9803 - (void) removeStashController {
9804 [[stash_ view] removeFromSuperview];
9806 [self unlockSuspend];
9810 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9811 UpdateExternalStatus(1);
9812 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9813 UpdateExternalStatus(0);
9815 [self removeStashController];
9817 pid_t pid(ExecFork());
9819 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9820 perror("launchctl stop");
9826 - (void) setupViewControllers {
9827 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9829 NSMutableArray *items;
9830 if (kCFCoreFoundationVersionNumber < 800) {
9831 items = [NSMutableArray arrayWithObjects:
9832 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9833 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9834 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9835 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9839 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9840 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9842 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9845 items = [NSMutableArray arrayWithObjects:
9846 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home7.png"] selectedImage:[UIImage applicationImageNamed:@"home7s.png"]] autorelease],
9847 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install7.png"] selectedImage:[UIImage applicationImageNamed:@"install7s.png"]] autorelease],
9848 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes7.png"] selectedImage:[UIImage applicationImageNamed:@"changes7s.png"]] autorelease],
9849 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search7.png"] selectedImage:[UIImage applicationImageNamed:@"search7s.png"]] autorelease],
9853 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source7.png"] selectedImage:[UIImage applicationImageNamed:@"source7s.png"]] autorelease] atIndex:3];
9854 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage7.png"] selectedImage:[UIImage applicationImageNamed:@"manage7s.png"]] autorelease] atIndex:3];
9856 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage7.png"] selectedImage:[UIImage applicationImageNamed:@"manage7s.png"]] autorelease] atIndex:3];
9860 NSMutableArray *controllers([NSMutableArray array]);
9861 for (UITabBarItem *item in items) {
9862 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9863 [controller setTabBarItem:item];
9864 [controllers addObject:controller];
9866 [tabbar_ setViewControllers:controllers];
9868 [tabbar_ setUpdateDelegate:self];
9871 - (void) _sendMemoryWarningNotification {
9872 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9873 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9875 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9878 - (void) _sendMemoryWarningNotifications {
9880 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9886 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9888 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9891 - (void) applicationDidFinishLaunching:(id)unused {
9892 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9895 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9896 [self setApplicationSupportsShakeToEdit:NO];
9898 @synchronized (HostConfig_) {
9899 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9902 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9903 initWithMemoryCapacity:524288
9904 diskCapacity:10485760
9905 diskPath:[NSString stringWithFormat:@"%@/SDURLCache", Cache_]
9908 [CydiaWebViewController _initialize];
9910 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9912 // this would disallow http{,s} URLs from accessing this data
9913 //[WebView registerURLSchemeAsLocal:@"cydia"];
9915 Font12_ = [UIFont systemFontOfSize:12];
9916 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9917 Font14_ = [UIFont systemFontOfSize:14];
9918 Font18_ = [UIFont systemFontOfSize:18];
9919 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9920 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9922 essential_ = [NSMutableArray arrayWithCapacity:4];
9923 broken_ = [NSMutableArray arrayWithCapacity:4];
9925 // XXX: I really need this thing... like, seriously... I'm sorry
9926 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9928 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9929 [window_ orderFront:self];
9930 [window_ makeKey:self];
9931 [window_ setHidden:NO];
9934 [self addStashController];
9935 // XXX: this would be much cleaner as a yieldToSelector:
9936 // that way the removeStashController could happen right here inline
9937 // we also could no longer require the useless stash_ field anymore
9938 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9943 int error(stat("/", &root));
9944 _assert(error != -1);
9946 #define Stash_(path) do { \
9947 struct stat folder; \
9948 int error(lstat((path), &folder)); \
9949 if (error != -1 && ( \
9950 folder.st_dev == root.st_dev && \
9951 S_ISDIR(folder.st_mode) \
9952 ) || error == -1 && ( \
9953 errno == ENOENT || \
9958 Stash_("/Applications");
9959 Stash_("/Library/Ringtones");
9960 Stash_("/Library/Wallpaper");
9961 //Stash_("/usr/bin");
9962 Stash_("/usr/include");
9963 Stash_("/usr/lib/pam");
9964 Stash_("/usr/share");
9965 //Stash_("/var/lib");
9967 database_ = [Database sharedInstance];
9968 [database_ setDelegate:self];
9970 [window_ setUserInteractionEnabled:NO];
9971 [self setupViewControllers];
9973 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9974 [window_ addSubview:[emulated_ view]];
9975 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9976 [window_ setRootViewController:emulated_];
9978 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9982 - (NSArray *) defaultStartPages {
9983 NSMutableArray *standard = [NSMutableArray array];
9984 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9985 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9986 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9988 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9990 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9991 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9993 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10000 [window_ setUserInteractionEnabled:YES];
10001 [self showSettings];
10004 if ([emulated_ modalViewController] != nil)
10005 [emulated_ dismissModalViewControllerAnimated:YES];
10006 [window_ setUserInteractionEnabled:NO];
10009 [self reloadDataWithInvocation:nil];
10010 [self refreshIfPossible];
10015 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
10016 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
10017 int standardIndex = 0;
10018 NSArray *standard = [self defaultStartPages];
10025 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
10026 if (valid && closed != nil) {
10027 NSTimeInterval interval([closed timeIntervalSinceNow]);
10028 // XXX: Is 30 minutes the optimal time here?
10029 if (interval <= -(30*60))
10033 if (valid && [saved count] != [standard count])
10037 for (unsigned int i = 0; i < [standard count]; i++) {
10038 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10039 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10040 // but it's good enough for now.
10041 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10048 NSArray *items = nil;
10050 [tabbar_ setSelectedIndex:savedIndex];
10053 [tabbar_ setSelectedIndex:standardIndex];
10057 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10058 NSArray *stack = [items objectAtIndex:tab];
10059 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10060 NSMutableArray *current = [NSMutableArray array];
10062 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10063 NSString *addr = [stack objectAtIndex:nav];
10064 NSURL *url = [NSURL URLWithString:addr];
10065 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10067 [current addObject:page];
10070 [navigation setViewControllers:current];
10073 // (Try to) show the startup URL.
10074 if (starturl_ != nil) {
10075 [self openCydiaURL:starturl_ forExternal:NO];
10080 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10081 if (item != nil && IsWildcat_) {
10082 [sheet showFromBarButtonItem:item animated:YES];
10084 [sheet showInView:window_];
10088 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10089 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10090 [progress setTitle:task];
10091 [progress addProgressEvent:event];
10094 - (void) addProgressEventForTask:(NSArray *)data {
10095 CydiaProgressEvent *event([data objectAtIndex:0]);
10096 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10097 [self addProgressEvent:event forTask:task];
10100 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10101 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10107 id Alloc_(id self, SEL selector) {
10108 id object = alloc_(self, selector);
10109 lprintf("[%s]A-%p\n", self->isa->name, object);
10114 id Dealloc_(id self, SEL selector) {
10115 id object = dealloc_(self, selector);
10116 lprintf("[%s]D-%p\n", self->isa->name, object);
10120 static NSSet *MobilizedFiles_;
10122 static NSURL *MobilizeURL(NSURL *url) {
10123 NSString *path([url path]);
10124 if ([path hasPrefix:@"/var/root/"]) {
10125 NSString *file([path substringFromIndex:10]);
10126 if ([MobilizedFiles_ containsObject:file])
10127 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10133 Class $CFXPreferencesPropertyListSource;
10134 @class CFXPreferencesPropertyListSource;
10136 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10137 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10138 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10139 url = MobilizeURL(url);
10140 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10141 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10147 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10148 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10149 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10150 url = MobilizeURL(url);
10151 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10152 //NSLog(@"%@ %@", [url absoluteString], value);
10158 Class $NSURLConnection;
10160 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10161 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10163 NSURL *url([copy URL]);
10165 NSString *host([url host]);
10166 NSString *scheme([[url scheme] lowercaseString]);
10168 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10170 @synchronized (HostConfig_) {
10171 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10172 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10173 [copy setHTTPShouldUsePipelining:YES];
10175 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10176 if ([control isEqualToString:@"max-age=0"])
10177 if ([CachedURLs_ containsObject:url]) {
10179 NSLog(@"~~~: %@", url);
10182 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10184 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10185 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10186 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10190 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10196 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10197 CGSize size([[UIScreen mainScreen] bounds].size);
10198 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10199 if ([$WAKWindow hasLandscapeOrientation])
10200 std::swap(size.width, size.height);*/
10204 Class $NSUserDefaults;
10206 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10207 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10208 return [NSString stringWithFormat:@"%@/LocalStorage", Cache_];
10209 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10212 int main(int argc, char *argv[]) {
10213 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10217 UpdateExternalStatus(0);
10219 UIScreen *screen([UIScreen mainScreen]);
10220 if ([screen respondsToSelector:@selector(scale)])
10221 ScreenScale_ = [screen scale];
10225 UIDevice *device([UIDevice currentDevice]);
10226 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10227 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10228 if (idiom == UIUserInterfaceIdiomPad)
10232 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10234 Pcre pattern("^([0-9]+\\.[0-9]+)");
10236 if (pattern([device systemVersion]))
10237 Firmware_ = pattern[1];
10238 if (pattern(Cydia_))
10239 Major_ = pattern[1];
10241 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10243 HostConfig_ = [[[NSObject alloc] init] autorelease];
10244 @synchronized (HostConfig_) {
10245 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10246 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10247 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10248 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10249 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10252 NSString *ui(@"ui/ios");
10254 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10255 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10256 UI_ = CydiaURL(ui);
10258 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10260 MobilizedFiles_ = [NSMutableSet setWithObjects:
10261 @"Library/Preferences/com.apple.Accessibility.plist",
10262 @"Library/Preferences/com.apple.preferences.sounds.plist",
10265 /* Library Hacks {{{ */
10266 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10268 $WAKWindow = objc_getClass("WAKWindow");
10269 if ($WAKWindow != NULL)
10270 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10271 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10273 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10275 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10276 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10277 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10278 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10281 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10282 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10283 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10284 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10287 $NSURLConnection = objc_getClass("NSURLConnection");
10288 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10289 if (NSURLConnection$init$ != NULL) {
10290 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10291 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10294 $NSUserDefaults = objc_getClass("NSUserDefaults");
10295 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10296 if (NSUserDefaults$objectForKey$ != NULL) {
10297 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10298 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10301 /* Set Locale {{{ */
10302 Locale_ = CFLocaleCopyCurrent();
10303 Languages_ = [NSLocale preferredLanguages];
10305 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10306 //NSLog(@"%@", [Languages_ description]);
10309 if (Locale_ != NULL)
10310 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10311 else if (Languages_ != nil && [Languages_ count] != 0)
10312 lang = [[Languages_ objectAtIndex:0] UTF8String];
10314 // XXX: consider just setting to C and then falling through?
10317 if (lang != NULL) {
10318 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10319 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10322 NSLog(@"Setting Language: %s", lang);
10324 if (lang != NULL) {
10325 setenv("LANG", lang, true);
10326 std::setlocale(LC_ALL, lang);
10330 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10332 /* Parse Arguments {{{ */
10333 bool substrate(false);
10339 for (int argi(1); argi != argc; ++argi)
10340 if (strcmp(argv[argi], "--") == 0) {
10342 argv[argi] = argv[0];
10348 for (int argi(1); argi != arge; ++argi)
10349 if (strcmp(args[argi], "--substrate") == 0)
10352 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10356 App_ = [[NSBundle mainBundle] bundlePath];
10362 if (access("/var/mobile/Library/Keyboard/UserDictionary.sqlite", F_OK) == 0)
10363 system("mkdir -p /var/root/Library/Keyboard; cp -af /var/mobile/Library/Keyboard/UserDictionary.sqlite /var/root/Library/Keyboard/");
10365 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/root"] retain];
10367 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10368 alloc_ = alloc->method_imp;
10369 alloc->method_imp = (IMP) &Alloc_;*/
10371 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10372 dealloc_ = dealloc->method_imp;
10373 dealloc->method_imp = (IMP) &Dealloc_;*/
10375 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10376 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10378 /* System Information {{{ */
10382 size = sizeof(maxproc);
10383 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10384 perror("sysctlbyname(\"kern.maxproc\", ?)");
10385 else if (maxproc < 64) {
10387 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10388 perror("sysctlbyname(\"kern.maxproc\", #)");
10391 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10392 char *osversion = new char[size];
10393 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10394 perror("sysctlbyname(\"kern.osversion\", ?)");
10396 System_ = [NSString stringWithUTF8String:osversion];
10398 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10399 char *machine = new char[size];
10400 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10401 perror("sysctlbyname(\"hw.machine\", ?)");
10403 Machine_ = machine;
10405 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10406 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10407 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10409 UniqueID_ = UniqueIdentifier(device);
10411 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10412 Product_ = [info objectForKey:@"SafariProductVersion"];
10413 Safari_ = [info objectForKey:@"CFBundleVersion"];
10416 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10418 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10419 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10420 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10421 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10422 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10423 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10425 UserAgent_ = agent;
10427 /* Load Database {{{ */
10429 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10431 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10433 if (Metadata_ == NULL)
10434 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10436 Settings_ = [Metadata_ objectForKey:@"Settings"];
10438 Packages_ = [Metadata_ objectForKey:@"Packages"];
10440 Values_ = [Metadata_ objectForKey:@"Values"];
10441 Sections_ = [Metadata_ objectForKey:@"Sections"];
10442 Sources_ = [Metadata_ objectForKey:@"Sources"];
10444 Token_ = [Metadata_ objectForKey:@"Token"];
10446 Version_ = [Metadata_ objectForKey:@"Version"];
10449 if (Settings_ != nil)
10450 Role_ = [Settings_ objectForKey:@"Role"];
10452 if (Values_ == nil) {
10453 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10454 [Metadata_ setObject:Values_ forKey:@"Values"];
10457 if (Sections_ == nil) {
10458 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10459 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10462 if (Sources_ == nil) {
10463 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10464 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10467 if (Version_ == nil) {
10468 Version_ = [NSNumber numberWithUnsignedInt:0];
10469 [Metadata_ setObject:Version_ forKey:@"Version"];
10472 if ([Version_ unsignedIntValue] == 0) {
10473 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10474 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10475 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10476 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10478 Version_ = [NSNumber numberWithUnsignedInt:1];
10479 [Metadata_ setObject:Version_ forKey:@"Version"];
10481 [Metadata_ removeObjectForKey:@"LastUpdate"];
10487 CydiaWriteSources();
10490 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10493 if (Packages_ != nil) {
10495 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10499 [Metadata_ removeObjectForKey:@"Packages"];
10505 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10507 #define MobileSubstrate_(name) \
10508 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10509 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10510 if (handle == NULL) \
10511 NSLog(@"%s", dlerror()); \
10514 MobileSubstrate_(Activator)
10515 MobileSubstrate_(libstatusbar)
10516 MobileSubstrate_(SimulatedKeyEvents)
10517 MobileSubstrate_(WinterBoard)
10519 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10520 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10522 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10524 if (access("/User", F_OK) != 0 || version != 6) {
10526 system("/usr/libexec/cydia/firmware.sh");
10530 _assert([[NSFileManager defaultManager]
10531 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10532 withIntermediateDirectories:YES
10537 if (access("/tmp/cydia.chk", F_OK) == 0) {
10538 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10539 _assert(errno == ENOENT);
10540 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10541 _assert(errno == ENOENT);
10544 /* APT Initialization {{{ */
10545 _assert(pkgInitConfig(*_config));
10546 _assert(pkgInitSystem(*_config, _system));
10549 _config->Set("APT::Acquire::Translation", lang);
10551 // XXX: this timeout might be important :(
10552 //_config->Set("Acquire::http::Timeout", 15);
10554 _config->Set("Acquire::http::MaxParallel", 3);
10556 /* Color Choices {{{ */
10557 space_ = CGColorSpaceCreateDeviceRGB();
10559 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10560 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10561 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10562 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10563 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10564 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10565 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10566 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10567 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10568 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10570 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10571 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10573 /* UIKit Configuration {{{ */
10574 // XXX: I have a feeling this was important
10575 //UIKeyboardDisableAutomaticAppearance();
10578 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10580 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10581 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10582 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10584 PulseInterval_ = fast ? 50000 : 500000;
10586 Colon_ = UCLocalize("COLON_DELIMITED");
10587 Elision_ = UCLocalize("ELISION");
10588 Error_ = UCLocalize("ERROR");
10589 Warning_ = UCLocalize("WARNING");
10592 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10594 CGColorSpaceRelease(space_);
10595 CFRelease(Locale_);