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 source:(Source *)source;
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 source:(Source *)source {
3083 NSString *section([self section]);
3087 section == nil && [name length] == 0 ||
3088 [name isEqualToString:section]
3091 [self source] == source
3092 ) && [self visible];
3095 - (bool) isVisibleInSource:(Source *)source {
3096 return [self source] == source && [self visible];
3101 /* Section Class {{{ */
3102 @interface Section : NSObject {
3107 _H<NSString> localized_;
3110 - (NSComparisonResult) compareByLocalized:(Section *)section;
3111 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3112 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3113 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3114 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3115 - (NSString *) name;
3122 - (void) addToCount;
3124 - (void) setCount:(size_t)count;
3125 - (NSString *) localized;
3129 @implementation Section
3131 - (NSComparisonResult) compareByLocalized:(Section *)section {
3132 NSString *lhs(localized_);
3133 NSString *rhs([section localized]);
3135 /*if ([lhs length] != 0 && [rhs length] != 0) {
3136 unichar lhc = [lhs characterAtIndex:0];
3137 unichar rhc = [rhs characterAtIndex:0];
3139 if (isalpha(lhc) && !isalpha(rhc))
3140 return NSOrderedAscending;
3141 else if (!isalpha(lhc) && isalpha(rhc))
3142 return NSOrderedDescending;
3145 return [lhs compare:rhs options:LaxCompareOptions_];
3148 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3149 if ((self = [self initWithName:name localize:NO]) != nil) {
3150 if (localized != nil)
3151 localized_ = localized;
3155 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3156 return [self initWithName:name row:0 localize:localize];
3159 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3160 if ((self = [super init]) != nil) {
3165 localized_ = LocalizeSection(name_);
3169 /* XXX: localize the index thingees */
3170 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3171 if ((self = [super init]) != nil) {
3172 name_ = [NSString stringWithCharacters:&index length:1];
3178 - (NSString *) name {
3198 - (void) addToCount {
3202 - (void) setCount:(size_t)count {
3206 - (NSString *) localized {
3213 class CydiaLogCleaner :
3214 public pkgArchiveCleaner
3217 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3222 /* Database Implementation {{{ */
3223 @implementation Database
3225 + (Database *) sharedInstance {
3226 static _H<Database> instance;
3227 if (instance == nil)
3228 instance = [[[Database alloc] init] autorelease];
3236 - (void) releasePackages {
3237 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3238 CFArrayRemoveAllValues(packages_);
3242 // XXX: actually implement this thing
3244 [self releasePackages];
3245 apr_pool_destroy(pool_);
3246 NSRecycleZone(zone_);
3250 - (void) _readCydia:(NSNumber *)fd {
3251 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3252 std::istream is(&ib);
3255 static Pcre finish_r("^finish:([^:]*)$");
3257 while (std::getline(is, line)) {
3258 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3260 const char *data(line.c_str());
3261 size_t size = line.size();
3262 lprintf("C:%s\n", data);
3264 if (finish_r(data, size)) {
3265 NSString *finish = finish_r[1];
3266 int index = [Finishes_ indexOfObject:finish];
3267 if (index != INT_MAX && index > Finish_)
3277 - (void) _readStatus:(NSNumber *)fd {
3278 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3279 std::istream is(&ib);
3282 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3283 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3285 while (std::getline(is, line)) {
3286 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3288 const char *data(line.c_str());
3289 size_t size(line.size());
3290 lprintf("S:%s\n", data);
3292 if (conffile_r(data, size)) {
3293 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3294 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3295 } else if (strncmp(data, "status: ", 8) == 0) {
3296 // status: <package>: {unpacked,half-configured,installed}
3297 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3298 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3299 } else if (strncmp(data, "processing: ", 12) == 0) {
3300 // processing: configure: config-test
3301 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3302 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3303 } else if (pmstatus_r(data, size)) {
3304 std::string type([pmstatus_r[1] UTF8String]);
3306 NSString *package = pmstatus_r[2];
3307 if ([package isEqualToString:@"dpkg-exec"])
3310 float percent([pmstatus_r[3] floatValue]);
3311 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3313 NSString *string = pmstatus_r[4];
3315 if (type == "pmerror") {
3316 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3317 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3318 } else if (type == "pmstatus") {
3319 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3320 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3321 } else if (type == "pmconffile")
3322 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3324 lprintf("E:unknown pmstatus\n");
3326 lprintf("E:unknown status\n");
3334 - (void) _readOutput:(NSNumber *)fd {
3335 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3336 std::istream is(&ib);
3339 while (std::getline(is, line)) {
3340 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3342 lprintf("O:%s\n", line.c_str());
3344 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3345 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3357 - (Package *) packageWithName:(NSString *)name {
3360 @synchronized (self) {
3361 if (static_cast<pkgDepCache *>(cache_) == NULL)
3363 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3364 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3368 if ((self = [super init]) != nil) {
3375 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3376 apr_pool_create(&pool_, NULL);
3378 size_t capacity(MetaFile_->active_);
3384 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3385 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3389 _assert(pipe(fds) != -1);
3392 _config->Set("APT::Keep-Fds::", cydiafd_);
3393 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3396 detachNewThreadSelector:@selector(_readCydia:)
3398 withObject:[NSNumber numberWithInt:fds[0]]
3401 _assert(pipe(fds) != -1);
3405 detachNewThreadSelector:@selector(_readStatus:)
3407 withObject:[NSNumber numberWithInt:fds[0]]
3410 _assert(pipe(fds) != -1);
3411 _assert(dup2(fds[0], 0) != -1);
3412 _assert(close(fds[0]) != -1);
3414 input_ = fdopen(fds[1], "a");
3416 _assert(pipe(fds) != -1);
3417 _assert(dup2(fds[1], 1) != -1);
3418 _assert(close(fds[1]) != -1);
3421 detachNewThreadSelector:@selector(_readOutput:)
3423 withObject:[NSNumber numberWithInt:fds[0]]
3428 - (pkgCacheFile &) cache {
3432 - (pkgDepCache::Policy *) policy {
3436 - (pkgRecords *) records {
3440 - (pkgProblemResolver *) resolver {
3444 - (pkgAcquire &) fetcher {
3448 - (pkgSourceList &) list {
3452 - (NSArray *) packages {
3453 return (NSArray *) packages_;
3456 - (NSArray *) sources {
3460 - (Source *) sourceWithKey:(NSString *)key {
3461 for (Source *source in [self sources]) {
3462 if ([[source key] isEqualToString:key])
3467 - (bool) popErrorWithTitle:(NSString *)title {
3470 while (!_error->empty()) {
3472 bool warning(!_error->PopMessage(error));
3477 size_t size(error.size());
3478 if (size == 0 || error[size - 1] != '\n')
3480 error.resize(size - 1);
3483 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3485 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3486 if (warning && no_pubkey(error.c_str()))
3489 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3495 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3496 return [self popErrorWithTitle:title] || !success;
3499 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3500 @synchronized (self) {
3503 [self releasePackages];
3506 [sourceList_ removeAllObjects];
3526 apr_pool_clear(pool_);
3528 NSRecycleZone(zone_);
3529 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3531 int chk(creat("/tmp/cydia.chk", 0644));
3535 if (invocation != nil)
3536 [invocation invoke];
3538 NSString *title(UCLocalize("DATABASE"));
3540 list_ = new pkgSourceList();
3541 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3544 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3545 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3546 [sourceList_ addObject:object];
3550 OpProgress progress;
3552 if (!cache_.Open(progress, true)) {
3553 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3554 while (!_error->empty()) {
3556 bool warning(!_error->PopMessage(error));
3558 lprintf("cache_.Open():[%s]\n", error.c_str());
3560 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3564 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3565 repair = @selector(configure);
3566 //else if (error == "The package lists or status file could not be parsed or opened.")
3567 // repair = @selector(update);
3568 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3569 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3570 // else if (error == "Malformed Status line")
3571 // else if (error == "The list of sources could not be read.")
3573 if (repair != NULL) {
3575 [delegate_ repairWithSelector:repair];
3584 unlink("/tmp/cydia.chk");
3586 now_ = [[NSDate date] timeIntervalSince1970];
3588 policy_ = new pkgDepCache::Policy();
3589 records_ = new pkgRecords(cache_);
3590 resolver_ = new pkgProblemResolver(cache_);
3591 fetcher_ = new pkgAcquire(&status_);
3594 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3595 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3599 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3602 if (cache_->BrokenCount() != 0) {
3603 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3606 if (cache_->BrokenCount() != 0) {
3607 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3611 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3615 for (Source *object in (id) sourceList_) {
3616 metaIndex *source([object metaIndex]);
3617 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3618 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3619 // XXX: this could be more intelligent
3620 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3621 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3623 sourceMap_[cached->ID] = object;
3628 /*std::vector<Package *> packages;
3629 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3634 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3635 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3636 //packages.push_back(package);
3637 CFArrayAppendValue(packages_, CFRetain(package));
3641 /*if (packages.empty())
3642 packages_ = [[NSArray alloc] init];
3644 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3647 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3648 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3649 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3657 /*if (!packages.empty())
3658 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3659 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3661 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3663 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3665 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3669 size_t count(CFArrayGetCount(packages_));
3670 MetaFile_->active_ = count;
3672 for (size_t index(0); index != count; ++index)
3673 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3680 @synchronized (self) {
3682 resolver_ = new pkgProblemResolver(cache_);
3684 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3685 if (!cache_[iterator].Keep())
3686 cache_->MarkKeep(iterator, false);
3687 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3688 cache_->SetReInstall(iterator, false);
3691 - (void) configure {
3692 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3694 system([dpkg UTF8String]);
3699 @synchronized (self) {
3700 // XXX: I don't remember this condition
3705 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3707 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3709 if ([self popErrorWithTitle:title])
3713 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3715 CydiaLogCleaner cleaner;
3716 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3723 fetcher_->Shutdown();
3725 pkgRecords records(cache_);
3727 lock_ = new FileFd();
3728 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3730 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3732 if ([self popErrorWithTitle:title])
3736 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3739 manager_ = (_system->CreatePM(cache_));
3740 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3747 bool substrate(RestartSubstrate_);
3748 RestartSubstrate_ = false;
3750 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3752 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3754 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3756 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3757 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3760 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3762 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3764 [self popErrorWithTitle:title];
3768 bool failed = false;
3769 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3770 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3772 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3775 std::string uri = (*item)->DescURI();
3776 std::string error = (*item)->ErrorText;
3778 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3781 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3782 [delegate_ addProgressEventOnMainThread:event forTask:title];
3785 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3793 RestartSubstrate_ = true;
3796 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3797 if ([self popErrorWithTitle:title])
3800 if (result == pkgPackageManager::Failed) {
3805 if (result != pkgPackageManager::Completed) {
3810 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3812 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3814 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3815 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3818 if (![before isEqualToArray:after])
3823 NSString *title(UCLocalize("UPGRADE"));
3824 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3830 [self updateWithStatus:status_];
3833 - (void) updateWithStatus:(Status &)status {
3834 NSString *title(UCLocalize("REFRESHING_DATA"));
3837 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3841 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3842 if ([self popErrorWithTitle:title])
3845 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3847 bool success(ListUpdate(status, list, PulseInterval_));
3848 if (status.WasCancelled())
3851 [self popErrorWithTitle:title forOperation:success];
3852 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3856 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3859 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3860 delegate_ = delegate;
3863 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3864 progress_ = delegate;
3865 status_.setDelegate(delegate);
3868 - (NSObject<ProgressDelegate> *) progressDelegate {
3872 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3873 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3874 return i == sourceMap_.end() ? nil : i->second;
3877 - (NSString *) mappedSectionForPointer:(const char *)section {
3878 _H<NSString> *mapped;
3880 _profile(Database$mappedSectionForPointer$Cache)
3881 mapped = §ions_[section];
3884 if (*mapped == NULL) {
3885 size_t length(strlen(section));
3886 char spaced[length + 1];
3888 _profile(Database$mappedSectionForPointer$Replace)
3889 for (size_t index(0); index != length; ++index)
3890 spaced[index] = section[index] == '_' ? ' ' : section[index];
3891 spaced[length] = '\0';
3896 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3897 string = [NSString stringWithUTF8String:spaced];
3900 _profile(Database$mappedSectionForPointer$Map)
3901 string = [SectionMap_ objectForKey:string] ?: string;
3911 static _H<NSMutableSet> Diversions_;
3913 @interface Diversion : NSObject {
3916 _H<NSString> format_;
3921 @implementation Diversion
3923 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3924 if ((self = [super init]) != nil) {
3925 pattern_ = [from UTF8String];
3931 - (NSString *) divert:(NSString *)url {
3932 return !pattern_(url) ? nil : pattern_->*format_;
3935 + (NSURL *) divertURL:(NSURL *)url {
3937 NSString *href([url absoluteString]);
3939 for (Diversion *diversion in (id) Diversions_)
3940 if (NSString *diverted = [diversion divert:href]) {
3942 NSLog(@"div: %@", diverted);
3944 url = [NSURL URLWithString:diverted];
3951 - (NSString *) key {
3955 - (NSUInteger) hash {
3959 - (BOOL) isEqual:(Diversion *)object {
3960 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3965 @interface CydiaObject : NSObject {
3966 _H<CyteWebViewController> indirect_;
3967 _transient id delegate_;
3970 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3976 @interface CydiaWebViewController : CyteWebViewController {
3977 _H<CydiaObject> cydia_;
3980 + (void) addDiversion:(Diversion *)diversion;
3981 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
3982 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
3983 - (void) setDelegate:(id)delegate;
3987 /* Web Scripting {{{ */
3988 @implementation CydiaObject
3990 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3991 if ((self = [super init]) != nil) {
3992 indirect_ = (CyteWebViewController *) indirect;
3996 - (void) setDelegate:(id)delegate {
3997 delegate_ = delegate;
4000 + (NSArray *) _attributeKeys {
4001 return [NSArray arrayWithObjects:
4004 @"coreFoundationVersionNumber",
4021 - (NSArray *) attributeKeys {
4022 return [[self class] _attributeKeys];
4025 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4026 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4029 - (NSString *) version {
4033 - (NSString *) build {
4037 - (NSString *) coreFoundationVersionNumber {
4038 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4041 - (NSString *) device {
4042 return UniqueIdentifier();
4045 - (NSString *) firmware {
4046 return [[UIDevice currentDevice] systemVersion];
4049 - (NSString *) hostname {
4050 return [[UIDevice currentDevice] name];
4053 - (NSString *) idiom {
4054 return (id) Idiom_ ?: [NSNull null];
4057 - (NSString *) mcc {
4058 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4059 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4063 - (NSString *) mnc {
4064 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4065 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4069 - (NSString *) operator {
4070 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4071 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4075 - (NSString *) bbsnum {
4076 return (id) BBSNum_ ?: [NSNull null];
4079 - (NSString *) ecid {
4080 return (id) ChipID_ ?: [NSNull null];
4083 - (NSString *) serial {
4084 return SerialNumber_;
4087 - (NSString *) role {
4088 return (id) Role_ ?: [NSNull null];
4091 - (NSString *) model {
4092 return [NSString stringWithUTF8String:Machine_];
4095 - (NSString *) token {
4096 return (id) Token_ ?: [NSNull null];
4099 + (NSString *) webScriptNameForSelector:(SEL)selector {
4101 else if (selector == @selector(addBridgedHost:))
4102 return @"addBridgedHost";
4103 else if (selector == @selector(addInsecureHost:))
4104 return @"addInsecureHost";
4105 else if (selector == @selector(addInternalRedirect::))
4106 return @"addInternalRedirect";
4107 else if (selector == @selector(addPipelinedHost:scheme:))
4108 return @"addPipelinedHost";
4109 else if (selector == @selector(addSource:::))
4110 return @"addSource";
4111 else if (selector == @selector(addTokenHost:))
4112 return @"addTokenHost";
4113 else if (selector == @selector(addTrivialSource:))
4114 return @"addTrivialSource";
4115 else if (selector == @selector(close))
4117 else if (selector == @selector(du:))
4119 else if (selector == @selector(stringWithFormat:arguments:))
4121 else if (selector == @selector(getAllSources))
4122 return @"getAllSources";
4123 else if (selector == @selector(getApplicationInfo:value:))
4124 return @"getApplicationInfoValue";
4125 else if (selector == @selector(getKernelNumber:))
4126 return @"getKernelNumber";
4127 else if (selector == @selector(getKernelString:))
4128 return @"getKernelString";
4129 else if (selector == @selector(getInstalledPackages))
4130 return @"getInstalledPackages";
4131 else if (selector == @selector(getIORegistryEntry::))
4132 return @"getIORegistryEntry";
4133 else if (selector == @selector(getLocaleIdentifier))
4134 return @"getLocaleIdentifier";
4135 else if (selector == @selector(getPreferredLanguages))
4136 return @"getPreferredLanguages";
4137 else if (selector == @selector(getPackageById:))
4138 return @"getPackageById";
4139 else if (selector == @selector(getMetadataKeys))
4140 return @"getMetadataKeys";
4141 else if (selector == @selector(getMetadataValue:))
4142 return @"getMetadataValue";
4143 else if (selector == @selector(getSessionValue:))
4144 return @"getSessionValue";
4145 else if (selector == @selector(installPackages:))
4146 return @"installPackages";
4147 else if (selector == @selector(isReachable:))
4148 return @"isReachable";
4149 else if (selector == @selector(localizedStringForKey:value:table:))
4151 else if (selector == @selector(popViewController:))
4152 return @"popViewController";
4153 else if (selector == @selector(refreshSources))
4154 return @"refreshSources";
4155 else if (selector == @selector(registerFrame:))
4156 return @"registerFrame";
4157 else if (selector == @selector(removeButton))
4158 return @"removeButton";
4159 else if (selector == @selector(saveConfig))
4160 return @"saveConfig";
4161 else if (selector == @selector(setMetadataValue::))
4162 return @"setMetadataValue";
4163 else if (selector == @selector(setSessionValue::))
4164 return @"setSessionValue";
4165 else if (selector == @selector(substitutePackageNames:))
4166 return @"substitutePackageNames";
4167 else if (selector == @selector(scrollToBottom:))
4168 return @"scrollToBottom";
4169 else if (selector == @selector(setAllowsNavigationAction:))
4170 return @"setAllowsNavigationAction";
4171 else if (selector == @selector(setBadgeValue:))
4172 return @"setBadgeValue";
4173 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4174 return @"setButtonImage";
4175 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4176 return @"setButtonTitle";
4177 else if (selector == @selector(setHidesBackButton:))
4178 return @"setHidesBackButton";
4179 else if (selector == @selector(setHidesNavigationBar:))
4180 return @"setHidesNavigationBar";
4181 else if (selector == @selector(setNavigationBarStyle:))
4182 return @"setNavigationBarStyle";
4183 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4184 return @"setNavigationBarTintColor";
4185 else if (selector == @selector(setPasteboardString:))
4186 return @"setPasteboardString";
4187 else if (selector == @selector(setPasteboardURL:))
4188 return @"setPasteboardURL";
4189 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4190 return @"setScrollAlwaysBounceVertical";
4191 else if (selector == @selector(setScrollIndicatorStyle:))
4192 return @"setScrollIndicatorStyle";
4193 else if (selector == @selector(setToken:))
4195 else if (selector == @selector(setViewportWidth:))
4196 return @"setViewportWidth";
4197 else if (selector == @selector(statfs:))
4199 else if (selector == @selector(supports:))
4201 else if (selector == @selector(unload))
4207 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4208 return [self webScriptNameForSelector:selector] == nil;
4211 - (BOOL) supports:(NSString *)feature {
4212 return [feature isEqualToString:@"window.open"];
4216 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4219 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4220 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4223 - (void) setScrollIndicatorStyle:(NSString *)style {
4224 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4227 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4228 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4231 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4233 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4234 return (id) [NSNull null];
4235 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4237 return (id) [NSNull null];
4238 return [info objectForKey:key];
4241 - (NSNumber *) getKernelNumber:(NSString *)name {
4242 const char *string([name UTF8String]);
4245 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4246 return (id) [NSNull null];
4248 if (size != sizeof(int))
4249 return (id) [NSNull null];
4252 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4253 return (id) [NSNull null];
4255 return [NSNumber numberWithInt:value];
4258 - (NSString *) getKernelString:(NSString *)name {
4259 const char *string([name UTF8String]);
4262 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4263 return (id) [NSNull null];
4265 char value[size + 1];
4266 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4267 return (id) [NSNull null];
4269 // XXX: just in case you request something ludicrous
4272 return [NSString stringWithCString:value];
4275 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4276 NSObject *value(CYIOGetValue([path UTF8String], entry));
4279 if ([value isKindOfClass:[NSData class]])
4280 value = CYHex((NSData *) value);
4285 - (NSArray *) getMetadataKeys {
4286 @synchronized (Values_) {
4287 return [Values_ allKeys];
4290 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4291 WebFrame *frame([iframe contentFrame]);
4292 [indirect_ registerFrame:frame];
4295 - (id) getMetadataValue:(NSString *)key {
4296 @synchronized (Values_) {
4297 return [Values_ objectForKey:key];
4300 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4301 @synchronized (Values_) {
4302 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4303 [Values_ removeObjectForKey:key];
4305 [Values_ setObject:value forKey:key];
4307 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4310 - (id) getSessionValue:(NSString *)key {
4311 @synchronized (SessionData_) {
4312 return [SessionData_ objectForKey:key];
4315 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4316 @synchronized (SessionData_) {
4317 if (value == (id) [WebUndefined undefined])
4318 [SessionData_ removeObjectForKey:key];
4320 [SessionData_ setObject:value forKey:key];
4323 - (void) addBridgedHost:(NSString *)host {
4324 @synchronized (HostConfig_) {
4325 [BridgedHosts_ addObject:host];
4328 - (void) addInsecureHost:(NSString *)host {
4329 @synchronized (HostConfig_) {
4330 [InsecureHosts_ addObject:host];
4333 - (void) addTokenHost:(NSString *)host {
4334 @synchronized (HostConfig_) {
4335 [TokenHosts_ addObject:host];
4338 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4339 @synchronized (HostConfig_) {
4340 if (scheme != (id) [WebUndefined undefined])
4341 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4343 [PipelinedHosts_ addObject:host];
4346 - (void) popViewController:(NSNumber *)value {
4347 if (value == (id) [WebUndefined undefined])
4348 value = [NSNumber numberWithBool:YES];
4349 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4352 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4353 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4355 for (NSString *section in sections)
4356 [array addObject:section];
4358 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4361 distribution, @"Distribution",
4363 nil] waitUntilDone:NO];
4366 - (void) addTrivialSource:(NSString *)href {
4367 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4370 - (void) refreshSources {
4371 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4374 - (void) saveConfig {
4375 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4378 - (NSArray *) getAllSources {
4379 return [[Database sharedInstance] sources];
4382 - (NSArray *) getInstalledPackages {
4383 Database *database([Database sharedInstance]);
4384 @synchronized (database) {
4385 NSArray *packages([database packages]);
4386 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4387 for (Package *package in packages)
4388 if (![package uninstalled])
4389 [installed addObject:package];
4393 - (Package *) getPackageById:(NSString *)id {
4394 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4398 return (Package *) [NSNull null];
4401 - (NSString *) getLocaleIdentifier {
4402 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4405 - (NSArray *) getPreferredLanguages {
4409 - (NSArray *) statfs:(NSString *)path {
4412 if (path == nil || statfs([path UTF8String], &stat) == -1)
4415 return [NSArray arrayWithObjects:
4416 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4417 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4418 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4422 - (NSNumber *) du:(NSString *)path {
4423 NSNumber *value(nil);
4426 _assert(pipe(fds) != -1);
4428 pid_t pid(ExecFork());
4430 _assert(dup2(fds[1], 1) != -1);
4431 _assert(close(fds[0]) != -1);
4432 _assert(close(fds[1]) != -1);
4433 /* XXX: this should probably not use du */
4434 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4437 _assert(close(fds[1]) != -1);
4439 if (FILE *du = fdopen(fds[0], "r")) {
4441 while (fgets(line, sizeof(line), du) != NULL) {
4442 size_t length(strlen(line));
4443 while (length != 0 && line[length - 1] == '\n')
4444 line[--length] = '\0';
4445 if (char *tab = strchr(line, '\t')) {
4447 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4453 _assert(close(fds[0]) != -1);
4460 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4463 - (NSNumber *) isReachable:(NSString *)name {
4464 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4467 - (void) installPackages:(NSArray *)packages {
4468 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4471 - (NSString *) substitutePackageNames:(NSString *)message {
4472 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4473 for (size_t i(0), e([words count]); i != e; ++i) {
4474 NSString *word([words objectAtIndex:i]);
4475 if (Package *package = [[Database sharedInstance] packageWithName:word])
4476 [words replaceObjectAtIndex:i withObject:[package name]];
4479 return [words componentsJoinedByString:@" "];
4482 - (void) removeButton {
4483 [indirect_ removeButton];
4486 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4487 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4490 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4491 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4494 - (void) setBadgeValue:(id)value {
4495 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4498 - (void) setAllowsNavigationAction:(NSString *)value {
4499 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4502 - (void) setHidesBackButton:(NSString *)value {
4503 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4506 - (void) setHidesNavigationBar:(NSString *)value {
4507 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4510 - (void) setNavigationBarStyle:(NSString *)value {
4511 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4514 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4515 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4516 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4517 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4520 - (void) setPasteboardString:(NSString *)value {
4521 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4524 - (void) setPasteboardURL:(NSString *)value {
4525 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4528 - (void) _setToken:(NSString *)token {
4532 [Metadata_ removeObjectForKey:@"Token"];
4534 [Metadata_ setObject:Token_ forKey:@"Token"];
4539 - (void) setToken:(NSString *)token {
4540 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4543 - (void) scrollToBottom:(NSNumber *)animated {
4544 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4547 - (void) setViewportWidth:(float)width {
4548 [indirect_ setViewportWidthOnMainThread:width];
4551 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4552 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4553 unsigned count([arguments count]);
4555 for (unsigned i(0); i != count; ++i)
4556 values[i] = [arguments objectAtIndex:i];
4557 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4560 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4561 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4563 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4565 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4571 @interface NSURL (CydiaSecure)
4574 @implementation NSURL (CydiaSecure)
4576 - (bool) isCydiaSecure {
4577 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4580 @synchronized (HostConfig_) {
4581 if ([InsecureHosts_ containsObject:[self host]])
4590 /* Cydia Browser Controller {{{ */
4591 @implementation CydiaWebViewController
4593 - (NSURL *) navigationURL {
4594 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4597 + (void) _initialize {
4598 [super _initialize];
4600 Diversions_ = [NSMutableSet setWithCapacity:0];
4603 + (void) addDiversion:(Diversion *)diversion {
4604 [Diversions_ addObject:diversion];
4607 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4608 [super webView:view didClearWindowObject:window forFrame:frame];
4609 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4612 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4613 WebDataSource *source([frame dataSource]);
4614 NSURLResponse *response([source response]);
4615 NSURL *url([response URL]);
4616 NSString *scheme([[url scheme] lowercaseString]);
4618 bool bridged(false);
4620 @synchronized (HostConfig_) {
4621 if ([scheme isEqualToString:@"file"])
4623 else if ([scheme isEqualToString:@"https"])
4624 if ([BridgedHosts_ containsObject:[url host]])
4629 [window setValue:cydia forKey:@"cydia"];
4632 - (void) _setupMail:(MFMailComposeViewController *)controller {
4633 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4635 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4636 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4639 - (NSURL *) URLWithURL:(NSURL *)url {
4640 return [Diversion divertURL:url];
4643 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4644 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4647 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4648 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4650 NSURL *url([copy URL]);
4651 NSString *href([url absoluteString]);
4652 NSString *host([url host]);
4654 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4655 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4656 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4657 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4660 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4661 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4663 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4667 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4668 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4669 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4670 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4675 @synchronized (HostConfig_) {
4676 bridged = [BridgedHosts_ containsObject:host];
4677 token = [TokenHosts_ containsObject:host];
4680 if ([url isCydiaSecure]) {
4682 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4683 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4685 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4686 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4693 - (void) setDelegate:(id)delegate {
4694 [super setDelegate:delegate];
4695 [cydia_ setDelegate:delegate];
4698 - (NSString *) applicationNameForUserAgent {
4703 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4704 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4710 @interface AppCacheController : CydiaWebViewController {
4715 @implementation AppCacheController
4717 - (void) didReceiveMemoryWarning {
4718 // XXX: this doesn't work
4721 - (bool) retainsNetworkActivityIndicator {
4729 @interface NSObject (CydiaScript)
4730 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4733 @implementation NSObject (CydiaScript)
4735 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4741 @implementation NSArray (CydiaScript)
4743 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4744 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4745 for (size_t i(0), e([self count]); i != e; ++i)
4746 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4752 @implementation NSDictionary (CydiaScript)
4754 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4755 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4757 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4764 /* Confirmation Controller {{{ */
4765 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4766 if (!iterator.end())
4767 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4768 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4770 pkgCache::PkgIterator package(dep.TargetPkg());
4773 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4780 @protocol ConfirmationControllerDelegate
4781 - (void) cancelAndClear:(bool)clear;
4782 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4786 @interface ConfirmationController : CydiaWebViewController {
4787 _transient Database *database_;
4789 _H<UIAlertView> essential_;
4791 _H<NSDictionary> changes_;
4792 _H<NSMutableArray> issues_;
4793 _H<NSDictionary> sizes_;
4798 - (id) initWithDatabase:(Database *)database;
4802 @implementation ConfirmationController
4806 RestartSubstrate_ = true;
4807 [delegate_ confirmWithNavigationController:[self navigationController]];
4810 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4811 NSString *context([alert context]);
4813 if ([context isEqualToString:@"remove"]) {
4814 if (button == [alert cancelButtonIndex])
4815 [self dismissModalViewControllerAnimated:YES];
4816 else if (button == [alert firstOtherButtonIndex]) {
4817 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
4820 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4821 } else if ([context isEqualToString:@"unable"]) {
4822 [self dismissModalViewControllerAnimated:YES];
4823 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4825 [super alertView:alert clickedButtonAtIndex:button];
4829 - (void) _doContinue {
4830 [delegate_ cancelAndClear:NO];
4831 [self dismissModalViewControllerAnimated:YES];
4834 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4835 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4839 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4840 [super webView:view didClearWindowObject:window forFrame:frame];
4842 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4843 (id) changes_, @"changes",
4844 (id) issues_, @"issues",
4845 (id) sizes_, @"sizes",
4847 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4850 - (id) initWithDatabase:(Database *)database {
4851 if ((self = [super init]) != nil) {
4852 database_ = database;
4854 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4855 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4856 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4857 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4858 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4862 pkgCacheFile &cache([database_ cache]);
4863 NSArray *packages([database_ packages]);
4864 pkgDepCache::Policy *policy([database_ policy]);
4866 issues_ = [NSMutableArray arrayWithCapacity:4];
4868 for (Package *package in packages) {
4869 pkgCache::PkgIterator iterator([package iterator]);
4870 NSString *name([package id]);
4872 if ([package broken]) {
4873 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4875 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4877 reasons, @"reasons",
4880 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4884 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4885 pkgCache::DepIterator start;
4886 pkgCache::DepIterator end;
4887 dep.GlobOr(start, end); // ++dep
4889 if (!cache->IsImportantDep(end))
4891 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4894 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4896 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4897 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4898 clauses, @"clauses",
4902 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4904 pkgCache::PkgIterator target(start.TargetPkg());
4905 if (target->ProvidesList != 0)
4906 reason = @"missing";
4908 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4910 reason = @"installed";
4911 installed = [NSString stringWithUTF8String:ver.VerStr()];
4912 } else if (!cache[target].CandidateVerIter(cache).end())
4913 reason = @"uninstalled";
4914 else if (target->ProvidesList == 0)
4915 reason = @"uninstallable";
4917 reason = @"virtual";
4920 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4921 [NSString stringWithUTF8String:start.CompType()], @"operator",
4922 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4925 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4926 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4927 version, @"version",
4929 installed, @"installed",
4932 // yes, seriously. (wtf?)
4940 pkgDepCache::StateCache &state(cache[iterator]);
4942 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4944 if (state.NewInstall())
4945 [installs addObject:name];
4946 // XXX: else if (state.Install())
4947 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4948 [reinstalls addObject:name];
4949 // XXX: move before previous if
4950 else if (state.Upgrade())
4951 [upgrades addObject:name];
4952 else if (state.Downgrade())
4953 [downgrades addObject:name];
4954 else if (!state.Delete())
4955 // XXX: _assert(state.Keep());
4957 else if (special_r(name))
4958 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4959 [NSNull null], @"package",
4960 [NSArray arrayWithObjects:
4961 [NSDictionary dictionaryWithObjectsAndKeys:
4962 @"Conflicts", @"relationship",
4963 [NSArray arrayWithObjects:
4964 [NSDictionary dictionaryWithObjectsAndKeys:
4966 [NSNull null], @"version",
4967 @"installed", @"reason",
4974 if ([package essential])
4976 [removes addObject:name];
4979 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4980 substrate_ |= DepSubstrate(iterator.CurrentVer());
4985 else if (Advanced_) {
4986 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4988 essential_ = [[[UIAlertView alloc]
4989 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4990 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4992 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4994 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4998 [essential_ setContext:@"remove"];
4999 [essential_ setNumberOfRows:2];
5001 essential_ = [[[UIAlertView alloc]
5002 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5003 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5005 cancelButtonTitle:UCLocalize("OKAY")
5006 otherButtonTitles:nil
5009 [essential_ setContext:@"unable"];
5012 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5013 installs, @"installs",
5014 reinstalls, @"reinstalls",
5015 upgrades, @"upgrades",
5016 downgrades, @"downgrades",
5017 removes, @"removes",
5020 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5021 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5022 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5025 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5029 - (UIBarButtonItem *) leftButton {
5030 return [[[UIBarButtonItem alloc]
5031 initWithTitle:UCLocalize("CANCEL")
5032 style:UIBarButtonItemStylePlain
5034 action:@selector(cancelButtonClicked)
5039 - (void) applyRightButton {
5040 if ([issues_ count] == 0 && ![self isLoading])
5041 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5042 initWithTitle:UCLocalize("CONFIRM")
5043 style:UIBarButtonItemStyleDone
5045 action:@selector(confirmButtonClicked)
5048 [[self navigationItem] setRightBarButtonItem:nil];
5052 - (void) cancelButtonClicked {
5053 [delegate_ cancelAndClear:YES];
5054 [self dismissModalViewControllerAnimated:YES];
5058 - (void) confirmButtonClicked {
5059 if (essential_ != nil)
5069 /* Progress Data {{{ */
5070 @interface CydiaProgressData : NSObject {
5071 _transient id delegate_;
5080 _H<NSMutableArray> events_;
5081 _H<NSString> title_;
5083 _H<NSString> status_;
5084 _H<NSString> finish_;
5089 @implementation CydiaProgressData
5091 + (NSArray *) _attributeKeys {
5092 return [NSArray arrayWithObjects:
5104 - (NSArray *) attributeKeys {
5105 return [[self class] _attributeKeys];
5108 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5109 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5113 if ((self = [super init]) != nil) {
5114 events_ = [NSMutableArray arrayWithCapacity:32];
5122 - (void) setDelegate:(id)delegate {
5123 delegate_ = delegate;
5126 - (void) setPercent:(float)value {
5130 - (NSNumber *) percent {
5131 return [NSNumber numberWithFloat:percent_];
5134 - (void) setCurrent:(float)value {
5138 - (NSNumber *) current {
5139 return [NSNumber numberWithFloat:current_];
5142 - (void) setTotal:(float)value {
5146 - (NSNumber *) total {
5147 return [NSNumber numberWithFloat:total_];
5150 - (void) setSpeed:(float)value {
5154 - (NSNumber *) speed {
5155 return [NSNumber numberWithFloat:speed_];
5158 - (NSArray *) events {
5162 - (void) removeAllEvents {
5163 [events_ removeAllObjects];
5166 - (void) addEvent:(CydiaProgressEvent *)event {
5167 [events_ addObject:event];
5170 - (void) setTitle:(NSString *)text {
5174 - (NSString *) title {
5178 - (void) setFinish:(NSString *)text {
5182 - (NSString *) finish {
5183 return (id) finish_ ?: [NSNull null];
5186 - (void) setRunning:(bool)running {
5190 - (NSNumber *) running {
5191 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5196 /* Progress Controller {{{ */
5197 @interface ProgressController : CydiaWebViewController <
5200 _transient Database *database_;
5201 _H<CydiaProgressData, 1> progress_;
5205 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5207 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5209 - (void) setTitle:(NSString *)title;
5210 - (void) setCancellable:(bool)cancellable;
5214 @implementation ProgressController
5217 [database_ setProgressDelegate:nil];
5221 - (UIBarButtonItem *) leftButton {
5222 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5223 initWithTitle:UCLocalize("CANCEL")
5224 style:UIBarButtonItemStylePlain
5226 action:@selector(cancel)
5227 ] autorelease] : nil;
5230 - (void) updateCancel {
5231 [super applyLeftButton];
5234 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5235 if ((self = [super init]) != nil) {
5236 database_ = database;
5237 delegate_ = delegate;
5239 [database_ setProgressDelegate:self];
5241 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5242 [progress_ setDelegate:self];
5244 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5246 [scroller_ setBackgroundColor:[UIColor blackColor]];
5248 [[self navigationItem] setHidesBackButton:YES];
5250 [self updateCancel];
5254 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5255 [super webView:view didClearWindowObject:window forFrame:frame];
5256 [window setValue:progress_ forKey:@"cydiaProgress"];
5259 - (void) updateProgress {
5260 [self dispatchEvent:@"CydiaProgressUpdate"];
5263 - (void) viewWillAppear:(BOOL)animated {
5264 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5265 [super viewWillAppear:animated];
5268 - (void) reloadSpringBoard {
5269 if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
5270 system("/bin/launchctl stop com.apple.backboardd");
5272 system("/usr/bin/killall backboardd SpringBoard sbreload");
5276 pid_t pid(ExecFork());
5281 pid_t pid(ExecFork());
5283 execl("/usr/bin/sbreload", "sbreload", NULL);
5293 system("/usr/bin/killall backboardd SpringBoard sbreload");
5297 UpdateExternalStatus(0);
5300 [delegate_ saveState];
5304 [delegate_ returnToCydia];
5308 [delegate_ terminateWithSuccess];
5309 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5310 [delegate_ suspendWithAnimation:YES];
5312 [delegate_ suspend];*/
5324 UIProgressHUD *hud([delegate_ addProgressHUD]);
5325 [hud setText:UCLocalize("LOADING")];
5326 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5332 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5333 SBReboot(SBSSpringBoardServerPort());
5335 reboot2(RB_AUTOBOOT);
5342 - (void) setTitle:(NSString *)title {
5343 [progress_ setTitle:title];
5344 [self updateProgress];
5347 - (UIBarButtonItem *) rightButton {
5348 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5349 initWithTitle:UCLocalize("CLOSE")
5350 style:UIBarButtonItemStylePlain
5352 action:@selector(close)
5356 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5357 UpdateExternalStatus(1);
5359 [progress_ setRunning:true];
5360 [self setTitle:title];
5361 // implicit updateProgress
5363 SHA1SumValue notifyconf; {
5365 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5368 MMap mmap(file, MMap::ReadOnly);
5370 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5371 notifyconf = sha1.Result();
5375 SHA1SumValue springlist; {
5377 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5380 MMap mmap(file, MMap::ReadOnly);
5382 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5383 springlist = sha1.Result();
5387 if (invocation != nil) {
5388 [invocation yieldToSelector:@selector(invoke)];
5389 [self setTitle:@"COMPLETE"];
5394 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5397 MMap mmap(file, MMap::ReadOnly);
5399 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5400 if (!(notifyconf == sha1.Result()))
5407 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5410 MMap mmap(file, MMap::ReadOnly);
5412 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5413 if (!(springlist == sha1.Result()))
5419 if (RestartSubstrate_)
5423 RestartSubstrate_ = false;
5426 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5427 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5428 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5429 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5430 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5433 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5435 [progress_ setRunning:false];
5436 [self updateProgress];
5438 [self applyRightButton];
5441 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5442 [progress_ addEvent:event];
5443 [self updateProgress];
5446 - (bool) isProgressCancelled {
5447 return cancel_ == 2;
5452 [self updateCancel];
5455 - (void) setCancellable:(bool)cancellable {
5456 unsigned cancel(cancel_);
5460 else if (cancel_ == 0)
5463 if (cancel != cancel_)
5464 [self updateCancel];
5467 - (void) setProgressCancellable:(NSNumber *)cancellable {
5468 [self setCancellable:[cancellable boolValue]];
5471 - (void) setProgressPercent:(NSNumber *)percent {
5472 [progress_ setPercent:[percent floatValue]];
5473 [self updateProgress];
5476 - (void) setProgressStatus:(NSDictionary *)status {
5477 if (status == nil) {
5478 [progress_ setCurrent:0];
5479 [progress_ setTotal:0];
5480 [progress_ setSpeed:0];
5482 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5484 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5485 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5486 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5489 [self updateProgress];
5495 /* Package Cell {{{ */
5496 @interface PackageCell : CyteTableViewCell <
5497 CyteTableViewCellDelegate
5501 _H<NSString> description_;
5503 _H<NSString> source_;
5505 _H<UIImage> placard_;
5509 - (PackageCell *) init;
5510 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5512 - (void) drawContentRect:(CGRect)rect;
5516 @implementation PackageCell
5518 - (PackageCell *) init {
5519 CGRect frame(CGRectMake(0, 0, 320, 74));
5520 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5521 UIView *content([self contentView]);
5522 CGRect bounds([content bounds]);
5524 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5525 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5526 [content addSubview:content_];
5528 [content_ setDelegate:self];
5529 [content_ setOpaque:YES];
5533 - (NSString *) accessibilityLabel {
5537 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5538 summarized_ = summary;
5548 [content_ setBackgroundColor:[UIColor whiteColor]];
5552 Source *source = [package source];
5554 icon_ = [package icon];
5556 if (NSString *name = [package name])
5557 name_ = [NSString stringWithString:name];
5559 if (NSString *description = [package shortDescription])
5560 description_ = [NSString stringWithString:description];
5562 commercial_ = [package isCommercial];
5564 NSString *label = nil;
5565 bool trusted = false;
5567 if (source != nil) {
5568 label = [source label];
5569 trusted = [source trusted];
5570 } else if ([[package id] isEqualToString:@"firmware"])
5571 label = UCLocalize("APPLE");
5573 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5575 NSString *from(label);
5577 NSString *section = [package simpleSection];
5578 if (section != nil && ![section isEqualToString:label]) {
5579 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5580 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5583 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5585 if (NSString *purpose = [package primaryPurpose])
5586 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5591 if (NSString *mode = [package mode]) {
5592 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5593 color = RemovingColor_;
5594 placard = @"removing";
5596 color = InstallingColor_;
5597 placard = @"installing";
5600 color = [UIColor whiteColor];
5602 if ([package installed] != nil)
5603 placard = @"installed";
5608 [content_ setBackgroundColor:color];
5611 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5614 [self setNeedsDisplay];
5615 [content_ setNeedsDisplay];
5618 - (void) drawSummaryContentRect:(CGRect)rect {
5619 bool highlighted(highlighted_);
5620 float width([self bounds].size.width);
5624 rect.size = [(UIImage *) icon_ size];
5626 while (rect.size.width > 16 || rect.size.height > 16) {
5627 rect.size.width /= 2;
5628 rect.size.height /= 2;
5631 rect.origin.x = 19 - rect.size.width / 2;
5632 rect.origin.y = 19 - rect.size.height / 2;
5634 [icon_ drawInRect:rect];
5637 if (badge_ != nil) {
5639 rect.size = [(UIImage *) badge_ size];
5641 rect.size.width /= 4;
5642 rect.size.height /= 4;
5644 rect.origin.x = 25 - rect.size.width / 2;
5645 rect.origin.y = 25 - rect.size.height / 2;
5647 [badge_ drawInRect:rect];
5650 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5654 UISetColor(commercial_ ? Purple_ : Black_);
5655 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5657 if (placard_ != nil)
5658 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5661 - (void) drawNormalContentRect:(CGRect)rect {
5662 bool highlighted(highlighted_);
5663 float width([self bounds].size.width);
5667 rect.size = [(UIImage *) icon_ size];
5669 while (rect.size.width > 32 || rect.size.height > 32) {
5670 rect.size.width /= 2;
5671 rect.size.height /= 2;
5674 rect.origin.x = 25 - rect.size.width / 2;
5675 rect.origin.y = 25 - rect.size.height / 2;
5677 [icon_ drawInRect:rect];
5680 if (badge_ != nil) {
5682 rect.size = [(UIImage *) badge_ size];
5684 rect.size.width /= 2;
5685 rect.size.height /= 2;
5687 rect.origin.x = 36 - rect.size.width / 2;
5688 rect.origin.y = 36 - rect.size.height / 2;
5690 [badge_ drawInRect:rect];
5693 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5697 UISetColor(commercial_ ? Purple_ : Black_);
5698 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5699 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5702 UISetColor(commercial_ ? Purplish_ : Gray_);
5703 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5705 if (placard_ != nil)
5706 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5709 - (void) drawContentRect:(CGRect)rect {
5711 [self drawSummaryContentRect:rect];
5713 [self drawNormalContentRect:rect];
5718 /* Section Cell {{{ */
5719 @interface SectionCell : CyteTableViewCell <
5720 CyteTableViewCellDelegate
5722 _H<NSString> basic_;
5723 _H<NSString> section_;
5725 _H<NSString> count_;
5727 _H<UISwitch> switch_;
5731 - (void) setSection:(Section *)section editing:(BOOL)editing;
5735 @implementation SectionCell
5737 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5738 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5739 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5740 // XXX: this initial frame is wrong, but is fixed later
5741 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5742 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5744 UIView *content([self contentView]);
5745 CGRect bounds([content bounds]);
5747 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5748 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5749 [content addSubview:content_];
5750 [content_ setBackgroundColor:[UIColor whiteColor]];
5752 [content_ setDelegate:self];
5756 - (void) onSwitch:(id)sender {
5757 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5758 if (metadata == nil) {
5759 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5760 [Sections_ setObject:metadata forKey:basic_];
5763 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5767 - (void) setSection:(Section *)section editing:(BOOL)editing {
5768 if (editing != editing_) {
5770 [switch_ removeFromSuperview];
5772 [self addSubview:switch_];
5781 if (section == nil) {
5782 name_ = UCLocalize("ALL_PACKAGES");
5785 basic_ = [section name];
5786 section_ = [section localized];
5788 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5789 count_ = [NSString stringWithFormat:@"%d", [section count]];
5792 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5795 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5796 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5798 [content_ setNeedsDisplay];
5801 - (void) setFrame:(CGRect)frame {
5802 [super setFrame:frame];
5804 CGRect rect([switch_ frame]);
5805 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
5808 - (NSString *) accessibilityLabel {
5812 - (void) drawContentRect:(CGRect)rect {
5813 bool highlighted(highlighted_ && !editing_);
5815 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
5817 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5820 float width(rect.size.width);
5822 width -= 9 + [switch_ frame].size.width;
5826 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:UILineBreakModeTailTruncation];
5828 CGSize size = [count_ sizeWithFont:Font14_];
5830 UISetColor(Folder_);
5832 [count_ drawAtPoint:CGPointMake(10 + (30 - size.width) / 2, 18) withFont:Font12Bold_];
5838 /* File Table {{{ */
5839 @interface FileTable : CyteViewController <
5840 UITableViewDataSource,
5843 _transient Database *database_;
5844 _H<Package> package_;
5846 _H<NSMutableArray> files_;
5847 _H<UITableView, 2> list_;
5850 - (id) initWithDatabase:(Database *)database;
5851 - (void) setPackage:(Package *)package;
5855 @implementation FileTable
5857 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5858 return files_ == nil ? 0 : [files_ count];
5861 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5865 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5866 static NSString *reuseIdentifier = @"Cell";
5868 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5870 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5871 [cell setFont:[UIFont systemFontOfSize:16]];
5873 [cell setText:[files_ objectAtIndex:indexPath.row]];
5874 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5879 - (NSURL *) navigationURL {
5880 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5884 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5885 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5886 [list_ setRowHeight:24.0f];
5887 [(UITableView *) list_ setDataSource:self];
5888 [list_ setDelegate:self];
5889 [self setView:list_];
5892 - (void) viewDidLoad {
5893 [super viewDidLoad];
5895 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5898 - (void) releaseSubviews {
5904 [super releaseSubviews];
5907 - (id) initWithDatabase:(Database *)database {
5908 if ((self = [super init]) != nil) {
5909 database_ = database;
5913 - (void) setPackage:(Package *)package {
5917 files_ = [NSMutableArray arrayWithCapacity:32];
5919 if (package != nil) {
5921 name_ = [package id];
5923 if (NSArray *files = [package files])
5924 [files_ addObjectsFromArray:files];
5926 if ([files_ count] != 0) {
5927 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5928 [files_ removeObjectAtIndex:0];
5929 [files_ sortUsingSelector:@selector(compareByPath:)];
5931 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5932 [stack addObject:@"/"];
5934 for (int i(0), e([files_ count]); i != e; ++i) {
5935 NSString *file = [files_ objectAtIndex:i];
5936 while (![file hasPrefix:[stack lastObject]])
5937 [stack removeLastObject];
5938 NSString *directory = [stack lastObject];
5939 [stack addObject:[file stringByAppendingString:@"/"]];
5940 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5941 ([stack count] - 2) * 3, "",
5942 [file substringFromIndex:[directory length]]
5951 - (void) reloadData {
5954 [self setPackage:[database_ packageWithName:name_]];
5959 /* Package Controller {{{ */
5960 @interface CYPackageController : CydiaWebViewController <
5961 UIActionSheetDelegate
5963 _transient Database *database_;
5964 _H<Package> package_;
5967 _H<NSMutableArray> buttons_;
5968 _H<UIBarButtonItem> button_;
5971 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
5975 @implementation CYPackageController
5977 - (NSURL *) navigationURL {
5978 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5981 /* XXX: this is not safe at all... localization of /fail/ */
5982 - (void) _clickButtonWithName:(NSString *)name {
5983 if ([name isEqualToString:UCLocalize("CLEAR")])
5984 [delegate_ clearPackage:package_];
5985 else if ([name isEqualToString:UCLocalize("INSTALL")])
5986 [delegate_ installPackage:package_];
5987 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5988 [delegate_ installPackage:package_];
5989 else if ([name isEqualToString:UCLocalize("REMOVE")])
5990 [delegate_ removePackage:package_];
5991 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5992 [delegate_ installPackage:package_];
5993 else _assert(false);
5996 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5997 NSString *context([sheet context]);
5999 if ([context isEqualToString:@"modify"]) {
6000 if (button != [sheet cancelButtonIndex]) {
6001 NSString *buttonName = [buttons_ objectAtIndex:button];
6002 [self _clickButtonWithName:buttonName];
6005 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6009 - (bool) _allowJavaScriptPanel {
6014 - (void) _customButtonClicked {
6015 int count([buttons_ count]);
6020 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6022 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6023 [buttons addObjectsFromArray:buttons_];
6025 UIActionSheet *sheet = [[[UIActionSheet alloc]
6028 cancelButtonTitle:nil
6029 destructiveButtonTitle:nil
6030 otherButtonTitles:nil
6033 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6035 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6036 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6038 [sheet setContext:@"modify"];
6040 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6044 - (void) reloadButtonClicked {
6045 if (commercial_ && function_ == nil && [package_ uninstalled])
6047 [self customButtonClicked];
6050 - (void) applyLoadingTitle {
6051 // Don't show "Loading" as the title. Ever.
6054 - (UIBarButtonItem *) rightButton {
6059 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6060 if ((self = [super init]) != nil) {
6061 database_ = database;
6062 buttons_ = [NSMutableArray arrayWithCapacity:4];
6063 name_ = name == nil ? @"" : [NSString stringWithString:name];
6064 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6068 - (void) reloadData {
6071 package_ = [database_ packageWithName:name_];
6073 [buttons_ removeAllObjects];
6075 if (package_ != nil) {
6076 [(Package *) package_ parse];
6078 commercial_ = [package_ isCommercial];
6080 if ([package_ mode] != nil)
6081 [buttons_ addObject:UCLocalize("CLEAR")];
6082 if ([package_ source] == nil);
6083 else if ([package_ upgradableAndEssential:NO])
6084 [buttons_ addObject:UCLocalize("UPGRADE")];
6085 else if ([package_ uninstalled])
6086 [buttons_ addObject:UCLocalize("INSTALL")];
6088 [buttons_ addObject:UCLocalize("REINSTALL")];
6089 if (![package_ uninstalled])
6090 [buttons_ addObject:UCLocalize("REMOVE")];
6094 switch ([buttons_ count]) {
6095 case 0: title = nil; break;
6096 case 1: title = [buttons_ objectAtIndex:0]; break;
6097 default: title = UCLocalize("MODIFY"); break;
6100 button_ = [[[UIBarButtonItem alloc]
6102 style:UIBarButtonItemStylePlain
6104 action:@selector(customButtonClicked)
6108 - (bool) isLoading {
6109 return commercial_ ? [super isLoading] : false;
6115 /* Package List Controller {{{ */
6116 @interface PackageListController : CyteViewController <
6117 UITableViewDataSource,
6120 _transient Database *database_;
6122 _H<NSArray> packages_;
6123 _H<NSMutableArray> sections_;
6124 _H<UITableView, 2> list_;
6125 _H<NSMutableArray> index_;
6126 _H<NSMutableDictionary> indices_;
6127 _H<NSString> title_;
6128 unsigned reloading_;
6131 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6132 - (void) setDelegate:(id)delegate;
6133 - (void) resetCursor;
6138 @implementation PackageListController
6140 - (NSURL *) referrerURL {
6141 return [self navigationURL];
6144 - (bool) isSummarized {
6148 - (bool) showsSections {
6152 - (void) deselectWithAnimation:(BOOL)animated {
6153 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6156 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6157 CGRect base = [[self view] bounds];
6158 base.size.height -= bounds.size.height;
6159 base.origin = [list_ frame].origin;
6161 [UIView beginAnimations:nil context:NULL];
6162 [UIView setAnimationBeginsFromCurrentState:YES];
6163 [UIView setAnimationCurve:curve];
6164 [UIView setAnimationDuration:duration];
6165 [list_ setFrame:base];
6166 [UIView commitAnimations];
6169 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6170 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6173 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6174 [self resizeForKeyboardBounds:bounds duration:0];
6177 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6178 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6179 *curve = UIViewAnimationCurveEaseInOut;
6181 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6183 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6186 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6189 - (void) keyboardWillShow:(NSNotification *)notification {
6192 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6193 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6195 NSTimeInterval duration;
6196 UIViewAnimationCurve curve;
6197 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6199 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);
6200 UIViewController *base = self;
6201 while ([base parentOrPresentingViewController] != nil)
6202 base = [base parentOrPresentingViewController];
6203 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6204 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6206 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6207 intersection.size.height += CYStatusBarHeight();
6209 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6212 - (void) keyboardWillHide:(NSNotification *)notification {
6213 NSTimeInterval duration;
6214 UIViewAnimationCurve curve;
6215 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6217 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6220 - (void) viewWillAppear:(BOOL)animated {
6221 [super viewWillAppear:animated];
6223 [self resizeForKeyboardBounds:CGRectZero];
6224 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6225 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6228 - (void) viewWillDisappear:(BOOL)animated {
6229 [super viewWillDisappear:animated];
6231 [self resizeForKeyboardBounds:CGRectZero];
6232 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6233 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6236 - (void) viewDidAppear:(BOOL)animated {
6237 [super viewDidAppear:animated];
6238 [self deselectWithAnimation:animated];
6241 - (void) didSelectPackage:(Package *)package {
6242 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6243 [view setDelegate:delegate_];
6244 [[self navigationController] pushViewController:view animated:YES];
6247 #if TryIndexedCollation
6248 + (BOOL) hasIndexedCollation {
6249 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6253 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6254 NSInteger count([sections_ count]);
6255 return count == 0 ? 1 : count;
6258 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6259 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6261 return [[sections_ objectAtIndex:section] name];
6264 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6265 if ([sections_ count] == 0)
6267 return [[sections_ objectAtIndex:section] count];
6270 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6271 @synchronized (database_) {
6272 if ([database_ era] != era_)
6275 Section *section([sections_ objectAtIndex:[path section]]);
6276 NSInteger row([path row]);
6277 Package *package([packages_ objectAtIndex:([section row] + row)]);
6278 return [[package retain] autorelease];
6281 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6282 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6284 cell = [[[PackageCell alloc] init] autorelease];
6286 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6287 [cell setPackage:package asSummary:[self isSummarized]];
6291 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6292 Package *package([self packageAtIndexPath:path]);
6293 package = [database_ packageWithName:[package id]];
6294 [self didSelectPackage:package];
6297 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6298 if (![self showsSections])
6304 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6305 #if TryIndexedCollation
6306 if ([[self class] hasIndexedCollation]) {
6307 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6314 - (void) updateHeight {
6315 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6318 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6319 if ((self = [super init]) != nil) {
6320 database_ = database;
6321 title_ = [title copy];
6322 [[self navigationItem] setTitle:title_];
6327 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6328 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6329 [self setView:view];
6331 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6332 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6333 [view addSubview:list_];
6335 // XXX: is 20 the most optimal number here?
6336 [list_ setSectionIndexMinimumDisplayRowCount:20];
6338 [(UITableView *) list_ setDataSource:self];
6339 [list_ setDelegate:self];
6341 [self updateHeight];
6344 - (void) releaseSubviews {
6352 [super releaseSubviews];
6355 - (void) setDelegate:(id)delegate {
6356 delegate_ = delegate;
6359 - (bool) shouldYield {
6363 - (bool) shouldBlock {
6367 - (NSMutableArray *) _reloadPackages {
6368 @synchronized (database_) {
6369 era_ = [database_ era];
6370 NSArray *packages([database_ packages]);
6372 return [NSMutableArray arrayWithArray:packages];
6375 - (void) _reloadData {
6376 if (reloading_ != 0) {
6384 if ([self shouldYield]) {
6388 if (![self shouldBlock])
6391 hud = [delegate_ addProgressHUD];
6392 [hud setText:UCLocalize("LOADING")];
6396 packages = [self yieldToSelector:@selector(_reloadPackages)];
6399 [delegate_ removeProgressHUD:hud];
6400 } while (reloading_ == 2);
6402 packages = [self _reloadPackages];
6405 @synchronized (database_) {
6406 if (era_ != [database_ era])
6410 packages_ = packages;
6412 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6413 sections_ = [NSMutableArray arrayWithCapacity:16];
6415 Section *section = nil;
6417 #if TryIndexedCollation
6418 if ([[self class] hasIndexedCollation]) {
6419 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6421 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6422 NSArray *titles = [collation sectionIndexTitles];
6425 _profile(PackageTable$reloadData$Section)
6426 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6430 _profile(PackageTable$reloadData$Section$Package)
6431 package = [packages_ objectAtIndex:offset];
6432 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6435 while (secidx < index) {
6438 _profile(PackageTable$reloadData$Section$Allocate)
6439 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6442 _profile(PackageTable$reloadData$Section$Add)
6443 [sections_ addObject:section];
6447 [section addToCount];
6453 index_ = [NSMutableArray arrayWithCapacity:32];
6455 bool sectioned([self showsSections]);
6457 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6458 [sections_ addObject:section];
6461 _profile(PackageTable$reloadData$Section)
6462 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6466 _profile(PackageTable$reloadData$Section$Package)
6467 package = [packages_ objectAtIndex:offset];
6468 index = [package index];
6471 if (sectioned && (section == nil || [section index] != index)) {
6472 _profile(PackageTable$reloadData$Section$Allocate)
6473 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6476 [index_ addObject:[section name]];
6477 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6479 _profile(PackageTable$reloadData$Section$Add)
6480 [sections_ addObject:section];
6484 [section addToCount];
6489 [self updateHeight];
6491 _profile(PackageTable$reloadData$List)
6492 [(UITableView *) list_ setDataSource:self];
6497 - (void) reloadData {
6500 if ([self shouldYield])
6501 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6506 - (void) resetCursor {
6507 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6510 - (void) clearData {
6511 [self updateHeight];
6513 [list_ setDataSource:nil];
6521 /* Filtered Package List Controller {{{ */
6522 @interface FilteredPackageListController : PackageListController {
6525 _H<NSObject> object_;
6526 _H<NSObject> stuff_;
6529 - (void) setObject:(id)object;
6530 - (void) setStuff:(id)object;
6531 - (void) setObject:(id)object andStuff:(id)stuff;
6533 - (void) setObject:(id)object forFilter:(SEL)filter;
6534 - (void) setObject:(id)object andStuff:(id)stuff forFilter:(SEL)filter;
6537 - (void) setFilter:(SEL)filter;
6539 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6543 @implementation FilteredPackageListController
6549 - (void) setFilter:(SEL)filter {
6550 @synchronized (self) {
6553 /* XXX: this is an unsafe optimization of doomy hell */
6554 Method method(class_getInstanceMethod([Package class], filter));
6555 _assert(method != NULL);
6556 imp_ = method_getImplementation(method);
6557 _assert(imp_ != NULL);
6560 - (void) setObject:(id)object {
6561 @synchronized (self) {
6565 - (void) setStuff:(id)stuff {
6566 @synchronized (self) {
6570 - (void) setObject:(id)object andStuff:(id)stuff {
6571 @synchronized (self) {
6576 - (void) setObject:(id)object forFilter:(SEL)filter {
6577 @synchronized (self) {
6578 [self setFilter:filter];
6582 - (void) setObject:(id)object andStuff:(id)stuff forFilter:(SEL)filter {
6583 @synchronized (self) {
6584 [self setFilter:filter];
6589 - (NSMutableArray *) _reloadPackages {
6590 @synchronized (database_) {
6591 era_ = [database_ era];
6592 NSArray *packages([database_ packages]);
6594 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6598 _H<NSObject> object;
6601 @synchronized (self) {
6608 _profile(PackageTable$reloadData$Filter)
6609 for (Package *package in packages)
6610 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id, id)>(imp))(package, filter, object, stuff))
6611 [filtered addObject:package];
6617 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6618 if ((self = [super initWithDatabase:database title:title]) != nil) {
6619 [self setFilter:filter];
6624 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object with:(id)stuff {
6625 if ((self = [super initWithDatabase:database title:title]) != nil) {
6626 [self setFilter:filter];
6635 /* Home Controller {{{ */
6636 @interface HomeController : CydiaWebViewController {
6637 CFRunLoopRef runloop_;
6638 SCNetworkReachabilityRef reachability_;
6643 @implementation HomeController
6645 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6646 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6650 if ((self = [super init]) != nil) {
6651 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6654 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6655 if (reachability_ != NULL) {
6656 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6657 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6659 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6660 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6667 if (reachability_ != NULL && runloop_ != NULL)
6668 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6672 - (NSURL *) navigationURL {
6673 return [NSURL URLWithString:@"cydia://home"];
6676 - (void) aboutButtonClicked {
6677 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6679 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6680 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6681 [alert setCancelButtonIndex:0];
6684 @"Copyright \u00a9 2008-2013\n"
6687 "Jay Freeman (saurik)\n"
6688 "saurik@saurik.com\n"
6689 "http://www.saurik.com/"
6695 - (UIBarButtonItem *) leftButton {
6696 return [[[UIBarButtonItem alloc]
6697 initWithTitle:UCLocalize("ABOUT")
6698 style:UIBarButtonItemStylePlain
6700 action:@selector(aboutButtonClicked)
6707 /* Refresh Bar {{{ */
6708 @interface RefreshBar : UINavigationBar {
6709 _H<UIProgressIndicator> indicator_;
6710 _H<UITextLabel> prompt_;
6711 _H<UINavigationButton> cancel_;
6716 @implementation RefreshBar
6718 - (void) positionViews {
6719 CGRect frame = [cancel_ frame];
6720 frame.size = [cancel_ sizeThatFits:frame.size];
6721 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6722 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6723 [cancel_ setFrame:frame];
6725 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6726 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6727 CGRect indrect = {{indoffset, indoffset}, indsize};
6728 [indicator_ setFrame:indrect];
6730 CGSize prmsize = {215, indsize.height + 4};
6732 indoffset * 2 + indsize.width,
6733 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6735 [prompt_ setFrame:prmrect];
6738 - (void) setFrame:(CGRect)frame {
6739 [super setFrame:frame];
6740 [self positionViews];
6743 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6744 if ((self = [super initWithFrame:frame]) != nil) {
6745 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6747 [self setBarStyle:UIBarStyleBlack];
6749 UIBarStyle barstyle([self _barStyle:NO]);
6750 bool ugly(barstyle == UIBarStyleDefault);
6752 UIProgressIndicatorStyle style = ugly ?
6753 UIProgressIndicatorStyleMediumBrown :
6754 UIProgressIndicatorStyleMediumWhite;
6756 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6757 [(UIProgressIndicator *) indicator_ setStyle:style];
6758 [indicator_ startAnimation];
6759 [self addSubview:indicator_];
6761 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6762 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6763 [prompt_ setBackgroundColor:[UIColor clearColor]];
6764 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6765 [self addSubview:prompt_];
6767 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6768 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6769 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6770 [cancel_ setBarStyle:barstyle];
6772 [self positionViews];
6776 - (void) setCancellable:(bool)cancellable {
6778 [self addSubview:cancel_];
6780 [cancel_ removeFromSuperview];
6784 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6788 [self setCancellable:NO];
6791 - (void) setPrompt:(NSString *)prompt {
6792 [prompt_ setText:prompt];
6795 - (void) setProgress:(float)progress {
6801 /* Cydia Navigation Controller Interface {{{ */
6802 @interface UINavigationController (Cydia)
6804 - (NSArray *) navigationURLCollection;
6805 - (void) unloadData;
6810 /* Cydia Tab Bar Controller {{{ */
6811 @interface CydiaTabBarController : CyteTabBarController <
6812 UITabBarControllerDelegate,
6815 _transient Database *database_;
6816 _H<RefreshBar, 1> refreshbar_;
6820 // XXX: ok, "updatedelegate_"?...
6821 _transient NSObject<CydiaDelegate> *updatedelegate_;
6824 - (NSArray *) navigationURLCollection;
6825 - (void) dropBar:(BOOL)animated;
6826 - (void) beginUpdate;
6827 - (void) raiseBar:(BOOL)animated;
6832 @implementation CydiaTabBarController
6834 - (NSArray *) navigationURLCollection {
6835 NSMutableArray *items([NSMutableArray array]);
6837 // XXX: Should this deal with transient view controllers?
6838 for (id navigation in [self viewControllers]) {
6839 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6841 [items addObject:stack];
6848 [[NSNotificationCenter defaultCenter] removeObserver:self];
6853 - (id) initWithDatabase:(Database *)database {
6854 if ((self = [super init]) != nil) {
6855 database_ = database;
6856 [self setDelegate:self];
6858 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6859 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6861 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6865 - (void) setUpdate:(NSDate *)date {
6869 - (void) beginUpdate {
6870 [(RefreshBar *) refreshbar_ start];
6873 [updatedelegate_ retainNetworkActivityIndicator];
6877 detachNewThreadSelector:@selector(performUpdate)
6883 - (void) performUpdate {
6884 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6887 status.setDelegate(self);
6888 [database_ updateWithStatus:status];
6891 performSelectorOnMainThread:@selector(completeUpdate)
6899 - (void) stopUpdateWithSelector:(SEL)selector {
6901 [updatedelegate_ releaseNetworkActivityIndicator];
6903 [self raiseBar:YES];
6906 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6909 - (void) completeUpdate {
6912 [self stopUpdateWithSelector:@selector(reloadData)];
6915 - (void) cancelUpdate {
6916 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
6919 - (void) cancelPressed {
6920 [self cancelUpdate];
6927 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6928 [refreshbar_ setPrompt:[event compoundMessage]];
6931 - (bool) isProgressCancelled {
6935 - (void) setProgressCancellable:(NSNumber *)cancellable {
6936 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6939 - (void) setProgressPercent:(NSNumber *)percent {
6940 [refreshbar_ setProgress:[percent floatValue]];
6943 - (void) setProgressStatus:(NSDictionary *)status {
6945 [self setProgressPercent:[status objectForKey:@"Percent"]];
6948 - (void) setUpdateDelegate:(id)delegate {
6949 updatedelegate_ = delegate;
6952 - (UIView *) transitionView {
6953 if (![self respondsToSelector:@selector(_transitionView)])
6954 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6955 else if (kCFCoreFoundationVersionNumber < 800)
6956 return [self _transitionView];
6958 return [[[self _transitionView] superview] superview];
6961 - (void) dropBar:(BOOL)animated {
6966 UIView *transition([self transitionView]);
6967 [[self view] addSubview:refreshbar_];
6969 CGRect barframe([refreshbar_ frame]);
6971 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6972 barframe.origin.y = 0;
6973 else if (kCFCoreFoundationVersionNumber < 800)
6974 barframe.origin.y = CYStatusBarHeight();
6976 barframe.origin.y = 0; //-barframe.size.height + CYStatusBarHeight();
6978 [refreshbar_ setFrame:barframe];
6980 CGRect viewframe = [transition frame];
6982 if (kCFCoreFoundationVersionNumber < 800) {
6984 [UIView beginAnimations:nil context:NULL];
6986 float adjust(barframe.size.height);
6987 if (kCFCoreFoundationVersionNumber >= 800)
6988 adjust -= CYStatusBarHeight();
6989 viewframe.origin.y += adjust;
6990 viewframe.size.height -= adjust;
6991 [transition setFrame:viewframe];
6994 [UIView commitAnimations];
6997 // Ensure bar has the proper width for our view, it might have changed
6998 barframe.size.width = viewframe.size.width;
6999 [refreshbar_ setFrame:barframe];
7002 - (void) raiseBar:(BOOL)animated {
7007 UIView *transition([self transitionView]);
7008 [refreshbar_ removeFromSuperview];
7010 CGRect barframe([refreshbar_ frame]);
7012 if (kCFCoreFoundationVersionNumber < 800) {
7014 [UIView beginAnimations:nil context:NULL];
7016 CGRect viewframe = [transition frame];
7017 float adjust(barframe.size.height);
7018 if (kCFCoreFoundationVersionNumber >= 800)
7019 adjust -= CYStatusBarHeight();
7020 viewframe.origin.y -= adjust;
7021 viewframe.size.height += adjust;
7022 [transition setFrame:viewframe];
7025 [UIView commitAnimations];
7029 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7030 bool dropped(dropped_);
7035 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7041 - (void) statusBarFrameChanged:(NSNotification *)notification {
7051 /* Cydia Navigation Controller Implementation {{{ */
7052 @implementation UINavigationController (Cydia)
7054 - (NSArray *) navigationURLCollection {
7055 NSMutableArray *stack([NSMutableArray array]);
7057 for (CyteViewController *controller in [self viewControllers]) {
7058 NSString *url = [[controller navigationURL] absoluteString];
7060 [stack addObject:url];
7066 - (void) reloadData {
7069 UIViewController *visible([self visibleViewController]);
7071 [visible reloadData];
7073 // on the iPad, this view controller is ALSO visible. :(
7075 if (UIViewController *top = [self topViewController])
7080 - (void) unloadData {
7081 for (CyteViewController *page in [self viewControllers])
7090 /* Cydia:// Protocol {{{ */
7091 @interface CydiaURLProtocol : NSURLProtocol {
7096 @implementation CydiaURLProtocol
7098 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7099 NSURL *url([request URL]);
7103 NSString *scheme([[url scheme] lowercaseString]);
7104 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7106 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7112 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7116 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7117 id<NSURLProtocolClient> client([self client]);
7119 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7121 NSData *data(UIImagePNGRepresentation(icon));
7123 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7124 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7125 [client URLProtocol:self didLoadData:data];
7126 [client URLProtocolDidFinishLoading:self];
7130 - (void) startLoading {
7131 id<NSURLProtocolClient> client([self client]);
7132 NSURLRequest *request([self request]);
7134 NSURL *url([request URL]);
7135 NSString *href([url absoluteString]);
7136 NSString *scheme([[url scheme] lowercaseString]);
7140 if ([scheme isEqualToString:@"cydia"])
7141 path = [href substringFromIndex:8];
7142 else if ([scheme isEqualToString:@"about"])
7143 path = [href substringFromIndex:12];
7144 else _assert(false);
7146 NSRange slash([path rangeOfString:@"/"]);
7149 if (slash.location == NSNotFound) {
7153 command = [path substringToIndex:slash.location];
7154 path = [path substringFromIndex:(slash.location + 1)];
7157 Database *database([Database sharedInstance]);
7159 if ([command isEqualToString:@"package-icon"]) {
7162 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7163 Package *package([database packageWithName:path]);
7167 UIImage *icon([package icon]);
7168 [self _returnPNGWithImage:icon forRequest:request];
7169 } else if ([command isEqualToString:@"uikit-image"]) {
7172 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7173 UIImage *icon(_UIImageWithName(path));
7174 [self _returnPNGWithImage:icon forRequest:request];
7175 } else if ([command isEqualToString:@"section-icon"]) {
7178 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7179 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7181 icon = [UIImage applicationImageNamed:@"unknown.png"];
7182 [self _returnPNGWithImage:icon forRequest:request];
7184 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7188 - (void) stopLoading {
7194 /* Section Controller {{{ */
7195 @interface SectionController : FilteredPackageListController {
7197 _H<NSString> section_;
7200 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7204 @implementation SectionController
7206 - (NSURL *) referrerURL {
7207 NSString *name(section_);
7208 name = name ?: @"*";
7209 NSString *key(key_);
7211 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7214 - (NSURL *) navigationURL {
7215 NSString *name(section_);
7216 name = name ?: @"*";
7217 NSString *key(key_);
7219 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7222 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7225 title = UCLocalize("ALL_PACKAGES");
7226 else if (![section isEqual:@""])
7227 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7229 title = UCLocalize("NO_SECTION");
7231 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:source:) with:section with:source]) != nil) {
7232 key_ = [source key];
7237 - (void) reloadData {
7238 [super setStuff:[database_ sourceWithKey:key_]];
7244 /* Sections Controller {{{ */
7245 @interface SectionsController : CyteViewController <
7246 UITableViewDataSource,
7249 _transient Database *database_;
7251 _H<NSMutableArray> sections_;
7252 _H<NSMutableArray> filtered_;
7253 _H<UITableView, 2> list_;
7256 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7257 - (void) editButtonClicked;
7261 @implementation SectionsController
7263 - (NSURL *) navigationURL {
7264 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7267 - (Source *) source {
7270 return [database_ sourceWithKey:key_];
7273 - (void) updateNavigationItem {
7274 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7275 if ([sections_ count] == 0) {
7276 [[self navigationItem] setRightBarButtonItem:nil];
7278 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7279 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7281 action:@selector(editButtonClicked)
7282 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7286 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7287 [super setEditing:editing animated:animated];
7292 [delegate_ updateData];
7294 [self updateNavigationItem];
7297 - (void) viewDidAppear:(BOOL)animated {
7298 [super viewDidAppear:animated];
7299 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7302 - (void) viewWillDisappear:(BOOL)animated {
7303 [super viewWillDisappear:animated];
7304 [self setEditing:NO];
7307 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7308 Section *section = nil;
7309 int index = [indexPath row];
7310 if (![self isEditing]) {
7313 section = [filtered_ objectAtIndex:index];
7315 section = [sections_ objectAtIndex:index];
7320 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7321 if ([self isEditing])
7322 return [sections_ count];
7324 return [filtered_ count] + 1;
7327 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7331 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7332 static NSString *reuseIdentifier = @"SectionCell";
7334 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7336 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7338 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7343 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7344 if ([self isEditing])
7347 Section *section = [self sectionAtIndexPath:indexPath];
7349 SectionController *controller = [[[SectionController alloc]
7350 initWithDatabase:database_
7351 source:[self source]
7352 section:[section name]
7354 [controller setDelegate:delegate_];
7356 [[self navigationController] pushViewController:controller animated:YES];
7360 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7361 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7362 [list_ setRowHeight:46];
7363 [(UITableView *) list_ setDataSource:self];
7364 [list_ setDelegate:self];
7365 [self setView:list_];
7368 - (void) viewDidLoad {
7369 [super viewDidLoad];
7371 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7374 - (void) releaseSubviews {
7380 [super releaseSubviews];
7383 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7384 if ((self = [super init]) != nil) {
7385 database_ = database;
7386 key_ = [source key];
7390 - (void) reloadData {
7393 NSArray *packages = [database_ packages];
7395 sections_ = [NSMutableArray arrayWithCapacity:16];
7396 filtered_ = [NSMutableArray arrayWithCapacity:16];
7398 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7400 Source *source([self source]);
7403 for (Package *package in packages) {
7404 if (source != nil && [package source] != source)
7407 NSString *name([package section]);
7408 NSString *key(name == nil ? @"" : name);
7412 _profile(SectionsView$reloadData$Section)
7413 section = [sections objectForKey:key];
7414 if (section == nil) {
7415 _profile(SectionsView$reloadData$Section$Allocate)
7416 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7417 [sections setObject:section forKey:key];
7422 [section addToCount];
7424 _profile(SectionsView$reloadData$Filter)
7425 if (![package valid] || ![package visible])
7433 [sections_ addObjectsFromArray:[sections allValues]];
7435 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7437 for (Section *section in (id) sections_) {
7438 size_t count([section row]);
7442 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7443 [section setCount:count];
7444 [filtered_ addObject:section];
7447 [self updateNavigationItem];
7452 - (void) editButtonClicked {
7453 [self setEditing:![self isEditing] animated:YES];
7459 /* Changes Controller {{{ */
7460 @interface ChangesController : CyteViewController <
7461 UITableViewDataSource,
7464 _transient Database *database_;
7466 _H<NSMutableArray> packages_;
7467 _H<NSMutableArray> sections_;
7468 _H<UITableView, 2> list_;
7472 - (id) initWithDatabase:(Database *)database;
7476 @implementation ChangesController
7478 - (NSURL *) navigationURL {
7479 return [NSURL URLWithString:@"cydia://changes"];
7482 - (void) viewDidAppear:(BOOL)animated {
7483 [super viewDidAppear:animated];
7484 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7487 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7488 NSInteger count([sections_ count]);
7489 return count == 0 ? 1 : count;
7492 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7493 if ([sections_ count] == 0)
7495 return [[sections_ objectAtIndex:section] name];
7498 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7499 if ([sections_ count] == 0)
7501 return [[sections_ objectAtIndex:section] count];
7504 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7505 @synchronized (database_) {
7506 if ([database_ era] != era_)
7509 NSUInteger sectionIndex([path section]);
7510 if (sectionIndex >= [sections_ count])
7512 Section *section([sections_ objectAtIndex:sectionIndex]);
7513 NSInteger row([path row]);
7514 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7517 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7518 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7520 cell = [[[PackageCell alloc] init] autorelease];
7522 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7523 [cell setPackage:package asSummary:false];
7527 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7528 Package *package([self packageAtIndexPath:path]);
7529 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[NSString stringWithFormat:@"%@/#!/changes/", UI_]] autorelease]);
7530 [view setDelegate:delegate_];
7531 [[self navigationController] pushViewController:view animated:YES];
7535 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7536 NSString *context([alert context]);
7538 if ([context isEqualToString:@"norefresh"])
7539 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7542 - (void) refreshButtonClicked {
7543 if (IsReachable("cydia.saurik.com")) {
7544 [delegate_ beginUpdate];
7545 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7547 UIAlertView *alert = [[[UIAlertView alloc]
7548 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
7549 message:@"Host Unreachable" // XXX: Localize
7551 cancelButtonTitle:UCLocalize("OK")
7552 otherButtonTitles:nil
7555 [alert setContext:@"norefresh"];
7560 - (void) upgradeButtonClicked {
7561 [delegate_ distUpgrade];
7562 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7566 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7567 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7568 [self setView:view];
7570 list_ = [[[UITableView alloc] initWithFrame:[view bounds] style:UITableViewStylePlain] autorelease];
7571 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7572 [list_ setRowHeight:73];
7573 [(UITableView *) list_ setDataSource:self];
7574 [list_ setDelegate:self];
7575 [view addSubview:list_];
7578 - (void) viewDidLoad {
7579 [super viewDidLoad];
7581 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7584 - (void) releaseSubviews {
7590 [super releaseSubviews];
7593 - (id) initWithDatabase:(Database *)database {
7594 if ((self = [super init]) != nil) {
7595 database_ = database;
7599 - (NSMutableArray *) _reloadPackages {
7600 @synchronized (database_) {
7601 era_ = [database_ era];
7602 NSArray *packages([database_ packages]);
7604 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7607 _profile(ChangesController$_reloadPackages$Filter)
7608 for (Package *package in packages)
7609 if ([package upgradableAndEssential:YES] || [package visible])
7610 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7613 _profile(ChangesController$_reloadPackages$radixSort)
7614 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7621 - (void) _reloadData {
7622 NSMutableArray *packages;
7626 UIProgressHUD *hud([delegate_ addProgressHUD]);
7627 [hud setText:UCLocalize("LOADING")];
7628 //NSLog(@"HUD:%@::%@", delegate_, hud);
7629 packages = [self yieldToSelector:@selector(_reloadPackages)];
7630 [delegate_ removeProgressHUD:hud];
7632 packages = [self _reloadPackages];
7635 @synchronized (database_) {
7636 if (era_ != [database_ era])
7639 packages_ = packages;
7640 sections_ = [NSMutableArray arrayWithCapacity:16];
7642 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7643 Section *ignored = nil;
7644 Section *section = nil;
7648 bool unseens = false;
7650 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7652 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7653 Package *package = [packages_ objectAtIndex:offset];
7655 BOOL uae = [package upgradableAndEssential:YES];
7659 time_t seen([package seen]);
7661 if (section == nil || last != seen) {
7665 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7668 _profile(ChangesController$reloadData$Allocate)
7669 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7670 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7671 [sections_ addObject:section];
7675 [section addToCount];
7676 } else if ([package ignored]) {
7677 if (ignored == nil) {
7678 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7680 [ignored addToCount];
7683 [upgradable addToCount];
7688 CFRelease(formatter);
7691 Section *last = [sections_ lastObject];
7692 size_t count = [last count];
7693 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7694 [sections_ removeLastObject];
7697 if ([ignored count] != 0)
7698 [sections_ insertObject:ignored atIndex:0];
7700 [sections_ insertObject:upgradable atIndex:0];
7704 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7705 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7706 style:UIBarButtonItemStylePlain
7708 action:@selector(upgradeButtonClicked)
7709 ] autorelease]) animated:YES];
7711 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7712 initWithTitle:UCLocalize("REFRESH")
7713 style:UIBarButtonItemStylePlain
7715 action:@selector(refreshButtonClicked)
7716 ] autorelease]) animated:YES];
7721 - (void) reloadData {
7723 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7728 /* Search Controller {{{ */
7729 @interface SearchController : FilteredPackageListController <
7732 _H<UISearchBar, 1> search_;
7736 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7737 - (void) reloadData;
7741 @implementation SearchController
7743 - (NSURL *) referrerURL {
7744 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7747 - (NSURL *) navigationURL {
7748 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7749 return [NSURL URLWithString:@"cydia://search"];
7751 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7754 - (NSArray *) termsForQuery:(NSString *)query {
7755 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7756 for (NSString *component in [query componentsSeparatedByString:@" "])
7757 if ([component length] != 0)
7758 [terms addObject:component];
7763 - (void) useSearch {
7764 [self setObject:[self termsForQuery:[search_ text]] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7769 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7770 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7775 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7776 [search_ resignFirstResponder];
7780 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7781 [search_ setText:@""];
7782 [self searchBarButtonClicked:searchBar];
7785 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7786 [self searchBarButtonClicked:searchBar];
7789 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7790 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7794 - (bool) shouldYield {
7798 - (bool) shouldBlock {
7799 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7802 - (bool) isSummarized {
7803 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7806 - (bool) showsSections {
7810 - (NSMutableArray *) _reloadPackages {
7811 NSMutableArray *packages([super _reloadPackages]);
7812 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7813 [packages radixSortUsingSelector:@selector(rank)];
7817 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7818 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[self termsForQuery:query]])) {
7819 search_ = [[[UISearchBar alloc] init] autorelease];
7820 [search_ setDelegate:self];
7823 [search_ setText:query];
7827 - (void) viewDidAppear:(BOOL)animated {
7828 [super viewDidAppear:animated];
7830 if (!searchloaded_) {
7831 searchloaded_ = YES;
7832 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7833 [search_ layoutSubviews];
7834 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7836 UITextField *textField;
7837 if ([search_ respondsToSelector:@selector(searchField)])
7838 textField = [search_ searchField];
7840 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7842 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7843 [textField setEnablesReturnKeyAutomatically:NO];
7844 [[self navigationItem] setTitleView:textField];
7847 if ([self isSummarized])
7848 [search_ becomeFirstResponder];
7851 - (void) reloadData {
7852 id object([search_ text]);
7853 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7854 object = [self termsForQuery:object];
7856 [self setObject:object];
7862 - (void) didSelectPackage:(Package *)package {
7863 [search_ resignFirstResponder];
7864 [super didSelectPackage:package];
7869 /* Package Settings Controller {{{ */
7870 @interface PackageSettingsController : CyteViewController <
7871 UITableViewDataSource,
7874 _transient Database *database_;
7876 _H<Package> package_;
7877 _H<UITableView, 2> table_;
7878 _H<UISwitch> subscribedSwitch_;
7879 _H<UISwitch> ignoredSwitch_;
7880 _H<UITableViewCell> subscribedCell_;
7881 _H<UITableViewCell> ignoredCell_;
7884 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7888 @implementation PackageSettingsController
7890 - (NSURL *) navigationURL {
7891 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7894 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7895 if (package_ == nil)
7898 if ([package_ installed] == nil)
7904 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7905 if (package_ == nil)
7908 // both sections contain just one item right now.
7912 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7916 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7918 return UCLocalize("SHOW_ALL_CHANGES_EX");
7920 return UCLocalize("IGNORE_UPGRADES_EX");
7923 - (void) onSubscribed:(id)control {
7924 bool value([control isOn]);
7925 if (package_ == nil)
7927 if ([package_ setSubscribed:value])
7928 [delegate_ updateData];
7931 - (void) _updateIgnored {
7932 const char *package([name_ UTF8String]);
7933 bool on([ignoredSwitch_ isOn]);
7935 pid_t pid(ExecFork());
7937 FILE *dpkg(popen("dpkg --set-selections", "w"));
7938 fwrite(package, strlen(package), 1, dpkg);
7941 fwrite(" hold\n", 6, 1, dpkg);
7943 fwrite(" install\n", 9, 1, dpkg);
7951 - (void) onIgnored:(id)control {
7952 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7953 [invocation setTarget:self];
7954 [invocation setSelector:@selector(_updateIgnored)];
7956 [delegate_ reloadDataWithInvocation:invocation];
7959 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7960 if (package_ == nil)
7963 switch ([indexPath section]) {
7964 case 0: return subscribedCell_;
7965 case 1: return ignoredCell_;
7974 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7975 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7976 [self setView:view];
7978 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7979 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7980 [(UITableView *) table_ setDataSource:self];
7981 [table_ setDelegate:self];
7982 [view addSubview:table_];
7984 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7985 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7986 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7988 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7989 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7990 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7992 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7993 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7994 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7995 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7997 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7998 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7999 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8000 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8003 - (void) viewDidLoad {
8004 [super viewDidLoad];
8006 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8009 - (void) releaseSubviews {
8011 subscribedCell_ = nil;
8013 ignoredSwitch_ = nil;
8014 subscribedSwitch_ = nil;
8016 [super releaseSubviews];
8019 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8020 if ((self = [super init]) != nil) {
8021 database_ = database;
8026 - (void) reloadData {
8029 package_ = [database_ packageWithName:name_];
8031 if (package_ != nil) {
8032 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8033 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8034 } // XXX: what now, G?
8036 [table_ reloadData];
8042 /* Installed Controller {{{ */
8043 @interface InstalledController : FilteredPackageListController {
8047 - (id) initWithDatabase:(Database *)database;
8049 - (void) updateRoleButton;
8050 - (void) queueStatusDidChange;
8054 @implementation InstalledController
8056 - (NSURL *) referrerURL {
8057 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8060 - (NSURL *) navigationURL {
8061 return [NSURL URLWithString:@"cydia://installed"];
8064 - (id) initWithDatabase:(Database *)database {
8065 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8066 [self updateRoleButton];
8067 [self queueStatusDidChange];
8072 - (void) queueButtonClicked {
8077 - (void) queueStatusDidChange {
8080 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8081 initWithTitle:UCLocalize("QUEUE")
8082 style:UIBarButtonItemStyleDone
8084 action:@selector(queueButtonClicked)
8087 [[self navigationItem] setLeftBarButtonItem:nil];
8092 - (void) updateRoleButton {
8093 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8094 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8095 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8096 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8098 action:@selector(roleButtonClicked)
8102 - (void) roleButtonClicked {
8103 [self setObject:[NSNumber numberWithBool:expert_]];
8107 [self updateRoleButton];
8113 /* Source Cell {{{ */
8114 @interface SourceCell : CyteTableViewCell <
8115 CyteTableViewCellDelegate
8119 _H<NSString> origin_;
8120 _H<NSString> label_;
8123 - (void) setSource:(Source *)source;
8127 @implementation SourceCell
8129 - (void) _setImage:(NSArray *)data {
8130 if ([url_ isEqual:[data objectAtIndex:0]]) {
8131 icon_ = [data objectAtIndex:1];
8132 [content_ setNeedsDisplay];
8136 - (void) _setSource:(NSURL *) url {
8137 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8139 if (NSData *data = [NSURLConnection
8140 sendSynchronousRequest:[NSURLRequest
8142 cachePolicy:NSURLRequestUseProtocolCachePolicy
8146 returningResponse:NULL
8149 if (UIImage *image = [UIImage imageWithData:data])
8150 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8155 - (void) setSource:(Source *)source {
8156 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8158 origin_ = [source name];
8159 label_ = [source rooturi];
8161 [content_ setNeedsDisplay];
8163 url_ = [source iconURL];
8164 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8167 - (void) setAllSource {
8168 icon_ = [UIImage applicationImageNamed:@"folder.png"];
8169 origin_ = UCLocalize("ALL_SOURCES");
8170 label_ = UCLocalize("ALL_SOURCES_EX");
8171 [content_ setNeedsDisplay];
8174 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8175 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8176 UIView *content([self contentView]);
8177 CGRect bounds([content bounds]);
8179 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8180 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8181 [content_ setBackgroundColor:[UIColor whiteColor]];
8182 [content addSubview:content_];
8184 [content_ setDelegate:self];
8185 [content_ setOpaque:YES];
8187 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8191 - (NSString *) accessibilityLabel {
8195 - (void) drawContentRect:(CGRect)rect {
8196 bool highlighted(highlighted_);
8197 float width(rect.size.width);
8201 rect.size = [(UIImage *) icon_ size];
8203 while (rect.size.width > 32 || rect.size.height > 32) {
8204 rect.size.width /= 2;
8205 rect.size.height /= 2;
8208 rect.origin.x = 26 - rect.size.width / 2;
8209 rect.origin.y = 26 - rect.size.height / 2;
8211 [icon_ drawInRect:rect];
8214 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8219 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 61) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8223 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 61) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8228 /* Sources Controller {{{ */
8229 @interface SourcesController : CyteViewController <
8230 UITableViewDataSource,
8233 _transient Database *database_;
8236 _H<UITableView, 2> list_;
8237 _H<NSMutableArray> sources_;
8241 _H<UIProgressHUD> hud_;
8244 //NSURLConnection *installer_;
8245 NSURLConnection *trivial_bz2_;
8246 NSURLConnection *trivial_gz_;
8247 //NSURLConnection *automatic_;
8252 - (id) initWithDatabase:(Database *)database;
8253 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8257 @implementation SourcesController
8259 - (void) _releaseConnection:(NSURLConnection *)connection {
8260 if (connection != nil) {
8261 [connection cancel];
8262 //[connection setDelegate:nil];
8263 [connection release];
8268 //[self _releaseConnection:installer_];
8269 [self _releaseConnection:trivial_gz_];
8270 [self _releaseConnection:trivial_bz2_];
8271 //[self _releaseConnection:automatic_];
8276 - (NSURL *) navigationURL {
8277 return [NSURL URLWithString:@"cydia://sources"];
8280 - (void) viewDidAppear:(BOOL)animated {
8281 [super viewDidAppear:animated];
8282 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8285 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8289 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8291 return UCLocalize("INDIVIDUAL_SOURCES");
8295 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8298 case 1: return [sources_ count];
8303 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8304 @synchronized (database_) {
8305 if ([database_ era] != era_)
8307 if ([indexPath section] != 1)
8309 NSUInteger index([indexPath row]);
8310 if (index >= [sources_ count])
8312 return [sources_ objectAtIndex:index];
8315 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8316 static NSString *cellIdentifier = @"SourceCell";
8318 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8319 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8320 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8322 Source *source([self sourceAtIndexPath:indexPath]);
8324 [cell setAllSource];
8326 [cell setSource:source];
8331 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8332 SectionsController *controller([[[SectionsController alloc]
8333 initWithDatabase:database_
8334 source:[self sourceAtIndexPath:indexPath]
8337 [controller setDelegate:delegate_];
8338 [[self navigationController] pushViewController:controller animated:YES];
8341 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8342 if ([indexPath section] != 1)
8344 Source *source = [self sourceAtIndexPath:indexPath];
8345 return [source record] != nil;
8348 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8349 _assert([indexPath section] == 1);
8350 if (editingStyle == UITableViewCellEditingStyleDelete) {
8351 Source *source = [self sourceAtIndexPath:indexPath];
8352 if (source == nil) return;
8354 [Sources_ removeObjectForKey:[source key]];
8357 [delegate_ _saveConfig];
8358 [delegate_ reloadDataWithInvocation:nil];
8363 [delegate_ addTrivialSource:href_];
8366 [delegate_ syncData];
8369 - (NSString *) getWarning {
8370 NSString *href(href_);
8371 NSRange colon([href rangeOfString:@"://"]);
8372 if (colon.location != NSNotFound)
8373 href = [href substringFromIndex:(colon.location + 3)];
8374 href = [href stringByAddingPercentEscapes];
8375 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8377 NSURL *url([NSURL URLWithString:href]);
8379 NSStringEncoding encoding;
8380 NSError *error(nil);
8382 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8383 return [warning length] == 0 ? nil : warning;
8387 - (void) _endConnection:(NSURLConnection *)connection {
8388 // XXX: the memory management in this method is horribly awkward
8390 NSURLConnection **field = NULL;
8391 if (connection == trivial_bz2_)
8392 field = &trivial_bz2_;
8393 else if (connection == trivial_gz_)
8394 field = &trivial_gz_;
8395 _assert(field != NULL);
8396 [connection release];
8400 trivial_bz2_ == nil &&
8403 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8405 [delegate_ releaseNetworkActivityIndicator];
8407 [delegate_ removeProgressHUD:hud_];
8411 if (warning != nil) {
8412 UIAlertView *alert = [[[UIAlertView alloc]
8413 initWithTitle:UCLocalize("SOURCE_WARNING")
8416 cancelButtonTitle:UCLocalize("CANCEL")
8418 UCLocalize("ADD_ANYWAY"),
8422 [alert setContext:@"warning"];
8423 [alert setNumberOfRows:1];
8426 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8432 } else if (error_ != nil) {
8433 UIAlertView *alert = [[[UIAlertView alloc]
8434 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8435 message:[error_ localizedDescription]
8437 cancelButtonTitle:UCLocalize("OK")
8438 otherButtonTitles:nil
8441 [alert setContext:@"urlerror"];
8446 UIAlertView *alert = [[[UIAlertView alloc]
8447 initWithTitle:UCLocalize("NOT_REPOSITORY")
8448 message:UCLocalize("NOT_REPOSITORY_EX")
8450 cancelButtonTitle:UCLocalize("OK")
8451 otherButtonTitles:nil
8454 [alert setContext:@"trivial"];
8464 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8465 switch ([response statusCode]) {
8471 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8472 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8474 [self _endConnection:connection];
8477 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8478 [self _endConnection:connection];
8481 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8482 NSURL *url([NSURL URLWithString:href]);
8484 NSMutableURLRequest *request = [NSMutableURLRequest
8486 cachePolicy:NSURLRequestUseProtocolCachePolicy
8490 [request setHTTPMethod:method];
8492 if (Machine_ != NULL)
8493 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8495 if (UniqueID_ != nil)
8496 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8498 if ([url isCydiaSecure]) {
8499 if (UniqueID_ != nil)
8500 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8503 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8506 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8507 NSString *context([alert context]);
8509 if ([context isEqualToString:@"source"]) {
8512 NSString *href = [[alert textField] text];
8514 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8516 if (![href hasSuffix:@"/"])
8517 href_ = [href stringByAppendingString:@"/"];
8521 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8522 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8523 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8527 // XXX: this is stupid
8528 hud_ = [delegate_ addProgressHUD];
8529 [hud_ setText:UCLocalize("VERIFYING_URL")];
8530 [delegate_ retainNetworkActivityIndicator];
8539 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8540 } else if ([context isEqualToString:@"trivial"])
8541 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8542 else if ([context isEqualToString:@"urlerror"])
8543 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8544 else if ([context isEqualToString:@"warning"]) {
8547 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8556 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8561 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8562 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8563 [list_ setRowHeight:53];
8564 [(UITableView *) list_ setDataSource:self];
8565 [list_ setDelegate:self];
8566 [self setView:list_];
8569 - (void) viewDidLoad {
8570 [super viewDidLoad];
8572 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8573 [self updateButtonsForEditingStatusAnimated:NO];
8576 - (void) viewWillAppear:(BOOL)animated {
8577 [super viewWillAppear:animated];
8579 [list_ setEditing:NO];
8580 [self updateButtonsForEditingStatusAnimated:NO];
8583 - (void) releaseSubviews {
8588 [super releaseSubviews];
8591 - (id) initWithDatabase:(Database *)database {
8592 if ((self = [super init]) != nil) {
8593 database_ = database;
8597 - (void) reloadData {
8600 @synchronized (database_) {
8601 era_ = [database_ era];
8603 sources_ = [NSMutableArray arrayWithCapacity:16];
8604 [sources_ addObjectsFromArray:[database_ sources]];
8606 [sources_ sortUsingSelector:@selector(compareByName:)];
8609 int count([sources_ count]);
8611 for (int i = 0; i != count; i++) {
8612 if ([[sources_ objectAtIndex:i] record] == nil)
8620 - (void) showAddSourcePrompt {
8621 UIAlertView *alert = [[[UIAlertView alloc]
8622 initWithTitle:UCLocalize("ENTER_APT_URL")
8625 cancelButtonTitle:UCLocalize("CANCEL")
8627 UCLocalize("ADD_SOURCE"),
8631 [alert setContext:@"source"];
8633 [alert setNumberOfRows:1];
8634 [alert addTextFieldWithValue:@"http://" label:@""];
8636 UITextInputTraits *traits = [[alert textField] textInputTraits];
8637 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8638 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8639 [traits setKeyboardType:UIKeyboardTypeURL];
8640 // XXX: UIReturnKeyDone
8641 [traits setReturnKeyType:UIReturnKeyNext];
8646 - (void) addButtonClicked {
8647 [self showAddSourcePrompt];
8650 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8651 BOOL editing([list_ isEditing]);
8653 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8654 initWithTitle:UCLocalize("ADD")
8655 style:UIBarButtonItemStylePlain
8657 action:@selector(addButtonClicked)
8658 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8660 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8661 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8662 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8664 action:@selector(editButtonClicked)
8665 ] autorelease] animated:animated];
8668 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8669 initWithTitle:UCLocalize("SETTINGS")
8670 style:UIBarButtonItemStylePlain
8672 action:@selector(settingsButtonClicked)
8676 - (void) settingsButtonClicked {
8677 [delegate_ showSettings];
8680 - (void) editButtonClicked {
8681 [list_ setEditing:![list_ isEditing] animated:YES];
8682 [self updateButtonsForEditingStatusAnimated:YES];
8688 /* Settings Controller {{{ */
8689 @interface SettingsController : CyteViewController <
8690 UITableViewDataSource,
8693 _transient Database *database_;
8694 // XXX: ok, "roledelegate_"?...
8695 _transient id roledelegate_;
8696 _H<UITableView, 2> table_;
8697 _H<UISegmentedControl> segment_;
8698 _H<UIView> container_;
8701 - (void) showDoneButton;
8702 - (void) resizeSegmentedControl;
8706 @implementation SettingsController
8709 table_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
8710 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8711 [table_ setDelegate:self];
8712 [(UITableView *) table_ setDataSource:self];
8713 [self setView:table_];
8715 NSArray *items = [NSArray arrayWithObjects:
8717 UCLocalize("HACKER"),
8718 UCLocalize("DEVELOPER"),
8720 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8721 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8722 [container_ addSubview:segment_];
8725 - (void) viewDidLoad {
8726 [super viewDidLoad];
8728 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8731 if ([Role_ isEqualToString:@"User"]) index = 0;
8732 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8733 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8735 [segment_ setSelectedSegmentIndex:index];
8736 [self showDoneButton];
8739 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8740 [self resizeSegmentedControl];
8743 - (void) releaseSubviews {
8748 [super releaseSubviews];
8751 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8752 if ((self = [super init]) != nil) {
8753 database_ = database;
8754 roledelegate_ = delegate;
8758 - (void) resizeSegmentedControl {
8759 CGFloat width = [[self view] frame].size.width;
8760 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8763 - (void) viewWillAppear:(BOOL)animated {
8764 [super viewWillAppear:animated];
8765 [self resizeSegmentedControl];
8768 - (void) viewDidAppear:(BOOL)animated {
8769 [super viewDidAppear:animated];
8770 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
8771 [self resizeSegmentedControl];
8774 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8775 [self resizeSegmentedControl];
8778 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8779 [self resizeSegmentedControl];
8783 NSString *role(nil);
8785 switch ([segment_ selectedSegmentIndex]) {
8786 case 0: role = @"User"; break;
8787 case 1: role = @"Hacker"; break;
8788 case 2: role = @"Developer"; break;
8793 if (![role isEqualToString:Role_]) {
8794 bool rolling(Role_ == nil);
8797 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8801 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8805 [roledelegate_ loadData];
8807 [roledelegate_ updateData];
8811 - (void) segmentChanged:(UISegmentedControl *)control {
8812 [self showDoneButton];
8815 - (void) saveAndClose {
8818 [[self navigationItem] setRightBarButtonItem:nil];
8819 [[self navigationController] dismissModalViewControllerAnimated:YES];
8822 - (void) doneButtonClicked {
8823 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8824 [spinner startAnimating];
8825 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8826 [[self navigationItem] setRightBarButtonItem:spinItem];
8828 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8831 - (void) showDoneButton {
8832 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8833 initWithTitle:UCLocalize("DONE")
8834 style:UIBarButtonItemStyleDone
8836 action:@selector(doneButtonClicked)
8837 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8840 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8841 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8845 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8849 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8850 return nil; // This method is required by the protocol.
8853 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8855 return UCLocalize("ROLE_EX");
8857 return [NSString stringWithFormat:
8858 @"%@: %@\n%@: %@\n%@: %@",
8859 UCLocalize("USER"), UCLocalize("USER_EX"),
8860 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8861 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8866 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8867 return section == 3 ? 44.0f : 0;
8870 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8871 return section == 3 ? container_ : nil;
8874 - (void) reloadData {
8877 [table_ reloadData];
8882 /* Stash Controller {{{ */
8883 @interface StashController : CyteViewController {
8884 _H<UIActivityIndicatorView> spinner_;
8885 _H<UILabel> status_;
8886 _H<UILabel> caption_;
8891 @implementation StashController
8894 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8895 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8896 [self setView:view];
8898 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8900 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8901 CGRect spinrect = [spinner_ frame];
8902 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8903 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8904 [spinner_ setFrame:spinrect];
8905 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8906 [view addSubview:spinner_];
8907 [spinner_ startAnimating];
8910 captrect.size.width = [[self view] frame].size.width;
8911 captrect.size.height = 40.0f;
8912 captrect.origin.x = 0;
8913 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8914 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8915 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8916 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8917 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8918 [caption_ setTextColor:[UIColor whiteColor]];
8919 [caption_ setBackgroundColor:[UIColor clearColor]];
8920 [caption_ setShadowColor:[UIColor blackColor]];
8921 [caption_ setTextAlignment:UITextAlignmentCenter];
8922 [view addSubview:caption_];
8925 statusrect.size.width = [[self view] frame].size.width;
8926 statusrect.size.height = 30.0f;
8927 statusrect.origin.x = 0;
8928 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8929 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8930 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8931 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8932 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8933 [status_ setTextColor:[UIColor whiteColor]];
8934 [status_ setBackgroundColor:[UIColor clearColor]];
8935 [status_ setShadowColor:[UIColor blackColor]];
8936 [status_ setTextAlignment:UITextAlignmentCenter];
8937 [view addSubview:status_];
8940 - (void) releaseSubviews {
8945 [super releaseSubviews];
8951 @interface CYURLCache : SDURLCache {
8956 @implementation CYURLCache
8958 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8961 else if ([event isEqualToString:@"no-cache"])
8963 else if ([event isEqualToString:@"store"])
8965 else if ([event isEqualToString:@"invalid"])
8967 else if ([event isEqualToString:@"memory"])
8969 else if ([event isEqualToString:@"disk"])
8971 else if ([event isEqualToString:@"miss"])
8974 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8978 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8979 if (NSURLResponse *response = [cached response])
8980 if (NSString *mime = [response MIMEType])
8981 if ([mime isEqualToString:@"text/cache-manifest"]) {
8982 NSURL *url([response URL]);
8985 NSLog(@"###: %@", [url absoluteString]);
8988 @synchronized (HostConfig_) {
8989 [CachedURLs_ addObject:url];
8993 [super storeCachedResponse:cached forRequest:request];
8998 @interface Cydia : UIApplication <
8999 ConfirmationControllerDelegate,
9002 UINavigationControllerDelegate,
9003 UITabBarControllerDelegate
9005 _H<UIWindow> window_;
9006 _H<CydiaTabBarController> tabbar_;
9007 _H<CydiaLoadingViewController> emulated_;
9009 _H<NSMutableArray> essential_;
9010 _H<NSMutableArray> broken_;
9012 Database *database_;
9014 _H<NSURL> starturl_;
9019 _H<StashController> stash_;
9028 @implementation Cydia
9030 - (void) lockSuspend {
9031 if (locked_++ == 0) {
9032 if ($SBSSetInterceptsMenuButtonForever != NULL)
9033 (*$SBSSetInterceptsMenuButtonForever)(true);
9035 [self setIdleTimerDisabled:YES];
9039 - (void) unlockSuspend {
9040 if (--locked_ == 0) {
9041 [self setIdleTimerDisabled:NO];
9043 if ($SBSSetInterceptsMenuButtonForever != NULL)
9044 (*$SBSSetInterceptsMenuButtonForever)(false);
9048 - (void) beginUpdate {
9049 [tabbar_ beginUpdate];
9053 return [tabbar_ updating];
9057 if ([broken_ count] != 0) {
9058 int count = [broken_ count];
9060 UIAlertView *alert = [[[UIAlertView alloc]
9061 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9062 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9064 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9066 UCLocalize("TEMPORARY_IGNORE"),
9070 [alert setContext:@"fixhalf"];
9071 [alert setNumberOfRows:2];
9073 } else if (!Ignored_ && [essential_ count] != 0) {
9074 int count = [essential_ count];
9076 UIAlertView *alert = [[[UIAlertView alloc]
9077 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9078 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9080 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9082 UCLocalize("UPGRADE_ESSENTIAL"),
9083 UCLocalize("COMPLETE_UPGRADE"),
9087 [alert setContext:@"upgrade"];
9092 - (void) returnToCydia {
9096 - (void) _saveConfig {
9097 @synchronized (database_) {
9104 NSString *error(nil);
9106 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9108 NSError *error(nil);
9109 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9110 NSLog(@"failure to save metadata data: %@", error);
9115 NSLog(@"failure to serialize metadata: %@", error);
9119 CydiaWriteSources();
9122 // Navigation controller for the queuing badge.
9123 - (UINavigationController *) queueNavigationController {
9124 NSArray *controllers = [tabbar_ viewControllers];
9125 return [controllers objectAtIndex:3];
9128 - (void) unloadData {
9129 [tabbar_ unloadData];
9132 - (void) _updateData {
9136 UINavigationController *navigation = [self queueNavigationController];
9138 id queuedelegate = nil;
9139 if ([[navigation viewControllers] count] > 0)
9140 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9142 [queuedelegate queueStatusDidChange];
9143 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9146 - (void) _refreshIfPossible:(NSDate *)update {
9147 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9149 bool recently = false;
9150 if (update != nil) {
9151 NSTimeInterval interval([update timeIntervalSinceNow]);
9152 if (interval <= 0 && interval > -(15*60))
9156 // Don't automatic refresh if:
9157 // - We already refreshed recently.
9158 // - We already auto-refreshed this launch.
9159 // - Auto-refresh is disabled.
9160 // - Cydia's server is not reachable
9161 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9162 // If we are cancelling, we need to make sure it knows it's already loaded.
9165 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9167 // We are going to load, so remember that.
9170 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9176 - (void) refreshIfPossible {
9177 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9180 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9181 @synchronized (self) {
9182 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9184 [hud setText:UCLocalize("RELOADING_DATA")];
9186 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9190 [essential_ removeAllObjects];
9191 [broken_ removeAllObjects];
9193 NSArray *packages([database_ packages]);
9194 for (Package *package in packages) {
9196 [broken_ addObject:package];
9197 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9198 if ([package essential] && [package installed] != nil)
9199 [essential_ addObject:package];
9204 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9207 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9208 [changesItem setBadgeValue:badge];
9209 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9210 [self setApplicationIconBadgeNumber:changes];
9213 [changesItem setBadgeValue:nil];
9214 [changesItem setAnimatedBadge:NO];
9215 [self setApplicationIconBadgeNumber:0];
9221 [self removeProgressHUD:hud];
9224 - (void) updateData {
9228 - (void) updateDataAndLoad {
9230 if ([database_ progressDelegate] == nil)
9236 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9239 - (void) disemulate {
9240 if (emulated_ == nil)
9243 [window_ addSubview:[tabbar_ view]];
9244 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9245 [window_ setRootViewController:tabbar_];
9246 [[emulated_ view] removeFromSuperview];
9248 [window_ setUserInteractionEnabled:YES];
9251 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9252 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9254 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9256 UIViewController *parent;
9257 if (emulated_ == nil)
9266 [parent presentModalViewController:navigation animated:YES];
9269 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9270 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9272 if (navigation != nil)
9273 [navigation pushViewController:progress animated:YES];
9275 [self presentModalViewController:progress force:YES];
9277 [progress invoke:invocation withTitle:title];
9281 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9282 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9285 - (void) repairWithInvocation:(NSInvocation *)invocation {
9287 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9291 - (void) repairWithSelector:(SEL)selector {
9292 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9295 - (void) reloadData {
9296 [self reloadDataWithInvocation:nil];
9297 if ([database_ progressDelegate] == nil)
9303 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9306 - (void) addSource:(NSDictionary *) source {
9307 CydiaAddSource(source);
9310 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9311 CydiaAddSource(href, distribution, sections);
9314 - (void) addTrivialSource:(NSString *)href {
9315 CydiaAddSource(href, @"./");
9318 - (void) updateValues {
9323 pkgProblemResolver *resolver = [database_ resolver];
9325 resolver->InstallProtect();
9326 if (!resolver->Resolve(true))
9331 // XXX: this is a really crappy way of doing this.
9332 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9333 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9334 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9335 if ([tabbar_ updating])
9336 [tabbar_ cancelUpdate];
9338 if (![database_ prepare])
9341 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9342 [page setDelegate:self];
9343 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9346 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9347 [tabbar_ presentModalViewController:confirm_ animated:YES];
9353 @synchronized (self) {
9358 - (void) clearPackage:(Package *)package {
9359 @synchronized (self) {
9366 - (void) installPackages:(NSArray *)packages {
9367 @synchronized (self) {
9368 for (Package *package in packages)
9375 - (void) installPackage:(Package *)package {
9376 @synchronized (self) {
9383 - (void) removePackage:(Package *)package {
9384 @synchronized (self) {
9391 - (void) distUpgrade {
9392 @synchronized (self) {
9393 if (![database_ upgrade])
9401 system("su -c /usr/bin/uicache mobile");
9406 UIProgressHUD *hud([self addProgressHUD]);
9407 [hud setText:UCLocalize("LOADING")];
9408 [self yieldToSelector:@selector(_uicache)];
9409 [self removeProgressHUD:hud];
9413 [database_ perform];
9414 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9415 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9418 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9421 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9422 [self unlockSuspend];
9425 - (void) showSettings {
9426 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9429 - (void) retainNetworkActivityIndicator {
9430 if (activity_++ == 0)
9431 [self setNetworkActivityIndicatorVisible:YES];
9434 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9438 - (void) releaseNetworkActivityIndicator {
9439 if (--activity_ == 0)
9440 [self setNetworkActivityIndicatorVisible:NO];
9443 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9448 - (void) cancelAndClear:(bool)clear {
9449 @synchronized (self) {
9461 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9462 NSString *context([alert context]);
9464 if ([context isEqualToString:@"conffile"]) {
9465 FILE *input = [database_ input];
9466 if (button == [alert cancelButtonIndex])
9467 fprintf(input, "N\n");
9468 else if (button == [alert firstOtherButtonIndex])
9469 fprintf(input, "Y\n");
9472 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9473 } else if ([context isEqualToString:@"fixhalf"]) {
9474 if (button == [alert cancelButtonIndex]) {
9475 @synchronized (self) {
9476 for (Package *broken in (id) broken_) {
9479 NSString *id = [broken id];
9480 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9481 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9482 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9483 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9489 } else if (button == [alert firstOtherButtonIndex]) {
9490 [broken_ removeAllObjects];
9494 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9495 } else if ([context isEqualToString:@"upgrade"]) {
9496 if (button == [alert firstOtherButtonIndex]) {
9497 @synchronized (self) {
9498 for (Package *essential in (id) essential_)
9499 [essential install];
9504 } else if (button == [alert firstOtherButtonIndex] + 1) {
9506 } else if (button == [alert cancelButtonIndex]) {
9510 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9514 - (void) system:(NSString *)command {
9515 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9518 system([command UTF8String]);
9524 - (void) applicationWillSuspend {
9526 [super applicationWillSuspend];
9529 - (BOOL) isSafeToSuspend {
9532 NSLog(@"isSafeToSuspend: locked_ != 0");
9537 // Use external process status API internally.
9538 // This is probably a really bad idea.
9539 // XXX: what is the point of this? does this solve anything at all?
9540 uint64_t status = 0;
9542 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9543 notify_get_state(notify_token, &status);
9544 notify_cancel(notify_token);
9549 NSLog(@"isSafeToSuspend: status != 0");
9555 NSLog(@"isSafeToSuspend: -> true");
9560 - (void) applicationSuspend:(__GSEvent *)event {
9561 if ([self isSafeToSuspend])
9562 [super applicationSuspend:event];
9565 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9566 if ([self isSafeToSuspend])
9567 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9570 - (void) _setSuspended:(BOOL)value {
9571 if ([self isSafeToSuspend])
9572 [super _setSuspended:value];
9575 - (UIProgressHUD *) addProgressHUD {
9576 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9577 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9579 [window_ setUserInteractionEnabled:NO];
9581 UIViewController *target(tabbar_);
9582 if (UIViewController *modal = [target modalViewController])
9585 [hud showInView:[target view]];
9591 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9592 [self unlockSuspend];
9594 [hud removeFromSuperview];
9595 [window_ setUserInteractionEnabled:YES];
9598 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9599 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9602 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9603 NSString *scheme([[url scheme] lowercaseString]);
9604 if ([[url absoluteString] length] <= [scheme length] + 3)
9606 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9607 NSArray *components([path componentsSeparatedByString:@"/"]);
9609 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9610 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9611 if (controller != nil)
9612 [controller setDelegate:self];
9616 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9619 NSString *base([components objectAtIndex:0]);
9621 CyteViewController *controller = nil;
9623 if ([base isEqualToString:@"url"]) {
9624 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9625 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9626 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9627 } else if (!external && [components count] == 1) {
9628 if ([base isEqualToString:@"sources"]) {
9629 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9632 if ([base isEqualToString:@"home"]) {
9633 controller = [[[HomeController alloc] init] autorelease];
9636 if ([base isEqualToString:@"sections"]) {
9637 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9640 if ([base isEqualToString:@"search"]) {
9641 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9644 if ([base isEqualToString:@"changes"]) {
9645 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9648 if ([base isEqualToString:@"installed"]) {
9649 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9651 } else if ([components count] == 2) {
9652 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9654 if ([base isEqualToString:@"package"]) {
9655 controller = [self pageForPackage:argument withReferrer:referrer];
9658 if (!external && [base isEqualToString:@"search"]) {
9659 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9662 if (!external && [base isEqualToString:@"sections"]) {
9663 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9665 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9668 if (!external && [base isEqualToString:@"sources"]) {
9669 if ([argument isEqualToString:@"add"]) {
9670 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9671 [(SourcesController *)controller showAddSourcePrompt];
9673 Source *source([database_ sourceWithKey:argument]);
9674 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9678 if (!external && [base isEqualToString:@"launch"]) {
9679 [self launchApplicationWithIdentifier:argument suspended:NO];
9682 } else if (!external && [components count] == 3) {
9683 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9684 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9686 if ([base isEqualToString:@"package"]) {
9687 if ([arg2 isEqualToString:@"settings"]) {
9688 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9689 } else if ([arg2 isEqualToString:@"files"]) {
9690 if (Package *package = [database_ packageWithName:arg1]) {
9691 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9692 [(FileTable *)controller setPackage:package];
9697 if ([base isEqualToString:@"sections"]) {
9698 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9699 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9700 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9704 [controller setDelegate:self];
9708 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9709 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9712 [tabbar_ setUnselectedViewController:page];
9717 - (void) applicationOpenURL:(NSURL *)url {
9718 [super applicationOpenURL:url];
9723 [self openCydiaURL:url forExternal:YES];
9726 - (void) applicationWillResignActive:(UIApplication *)application {
9727 // Stop refreshing if you get a phone call or lock the device.
9728 if ([tabbar_ updating])
9729 [tabbar_ cancelUpdate];
9731 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9732 [super applicationWillResignActive:application];
9735 - (void) saveState {
9736 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9737 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9738 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9744 - (void) applicationWillTerminate:(UIApplication *)application {
9748 - (void) setConfigurationData:(NSString *)data {
9749 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9751 if (!conffile_r(data)) {
9752 lprintf("E:invalid conffile\n");
9756 NSString *ofile = conffile_r[1];
9757 //NSString *nfile = conffile_r[2];
9759 UIAlertView *alert = [[[UIAlertView alloc]
9760 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9761 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9763 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9765 UCLocalize("ACCEPT_NEW_COPY"),
9766 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9770 [alert setContext:@"conffile"];
9771 [alert setNumberOfRows:2];
9775 - (void) addStashController {
9777 stash_ = [[[StashController alloc] init] autorelease];
9778 [window_ addSubview:[stash_ view]];
9781 - (void) removeStashController {
9782 [[stash_ view] removeFromSuperview];
9784 [self unlockSuspend];
9788 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9789 UpdateExternalStatus(1);
9790 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9791 UpdateExternalStatus(0);
9793 [self removeStashController];
9795 pid_t pid(ExecFork());
9797 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9798 perror("launchctl stop");
9804 - (void) setupViewControllers {
9805 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9807 NSMutableArray *items;
9808 if (kCFCoreFoundationVersionNumber < 800) {
9809 items = [NSMutableArray arrayWithObjects:
9810 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9811 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9812 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9813 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease],
9814 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9817 items = [NSMutableArray arrayWithObjects:
9818 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home7.png"] selectedImage:[UIImage applicationImageNamed:@"home7s.png"]] autorelease],
9819 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install7.png"] selectedImage:[UIImage applicationImageNamed:@"install7s.png"]] autorelease],
9820 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes7.png"] selectedImage:[UIImage applicationImageNamed:@"changes7s.png"]] autorelease],
9821 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage7.png"] selectedImage:[UIImage applicationImageNamed:@"manage7s.png"]] autorelease],
9822 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search7.png"] selectedImage:[UIImage applicationImageNamed:@"search7s.png"]] autorelease],
9826 NSMutableArray *controllers([NSMutableArray array]);
9827 for (UITabBarItem *item in items) {
9828 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9829 [controller setTabBarItem:item];
9830 [controllers addObject:controller];
9832 [tabbar_ setViewControllers:controllers];
9834 [tabbar_ setUpdateDelegate:self];
9837 - (void) _sendMemoryWarningNotification {
9838 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9839 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9841 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9844 - (void) _sendMemoryWarningNotifications {
9846 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9852 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9854 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9857 - (void) applicationDidFinishLaunching:(id)unused {
9858 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9861 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9862 [self setApplicationSupportsShakeToEdit:NO];
9864 @synchronized (HostConfig_) {
9865 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9868 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9869 initWithMemoryCapacity:524288
9870 diskCapacity:10485760
9871 diskPath:[NSString stringWithFormat:@"%@/SDURLCache", Cache_]
9874 [CydiaWebViewController _initialize];
9876 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9878 // this would disallow http{,s} URLs from accessing this data
9879 //[WebView registerURLSchemeAsLocal:@"cydia"];
9881 Font12_ = [UIFont systemFontOfSize:12];
9882 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9883 Font14_ = [UIFont systemFontOfSize:14];
9884 Font18_ = [UIFont systemFontOfSize:18];
9885 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9886 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9888 essential_ = [NSMutableArray arrayWithCapacity:4];
9889 broken_ = [NSMutableArray arrayWithCapacity:4];
9891 // XXX: I really need this thing... like, seriously... I'm sorry
9892 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9894 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9895 [window_ orderFront:self];
9896 [window_ makeKey:self];
9897 [window_ setHidden:NO];
9900 [self addStashController];
9901 // XXX: this would be much cleaner as a yieldToSelector:
9902 // that way the removeStashController could happen right here inline
9903 // we also could no longer require the useless stash_ field anymore
9904 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9909 int error(stat("/", &root));
9910 _assert(error != -1);
9912 #define Stash_(path) do { \
9913 struct stat folder; \
9914 int error(lstat((path), &folder)); \
9915 if (error != -1 && ( \
9916 folder.st_dev == root.st_dev && \
9917 S_ISDIR(folder.st_mode) \
9918 ) || error == -1 && ( \
9919 errno == ENOENT || \
9924 Stash_("/Applications");
9925 Stash_("/Library/Ringtones");
9926 Stash_("/Library/Wallpaper");
9927 //Stash_("/usr/bin");
9928 Stash_("/usr/include");
9929 Stash_("/usr/lib/pam");
9930 Stash_("/usr/share");
9931 //Stash_("/var/lib");
9933 database_ = [Database sharedInstance];
9934 [database_ setDelegate:self];
9936 [window_ setUserInteractionEnabled:NO];
9937 [self setupViewControllers];
9939 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9940 [window_ addSubview:[emulated_ view]];
9941 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9942 [window_ setRootViewController:emulated_];
9944 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9948 - (NSArray *) defaultStartPages {
9949 NSMutableArray *standard = [NSMutableArray array];
9950 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9951 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9952 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9953 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9954 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9961 [window_ setUserInteractionEnabled:YES];
9962 [self showSettings];
9965 if ([emulated_ modalViewController] != nil)
9966 [emulated_ dismissModalViewControllerAnimated:YES];
9967 [window_ setUserInteractionEnabled:NO];
9970 [self reloadDataWithInvocation:nil];
9971 [self refreshIfPossible];
9976 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9977 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9978 int standardIndex = 0;
9979 NSArray *standard = [self defaultStartPages];
9986 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9987 if (valid && closed != nil) {
9988 NSTimeInterval interval([closed timeIntervalSinceNow]);
9989 // XXX: Is 30 minutes the optimal time here?
9990 if (interval <= -(30*60))
9994 if (valid && [saved count] != [standard count])
9998 for (unsigned int i = 0; i < [standard count]; i++) {
9999 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10000 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10001 // but it's good enough for now.
10002 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10009 NSArray *items = nil;
10011 [tabbar_ setSelectedIndex:savedIndex];
10014 [tabbar_ setSelectedIndex:standardIndex];
10018 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10019 NSArray *stack = [items objectAtIndex:tab];
10020 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10021 NSMutableArray *current = [NSMutableArray array];
10023 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10024 NSString *addr = [stack objectAtIndex:nav];
10025 NSURL *url = [NSURL URLWithString:addr];
10026 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10028 [current addObject:page];
10031 [navigation setViewControllers:current];
10034 // (Try to) show the startup URL.
10035 if (starturl_ != nil) {
10036 [self openCydiaURL:starturl_ forExternal:NO];
10041 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10042 if (item != nil && IsWildcat_) {
10043 [sheet showFromBarButtonItem:item animated:YES];
10045 [sheet showInView:window_];
10049 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10050 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10051 [progress setTitle:task];
10052 [progress addProgressEvent:event];
10055 - (void) addProgressEventForTask:(NSArray *)data {
10056 CydiaProgressEvent *event([data objectAtIndex:0]);
10057 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10058 [self addProgressEvent:event forTask:task];
10061 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10062 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10068 id Alloc_(id self, SEL selector) {
10069 id object = alloc_(self, selector);
10070 lprintf("[%s]A-%p\n", self->isa->name, object);
10075 id Dealloc_(id self, SEL selector) {
10076 id object = dealloc_(self, selector);
10077 lprintf("[%s]D-%p\n", self->isa->name, object);
10081 static NSSet *MobilizedFiles_;
10083 static NSURL *MobilizeURL(NSURL *url) {
10084 NSString *path([url path]);
10085 if ([path hasPrefix:@"/var/root/"]) {
10086 NSString *file([path substringFromIndex:10]);
10087 if ([MobilizedFiles_ containsObject:file])
10088 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10094 Class $CFXPreferencesPropertyListSource;
10095 @class CFXPreferencesPropertyListSource;
10097 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10098 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10099 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10100 url = MobilizeURL(url);
10101 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10102 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10108 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10109 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10110 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10111 url = MobilizeURL(url);
10112 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10113 //NSLog(@"%@ %@", [url absoluteString], value);
10119 Class $NSURLConnection;
10121 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10122 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10124 NSURL *url([copy URL]);
10126 NSString *host([url host]);
10127 NSString *scheme([[url scheme] lowercaseString]);
10129 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10131 @synchronized (HostConfig_) {
10132 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10133 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10134 [copy setHTTPShouldUsePipelining:YES];
10136 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10137 if ([control isEqualToString:@"max-age=0"])
10138 if ([CachedURLs_ containsObject:url]) {
10140 NSLog(@"~~~: %@", url);
10143 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10145 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10146 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10147 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10151 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10157 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10158 CGSize size([[UIScreen mainScreen] bounds].size);
10159 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10160 if ([$WAKWindow hasLandscapeOrientation])
10161 std::swap(size.width, size.height);*/
10165 Class $NSUserDefaults;
10167 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10168 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10169 return [NSString stringWithFormat:@"%@/LocalStorage", Cache_];
10170 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10173 int main(int argc, char *argv[]) {
10174 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10178 UpdateExternalStatus(0);
10180 UIScreen *screen([UIScreen mainScreen]);
10181 if ([screen respondsToSelector:@selector(scale)])
10182 ScreenScale_ = [screen scale];
10186 UIDevice *device([UIDevice currentDevice]);
10187 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10188 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10189 if (idiom == UIUserInterfaceIdiomPad)
10193 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10195 Pcre pattern("^([0-9]+\\.[0-9]+)");
10197 if (pattern([device systemVersion]))
10198 Firmware_ = pattern[1];
10199 if (pattern(Cydia_))
10200 Major_ = pattern[1];
10202 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10204 HostConfig_ = [[[NSObject alloc] init] autorelease];
10205 @synchronized (HostConfig_) {
10206 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10207 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10208 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10209 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10210 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10213 NSString *ui(@"ui/ios");
10215 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10216 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10217 UI_ = CydiaURL(ui);
10219 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10221 MobilizedFiles_ = [NSMutableSet setWithObjects:
10222 @"Library/Preferences/com.apple.Accessibility.plist",
10223 @"Library/Preferences/com.apple.preferences.sounds.plist",
10226 /* Library Hacks {{{ */
10227 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10229 $WAKWindow = objc_getClass("WAKWindow");
10230 if ($WAKWindow != NULL)
10231 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10232 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10234 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10236 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10237 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10238 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10239 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10242 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10243 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10244 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10245 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10248 $NSURLConnection = objc_getClass("NSURLConnection");
10249 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10250 if (NSURLConnection$init$ != NULL) {
10251 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10252 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10255 $NSUserDefaults = objc_getClass("NSUserDefaults");
10256 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10257 if (NSUserDefaults$objectForKey$ != NULL) {
10258 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10259 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10262 /* Set Locale {{{ */
10263 Locale_ = CFLocaleCopyCurrent();
10264 Languages_ = [NSLocale preferredLanguages];
10266 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10267 //NSLog(@"%@", [Languages_ description]);
10270 if (Locale_ != NULL)
10271 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10272 else if (Languages_ != nil && [Languages_ count] != 0)
10273 lang = [[Languages_ objectAtIndex:0] UTF8String];
10275 // XXX: consider just setting to C and then falling through?
10278 if (lang != NULL) {
10279 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10280 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10283 NSLog(@"Setting Language: %s", lang);
10285 if (lang != NULL) {
10286 setenv("LANG", lang, true);
10287 std::setlocale(LC_ALL, lang);
10291 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10293 /* Parse Arguments {{{ */
10294 bool substrate(false);
10300 for (int argi(1); argi != argc; ++argi)
10301 if (strcmp(argv[argi], "--") == 0) {
10303 argv[argi] = argv[0];
10309 for (int argi(1); argi != arge; ++argi)
10310 if (strcmp(args[argi], "--substrate") == 0)
10313 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10317 App_ = [[NSBundle mainBundle] bundlePath];
10323 if (access("/var/mobile/Library/Keyboard/UserDictionary.sqlite", F_OK) == 0)
10324 system("mkdir -p /var/root/Library/Keyboard; cp -af /var/mobile/Library/Keyboard/UserDictionary.sqlite /var/root/Library/Keyboard/");
10326 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/root"] retain];
10328 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10329 alloc_ = alloc->method_imp;
10330 alloc->method_imp = (IMP) &Alloc_;*/
10332 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10333 dealloc_ = dealloc->method_imp;
10334 dealloc->method_imp = (IMP) &Dealloc_;*/
10336 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10337 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10339 /* System Information {{{ */
10343 size = sizeof(maxproc);
10344 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10345 perror("sysctlbyname(\"kern.maxproc\", ?)");
10346 else if (maxproc < 64) {
10348 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10349 perror("sysctlbyname(\"kern.maxproc\", #)");
10352 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10353 char *osversion = new char[size];
10354 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10355 perror("sysctlbyname(\"kern.osversion\", ?)");
10357 System_ = [NSString stringWithUTF8String:osversion];
10359 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10360 char *machine = new char[size];
10361 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10362 perror("sysctlbyname(\"hw.machine\", ?)");
10364 Machine_ = machine;
10366 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10367 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10368 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10370 UniqueID_ = UniqueIdentifier(device);
10372 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10373 Product_ = [info objectForKey:@"SafariProductVersion"];
10374 Safari_ = [info objectForKey:@"CFBundleVersion"];
10377 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10379 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10380 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10381 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10382 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10383 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10384 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10386 UserAgent_ = agent;
10388 /* Load Database {{{ */
10390 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10392 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10394 if (Metadata_ == NULL)
10395 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10397 Settings_ = [Metadata_ objectForKey:@"Settings"];
10399 Packages_ = [Metadata_ objectForKey:@"Packages"];
10401 Values_ = [Metadata_ objectForKey:@"Values"];
10402 Sections_ = [Metadata_ objectForKey:@"Sections"];
10403 Sources_ = [Metadata_ objectForKey:@"Sources"];
10405 Token_ = [Metadata_ objectForKey:@"Token"];
10407 Version_ = [Metadata_ objectForKey:@"Version"];
10410 if (Settings_ != nil)
10411 Role_ = [Settings_ objectForKey:@"Role"];
10413 if (Values_ == nil) {
10414 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10415 [Metadata_ setObject:Values_ forKey:@"Values"];
10418 if (Sections_ == nil) {
10419 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10420 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10423 if (Sources_ == nil) {
10424 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10425 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10428 if (Version_ == nil) {
10429 Version_ = [NSNumber numberWithUnsignedInt:0];
10430 [Metadata_ setObject:Version_ forKey:@"Version"];
10433 if ([Version_ unsignedIntValue] == 0) {
10434 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10435 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10436 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10437 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10439 Version_ = [NSNumber numberWithUnsignedInt:1];
10440 [Metadata_ setObject:Version_ forKey:@"Version"];
10442 [Metadata_ removeObjectForKey:@"LastUpdate"];
10448 CydiaWriteSources();
10451 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10454 if (Packages_ != nil) {
10456 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10460 [Metadata_ removeObjectForKey:@"Packages"];
10466 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10468 #define MobileSubstrate_(name) \
10469 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10470 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10471 if (handle == NULL) \
10472 NSLog(@"%s", dlerror()); \
10475 MobileSubstrate_(Activator)
10476 MobileSubstrate_(libstatusbar)
10477 MobileSubstrate_(SimulatedKeyEvents)
10478 MobileSubstrate_(WinterBoard)
10480 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10481 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10483 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10485 if (access("/User", F_OK) != 0 || version != 6) {
10487 system("/usr/libexec/cydia/firmware.sh");
10491 _assert([[NSFileManager defaultManager]
10492 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10493 withIntermediateDirectories:YES
10498 if (access("/tmp/cydia.chk", F_OK) == 0) {
10499 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10500 _assert(errno == ENOENT);
10501 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10502 _assert(errno == ENOENT);
10505 /* APT Initialization {{{ */
10506 _assert(pkgInitConfig(*_config));
10507 _assert(pkgInitSystem(*_config, _system));
10510 _config->Set("APT::Acquire::Translation", lang);
10512 // XXX: this timeout might be important :(
10513 //_config->Set("Acquire::http::Timeout", 15);
10515 _config->Set("Acquire::http::MaxParallel", 3);
10517 /* Color Choices {{{ */
10518 space_ = CGColorSpaceCreateDeviceRGB();
10520 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10521 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10522 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10523 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10524 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10525 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10526 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10527 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10528 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10529 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10531 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10532 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10534 /* UIKit Configuration {{{ */
10535 // XXX: I have a feeling this was important
10536 //UIKeyboardDisableAutomaticAppearance();
10539 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10541 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10542 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10543 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10545 PulseInterval_ = fast ? 50000 : 500000;
10547 Colon_ = UCLocalize("COLON_DELIMITED");
10548 Elision_ = UCLocalize("ELISION");
10549 Error_ = UCLocalize("ERROR");
10550 Warning_ = UCLocalize("WARNING");
10553 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10555 CGColorSpaceRelease(space_);
10556 CFRelease(Locale_);