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>
62 #include <ext/stdio_filebuf.h>
66 #include <apt-pkg/acquire.h>
67 #include <apt-pkg/acquire-item.h>
68 #include <apt-pkg/algorithms.h>
69 #include <apt-pkg/cachefile.h>
70 #include <apt-pkg/clean.h>
71 #include <apt-pkg/configuration.h>
72 #include <apt-pkg/debindexfile.h>
73 #include <apt-pkg/debmetaindex.h>
74 #include <apt-pkg/error.h>
75 #include <apt-pkg/init.h>
76 #include <apt-pkg/mmap.h>
77 #include <apt-pkg/pkgrecords.h>
78 #include <apt-pkg/sha1.h>
79 #include <apt-pkg/sourcelist.h>
80 #include <apt-pkg/sptr.h>
81 #include <apt-pkg/strutl.h>
82 #include <apt-pkg/tagfile.h>
84 #include <apr-1/apr_pools.h>
86 #include <sys/types.h>
88 #include <sys/sysctl.h>
89 #include <sys/param.h>
90 #include <sys/mount.h>
91 #include <sys/reboot.h>
98 #include <mach-o/nlist.h>
107 #include <Cytore.hpp>
110 #include <CydiaSubstrate/CydiaSubstrate.h>
111 #include "Menes/Menes.h"
113 #include "CyteKit/IndirectDelegate.h"
114 #include "CyteKit/PerlCompatibleRegEx.hpp"
115 #include "CyteKit/TableViewCell.h"
116 #include "CyteKit/TabBarController.h"
117 #include "CyteKit/WebScriptObject-Cyte.h"
118 #include "CyteKit/WebViewController.h"
119 #include "CyteKit/WebViewTableViewCell.h"
120 #include "CyteKit/stringWithUTF8Bytes.h"
122 #include "Cydia/MIMEAddress.h"
123 #include "Cydia/LoadingViewController.h"
124 #include "Cydia/ProgressEvent.h"
126 #include "SDURLCache/SDURLCache.h"
133 #define _timestamp ({ \
135 gettimeofday(&tv, NULL); \
136 tv.tv_sec * 1000000 + tv.tv_usec; \
139 typedef std::vector<class ProfileTime *> TimeList;
149 ProfileTime(const char *name) :
153 times_.push_back(this);
156 void AddTime(uint64_t time) {
163 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
175 ProfileTimer(ProfileTime &time) :
182 time_.AddTime(_timestamp - start_);
187 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
189 std::cerr << "========" << std::endl;
192 #define _profile(name) { \
193 static ProfileTime name(#name); \
194 ProfileTimer _ ## name(name);
199 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
200 #define synchronized(lock) \
201 synchronized(static_cast<NSObject *>(lock))
203 extern NSString *Cydia_;
205 #define lprintf(args...) fprintf(stderr, args)
208 #define TraceLogging (1 && !ForRelease)
209 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
210 #define ProfileTimes (0 && !ForRelease)
211 #define ForSaurik (0 && !ForRelease)
212 #define LogBrowser (0 && !ForRelease)
213 #define TrackResize (0 && !ForRelease)
214 #define ManualRefresh (1 && !ForRelease)
215 #define ShowInternals (0 && !ForRelease)
216 #define AlwaysReload (0 && !ForRelease)
217 #define TryIndexedCollation (0 && !ForRelease)
221 #define _trace(args...)
226 #define _profile(name) {
229 #define PrintTimes() do {} while (false)
232 // Hash Functions/Structures {{{
233 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
241 static NSString *Colon_;
243 static NSString *Error_;
244 static NSString *Warning_;
246 static NSString *Cache_;
248 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
250 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
252 static NSString *UniqueIdentifier(UIDevice *device = nil) {
253 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
254 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
256 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
259 static bool IsReachable(const char *name) {
260 SCNetworkReachabilityFlags flags; {
261 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
262 SCNetworkReachabilityGetFlags(reachability, &flags);
263 CFRelease(reachability);
266 // XXX: this elaborate mess is what Apple is using to determine this? :(
267 // XXX: do we care if the user has to intervene? maybe that's ok?
269 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
270 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
271 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
272 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
273 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
274 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
279 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
281 static _finline NSString *CydiaURL(NSString *path) {
283 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
284 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
285 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
286 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
287 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
289 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
292 static void ReapZombie(pid_t pid) {
295 if (waitpid(pid, &status, 0) == -1)
301 static _finline void UpdateExternalStatus(uint64_t newStatus) {
303 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
304 notify_set_state(notify_token, newStatus);
305 notify_cancel(notify_token);
307 notify_post("com.saurik.Cydia.status");
310 static CGFloat CYStatusBarHeight() {
311 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
312 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
315 /* NSForcedOrderingSearch doesn't work on the iPhone */
316 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
317 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
318 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
320 /* Insertion Sort {{{ */
322 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
323 const char *ptr = (const char *)list;
325 CFIndex half = count / 2;
326 const char *probe = ptr + elementSize * half;
327 CFComparisonResult cr = comparator(element, probe, context);
328 if (0 == cr) return (probe - (const char *)list) / elementSize;
329 ptr = (cr < 0) ? ptr : probe + elementSize;
330 count = (cr < 0) ? half : (half + (count & 1) - 1);
332 return (ptr - (const char *)list) / elementSize;
335 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
336 const char *ptr = (const char *)list;
338 CFIndex half = count / 2;
339 const char *probe = ptr + elementSize * half;
340 CFComparisonResult cr = comparator(element, probe, context);
341 if (0 == cr) return (probe - (const char *)list) / elementSize;
342 ptr = (cr < 0) ? ptr : probe + elementSize;
343 count = (cr < 0) ? half : (half + (count & 1) - 1);
345 return (ptr - (const char *)list) / elementSize;
348 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
349 if (range.length == 0)
351 const void **values(new const void *[range.length]);
352 CFArrayGetValues(array, range, values);
354 #if HistogramInsertionSort > 0
355 uint32_t total(0), *offsets(new uint32_t[range.length]);
358 for (CFIndex index(1); index != range.length; ++index) {
359 const void *value(values[index]);
360 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
361 CFIndex correct(index);
362 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
363 #if HistogramInsertionSort > 1
364 NSLog(@"%@ < %@", value, values[correct - 1]);
369 if (correct != index) {
370 size_t offset(index - correct);
371 #if HistogramInsertionSort
375 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
377 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
378 values[correct] = value;
382 CFArrayReplaceValues(array, range, values, range.length);
385 #if HistogramInsertionSort > 0
386 for (CFIndex index(0); index != range.length; ++index)
387 if (offsets[index] != 0)
388 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
389 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
396 /* Apple Bug Fixes {{{ */
397 @implementation UIWebDocumentView (Cydia)
399 - (void) _setScrollerOffset:(CGPoint)offset {
400 UIScroller *scroller([self _scroller]);
402 CGSize size([scroller contentSize]);
403 CGSize bounds([scroller bounds].size);
406 max.x = size.width - bounds.width;
407 max.y = size.height - bounds.height;
415 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
416 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
418 [scroller setOffset:offset];
424 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
425 size_t length([self length] - state->state);
428 else if (length > count)
430 for (size_t i(0); i != length; ++i)
431 objects[i] = [self item:state->state++];
432 state->itemsPtr = objects;
433 state->mutationsPtr = (unsigned long *) self;
437 /* Cydia NSString Additions {{{ */
438 @interface NSString (Cydia)
439 - (NSComparisonResult) compareByPath:(NSString *)other;
440 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
443 @implementation NSString (Cydia)
445 - (NSComparisonResult) compareByPath:(NSString *)other {
446 NSString *prefix = [self commonPrefixWithString:other options:0];
447 size_t length = [prefix length];
449 NSRange lrange = NSMakeRange(length, [self length] - length);
450 NSRange rrange = NSMakeRange(length, [other length] - length);
452 lrange = [self rangeOfString:@"/" options:0 range:lrange];
453 rrange = [other rangeOfString:@"/" options:0 range:rrange];
455 NSComparisonResult value;
457 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
458 value = NSOrderedSame;
459 else if (lrange.location == NSNotFound)
460 value = NSOrderedAscending;
461 else if (rrange.location == NSNotFound)
462 value = NSOrderedDescending;
464 value = NSOrderedSame;
466 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
467 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
468 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
469 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
471 NSComparisonResult result = [lpath compare:rpath];
472 return result == NSOrderedSame ? value : result;
475 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
476 return [(id)CFURLCreateStringByAddingPercentEscapes(
481 kCFStringEncodingUTF8
488 /* C++ NSString Wrapper Cache {{{ */
489 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
490 return size == 0 ? NULL :
491 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
492 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
495 static _finline CFStringRef CYStringCreate(const char *data) {
496 return CYStringCreate(data, strlen(data));
505 _finline void clear_() {
506 if (cache_ != NULL) {
513 _finline bool empty() const {
517 _finline size_t size() const {
521 _finline char *data() const {
525 _finline void clear() {
530 _finline CYString() :
537 _finline ~CYString() {
541 void operator =(const CYString &rhs) {
545 if (rhs.cache_ == nil)
548 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
551 void copy(apr_pool_t *pool) {
552 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
553 memcpy(temp, data_, size_);
558 void set(apr_pool_t *pool, const char *data, size_t size) {
564 data_ = const_cast<char *>(data);
572 _finline void set(apr_pool_t *pool, const char *data) {
573 set(pool, data, data == NULL ? 0 : strlen(data));
576 _finline void set(apr_pool_t *pool, const std::string &rhs) {
577 set(pool, rhs.data(), rhs.size());
580 bool operator ==(const CYString &rhs) const {
581 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
584 _finline operator CFStringRef() {
586 cache_ = CYStringCreate(data_, size_);
590 _finline operator id() {
591 return (NSString *) static_cast<CFStringRef>(*this);
594 _finline operator const char *() {
595 return reinterpret_cast<const char *>(data_);
599 /* C++ NSString Algorithm Adapters {{{ */
601 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
604 struct NSStringMapHash :
605 std::unary_function<NSString *, size_t>
607 _finline size_t operator ()(NSString *value) const {
608 return CFStringHashNSString((CFStringRef) value);
612 struct NSStringMapLess :
613 std::binary_function<NSString *, NSString *, bool>
615 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
616 return [lhs compare:rhs] == NSOrderedAscending;
620 struct NSStringMapEqual :
621 std::binary_function<NSString *, NSString *, bool>
623 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
624 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
625 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
626 //[lhs isEqualToString:rhs];
631 /* CoreGraphics Primitives {{{ */
636 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
637 CGFloat color[] = {red, green, blue, alpha};
638 return CGColorCreate(space, color);
647 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
648 color_(Create_(space, red, green, blue, alpha))
650 Set(space, red, green, blue, alpha);
655 CGColorRelease(color_);
662 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
664 color_ = Create_(space, red, green, blue, alpha);
667 operator CGColorRef() {
673 /* Random Global Variables {{{ */
674 static int PulseInterval_ = 500000;
676 static const NSString *UI_;
679 static bool RestartSubstrate_;
680 static NSArray *Finishes_;
682 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
683 #define NotifyConfig_ "/etc/notify.conf"
685 static bool Queuing_;
687 static CYColor Blue_;
688 static CYColor Blueish_;
689 static CYColor Black_;
690 static CYColor Folder_;
692 static CYColor White_;
693 static CYColor Gray_;
694 static CYColor Green_;
695 static CYColor Purple_;
696 static CYColor Purplish_;
698 static UIColor *InstallingColor_;
699 static UIColor *RemovingColor_;
701 static NSString *App_;
703 static BOOL Advanced_;
704 static BOOL Ignored_;
706 static _H<UIFont> Font12_;
707 static _H<UIFont> Font12Bold_;
708 static _H<UIFont> Font14_;
709 static _H<UIFont> Font18_;
710 static _H<UIFont> Font18Bold_;
711 static _H<UIFont> Font22Bold_;
713 static const char *Machine_ = NULL;
714 static _H<NSString> System_;
715 static NSString *SerialNumber_ = nil;
716 static NSString *ChipID_ = nil;
717 static NSString *BBSNum_ = nil;
718 static _H<NSString> Token_;
719 static _H<NSString> UniqueID_;
720 static _H<NSString> UserAgent_;
721 static _H<NSString> Product_;
722 static _H<NSString> Safari_;
724 static CFLocaleRef Locale_;
725 static NSArray *Languages_;
726 static CGColorSpaceRef space_;
728 static NSDictionary *SectionMap_;
729 static NSMutableDictionary *Metadata_;
730 static _transient NSMutableDictionary *Settings_;
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 SourceDelegate
868 - (void) setFetch:(NSNumber *)fetch;
871 @protocol FetchDelegate
872 - (bool) isSourceCancelled;
873 - (void) startSourceFetch:(NSString *)uri;
874 - (void) stopSourceFetch:(NSString *)uri;
877 @protocol CydiaDelegate
878 - (void) returnToCydia;
880 - (void) retainNetworkActivityIndicator;
881 - (void) releaseNetworkActivityIndicator;
882 - (void) clearPackage:(Package *)package;
883 - (void) installPackage:(Package *)package;
884 - (void) installPackages:(NSArray *)packages;
885 - (void) removePackage:(Package *)package;
886 - (void) beginUpdate;
888 - (bool) requestUpdate;
889 - (void) distUpgrade;
892 - (void) _saveConfig;
894 - (void) addSource:(NSDictionary *)source;
895 - (void) addTrivialSource:(NSString *)href;
896 - (UIProgressHUD *) addProgressHUD;
897 - (void) removeProgressHUD:(UIProgressHUD *)hud;
898 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
899 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
903 /* CancelStatus {{{ */
905 public pkgAcquireStatus
916 virtual bool MediaChange(std::string media, std::string drive) {
920 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
924 virtual bool Pulse_(pkgAcquire *Owner) = 0;
926 virtual bool Pulse(pkgAcquire *Owner) {
927 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
935 _finline bool WasCancelled() const {
940 /* DelegateStatus {{{ */
945 _transient NSObject<ProgressDelegate> *delegate_;
953 void setDelegate(NSObject<ProgressDelegate> *delegate) {
954 delegate_ = delegate;
957 virtual void Fetch(pkgAcquire::ItemDesc &item) {
958 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
959 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
960 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
963 virtual void Done(pkgAcquire::ItemDesc &item) {
964 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
965 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
966 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
969 virtual void Fail(pkgAcquire::ItemDesc &item) {
971 item.Owner->Status == pkgAcquire::Item::StatIdle ||
972 item.Owner->Status == pkgAcquire::Item::StatDone
976 std::string &error(item.Owner->ErrorText);
980 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
981 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
984 virtual bool Pulse_(pkgAcquire *Owner) {
986 double(CurrentBytes + CurrentItems) /
987 double(TotalBytes + TotalItems)
990 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
991 [NSNumber numberWithDouble:percent], @"Percent",
993 [NSNumber numberWithDouble:CurrentBytes], @"Current",
994 [NSNumber numberWithDouble:TotalBytes], @"Total",
995 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
996 nil] waitUntilDone:YES];
998 return ![delegate_ isProgressCancelled];
1001 virtual void Start() {
1002 pkgAcquireStatus::Start();
1003 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1006 virtual void Stop() {
1007 pkgAcquireStatus::Stop();
1008 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1009 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1013 /* Database Interface {{{ */
1014 typedef std::map< unsigned long, _H<Source> > SourceMap;
1016 @interface Database : NSObject {
1022 pkgCacheFile cache_;
1023 pkgDepCache::Policy *policy_;
1024 pkgRecords *records_;
1025 pkgProblemResolver *resolver_;
1026 pkgAcquire *fetcher_;
1028 SPtr<pkgPackageManager> manager_;
1029 pkgSourceList *list_;
1031 SourceMap sourceMap_;
1032 _H<NSMutableArray> sourceList_;
1034 CFMutableArrayRef packages_;
1036 _transient NSObject<DatabaseDelegate> *delegate_;
1037 _transient NSObject<ProgressDelegate> *progress_;
1039 CydiaStatus status_;
1045 std::map<const char *, _H<NSString> > sections_;
1048 + (Database *) sharedInstance;
1051 - (void) _readCydia:(NSNumber *)fd;
1052 - (void) _readStatus:(NSNumber *)fd;
1053 - (void) _readOutput:(NSNumber *)fd;
1057 - (Package *) packageWithName:(NSString *)name;
1059 - (pkgCacheFile &) cache;
1060 - (pkgDepCache::Policy *) policy;
1061 - (pkgRecords *) records;
1062 - (pkgProblemResolver *) resolver;
1063 - (pkgAcquire &) fetcher;
1064 - (pkgSourceList &) list;
1065 - (NSArray *) packages;
1066 - (NSArray *) sources;
1067 - (Source *) sourceWithKey:(NSString *)key;
1068 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1076 - (void) updateWithStatus:(CancelStatus &)status;
1078 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1080 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1081 - (NSObject<ProgressDelegate> *) progressDelegate;
1083 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1084 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1086 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1090 /* SourceStatus {{{ */
1091 class SourceStatus :
1095 _transient NSObject<FetchDelegate> *delegate_;
1096 _transient Database *database_;
1099 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1100 delegate_(delegate),
1105 void Set(bool fetch, pkgAcquire::ItemDesc &desc) {
1107 [database_ setFetch:fetch forURI:desc.Owner->DescURI().c_str()];
1110 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1114 virtual void Done(pkgAcquire::ItemDesc &desc) {
1118 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1122 virtual bool Pulse_(pkgAcquire *Owner) {
1123 for (pkgAcquire::ItemCIterator item = Owner->ItemsBegin(); item != Owner->ItemsEnd(); ++item)
1124 if ((*item)->ID != 0);
1125 else if ((*item)->Status == pkgAcquire::Item::StatIdle) {
1127 [database_ setFetch:true forURI:(*item)->DescURI().c_str()];
1128 } else (*item)->ID = 0;
1129 return ![delegate_ isSourceCancelled];
1133 /* ProgressEvent Implementation {{{ */
1134 @implementation CydiaProgressEvent
1136 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1137 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1140 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1141 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1142 [event setPackage:package];
1146 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1147 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1149 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1150 NSArray *fields([description componentsSeparatedByString:@" "]);
1151 [event setItem:fields];
1153 if ([fields count] > 3) {
1154 [event setPackage:[fields objectAtIndex:2]];
1155 [event setVersion:[fields objectAtIndex:3]];
1158 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1163 + (NSArray *) _attributeKeys {
1164 return [NSArray arrayWithObjects:
1174 - (NSArray *) attributeKeys {
1175 return [[self class] _attributeKeys];
1178 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1179 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1182 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1183 if ((self = [super init]) != nil) {
1189 - (NSString *) message {
1193 - (NSString *) type {
1197 - (NSArray *) item {
1198 return (id) item_ ?: [NSNull null];
1201 - (void) setItem:(NSArray *)item {
1205 - (NSString *) package {
1206 return (id) package_ ?: [NSNull null];
1209 - (void) setPackage:(NSString *)package {
1213 - (NSString *) url {
1214 return (id) url_ ?: [NSNull null];
1217 - (void) setURL:(NSString *)url {
1221 - (void) setVersion:(NSString *)version {
1225 - (NSString *) version {
1226 return (id) version_ ?: [NSNull null];
1229 - (NSString *) compound:(NSString *)value {
1231 NSString *mode(nil); {
1232 NSString *type([self type]);
1233 if ([type isEqualToString:kCydiaProgressEventTypeError])
1234 mode = UCLocalize("ERROR");
1235 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1236 mode = UCLocalize("WARNING");
1240 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1246 - (NSString *) compoundMessage {
1247 return [self compound:[self message]];
1250 - (NSString *) compoundTitle {
1253 if (package_ == nil)
1255 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1256 title = [package name];
1260 return [self compound:title];
1266 // Cytore Definitions {{{
1267 struct PackageValue :
1270 Cytore::Offset<PackageValue> next_;
1272 uint32_t index_ : 23;
1273 uint32_t subscribed_ : 1;
1290 Cytore::Offset<PackageValue> packages_[1 << 16];
1293 static Cytore::File<MetaValue> MetaFile_;
1295 // Cytore Helper Functions {{{
1296 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1297 SplitHash nhash = { hashlittle(name, length) };
1299 PackageValue *metadata;
1301 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1302 offset: if (offset->IsNull()) {
1303 *offset = MetaFile_.New<PackageValue>(length + 1);
1304 metadata = &MetaFile_.Get(*offset);
1306 if (metadata == NULL) {
1310 metadata = new PackageValue();
1311 memset(metadata, 0, sizeof(*metadata));
1314 memcpy(metadata->name_, name, length + 1);
1315 metadata->nhash_ = nhash.u16[1];
1317 metadata = &MetaFile_.Get(*offset);
1319 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1320 offset = &metadata->next_;
1328 static void PackageImport(const void *key, const void *value, void *context) {
1329 bool &fail(*reinterpret_cast<bool *>(context));
1332 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1333 NSLog(@"failed to import package %@", key);
1337 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1338 NSDictionary *package((NSDictionary *) value);
1340 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1341 if ([subscribed boolValue] && !metadata->subscribed_)
1342 metadata->subscribed_ = true;
1344 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1345 time_t time([date timeIntervalSince1970]);
1346 if (metadata->first_ > time || metadata->first_ == 0)
1347 metadata->first_ = time;
1350 NSDate *date([package objectForKey:@"LastSeen"]);
1351 NSString *version([package objectForKey:@"LastVersion"]);
1353 if (date != nil && version != nil) {
1354 time_t time([date timeIntervalSince1970]);
1355 if (metadata->last_ < time || metadata->last_ == 0)
1356 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1357 size_t length(strlen(buffer));
1358 uint16_t vhash(hashlittle(buffer, length));
1360 size_t capped(std::min<size_t>(8, length));
1361 char *latest(buffer + length - capped);
1363 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1364 metadata->vhash_ = vhash;
1366 metadata->last_ = time;
1372 /* Source Class {{{ */
1373 @interface Source : NSObject {
1375 Database *database_;
1378 CYString depiction_;
1379 CYString description_;
1385 CYString distribution_;
1391 _H<NSString> authority_;
1393 CYString defaultIcon_;
1395 _H<NSMutableDictionary> record_;
1398 std::set<std::string> fetches_;
1399 std::set<std::string> files_;
1400 _transient NSObject<SourceDelegate> *delegate_;
1403 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1405 - (NSComparisonResult) compareByName:(Source *)source;
1407 - (NSString *) depictionForPackage:(NSString *)package;
1408 - (NSString *) supportForPackage:(NSString *)package;
1410 - (metaIndex *) metaIndex;
1411 - (NSDictionary *) record;
1414 - (NSString *) rooturi;
1415 - (NSString *) distribution;
1416 - (NSString *) type;
1419 - (NSString *) host;
1421 - (NSString *) name;
1422 - (NSString *) shortDescription;
1423 - (NSString *) label;
1424 - (NSString *) origin;
1425 - (NSString *) version;
1427 - (NSString *) defaultIcon;
1428 - (NSURL *) iconURL;
1430 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1434 @implementation Source
1436 + (NSString *) webScriptNameForSelector:(SEL)selector {
1438 else if (selector == @selector(addSection:))
1439 return @"addSection";
1440 else if (selector == @selector(getField:))
1442 else if (selector == @selector(removeSection:))
1443 return @"removeSection";
1444 else if (selector == @selector(remove))
1450 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1451 return [self webScriptNameForSelector:selector] == nil;
1454 + (NSArray *) _attributeKeys {
1455 return [NSArray arrayWithObjects:
1466 @"shortDescription",
1473 - (NSArray *) attributeKeys {
1474 return [[self class] _attributeKeys];
1477 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1478 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1481 - (metaIndex *) metaIndex {
1485 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1486 trusted_ = index->IsTrusted();
1488 uri_.set(pool, index->GetURI());
1489 distribution_.set(pool, index->GetDist());
1490 type_.set(pool, index->GetType());
1492 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1493 if (dindex != NULL) {
1494 std::string file(dindex->MetaIndexURI(""));
1495 files_.insert(file + "Release.gpg");
1496 files_.insert(file + "Release");
1497 base_.set(pool, file);
1499 std::vector<IndexTarget *> *targets(dindex->ComputeIndexTargets());
1500 for (std::vector<IndexTarget *>::const_iterator target(targets->begin()); target != targets->end(); ++target) {
1501 std::string file((*target)->URI);
1502 files_.insert(file);
1503 files_.insert(file + ".gz");
1504 files_.insert(file + ".bz2");
1505 files_.insert(file + "Index");
1509 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1512 pkgTagFile tags(&fd);
1514 pkgTagSection section;
1521 {"default-icon", &defaultIcon_},
1522 {"depiction", &depiction_},
1523 {"description", &description_},
1525 {"origin", &origin_},
1526 {"support", &support_},
1527 {"version", &version_},
1530 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1531 const char *start, *end;
1533 if (section.Find(names[i].name_, start, end)) {
1534 CYString &value(*names[i].value_);
1535 value.set(pool, start, end - start);
1541 record_ = [Sources_ objectForKey:[self key]];
1543 NSURL *url([NSURL URLWithString:uri_]);
1547 host_ = [host_ lowercaseString];
1552 authority_ = [url path];
1555 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1556 if ((self = [super init]) != nil) {
1557 era_ = [database era];
1558 database_ = database;
1561 [self setMetaIndex:index inPool:pool];
1565 - (NSString *) getField:(NSString *)name {
1566 @synchronized (database_) {
1567 if ([database_ era] != era_ || index_ == NULL)
1570 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1575 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1580 pkgTagFile tags(&fd);
1582 pkgTagSection section;
1585 const char *start, *end;
1586 if (!section.Find([name UTF8String], start, end))
1587 return (NSString *) [NSNull null];
1589 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1592 - (NSComparisonResult) compareByName:(Source *)source {
1593 NSString *lhs = [self name];
1594 NSString *rhs = [source name];
1596 if ([lhs length] != 0 && [rhs length] != 0) {
1597 unichar lhc = [lhs characterAtIndex:0];
1598 unichar rhc = [rhs characterAtIndex:0];
1600 if (isalpha(lhc) && !isalpha(rhc))
1601 return NSOrderedAscending;
1602 else if (!isalpha(lhc) && isalpha(rhc))
1603 return NSOrderedDescending;
1606 return [lhs compare:rhs options:LaxCompareOptions_];
1609 - (NSString *) depictionForPackage:(NSString *)package {
1610 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1613 - (NSString *) supportForPackage:(NSString *)package {
1614 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1617 - (NSArray *) sections {
1618 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1621 - (void) _addSection:(NSString *)section {
1624 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1625 if (![sections containsObject:section]) {
1626 [sections addObject:section];
1630 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1635 - (bool) addSection:(NSString *)section {
1639 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1643 - (void) _removeSection:(NSString *)section {
1647 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1648 if ([sections containsObject:section]) {
1649 [sections removeObject:section];
1654 - (bool) removeSection:(NSString *)section {
1658 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1663 [Sources_ removeObjectForKey:[self key]];
1668 bool value(record_ != nil);
1669 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1673 - (NSDictionary *) record {
1681 - (NSString *) rooturi {
1685 - (NSString *) distribution {
1686 return distribution_;
1689 - (NSString *) type {
1693 - (NSString *) baseuri {
1694 return base_.empty() ? nil : (id) base_;
1697 - (NSString *) iconuri {
1698 if (NSString *base = [self baseuri])
1699 return [base stringByAppendingString:@"CydiaIcon.png"];
1704 - (NSURL *) iconURL {
1705 if (NSString *uri = [self iconuri])
1706 return [NSURL URLWithString:uri];
1710 - (NSString *) key {
1711 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1714 - (NSString *) host {
1718 - (NSString *) name {
1719 return origin_.empty() ? (id) authority_ : origin_;
1722 - (NSString *) shortDescription {
1723 return description_;
1726 - (NSString *) label {
1727 return label_.empty() ? (id) authority_ : label_;
1730 - (NSString *) origin {
1734 - (NSString *) version {
1738 - (NSString *) defaultIcon {
1739 return defaultIcon_;
1742 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1743 delegate_ = delegate;
1747 return !fetches_.empty();
1750 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1752 if (fetches_.erase(uri) == 0)
1754 } else if (files_.find(uri) == files_.end())
1756 else if (!fetches_.insert(uri).second)
1759 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1764 /* CydiaOperation Class {{{ */
1765 @interface CydiaOperation : NSObject {
1766 _H<NSString> operator_;
1767 _H<NSString> value_;
1770 - (NSString *) operator;
1771 - (NSString *) value;
1775 @implementation CydiaOperation
1777 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1778 if ((self = [super init]) != nil) {
1779 operator_ = [NSString stringWithUTF8String:_operator];
1780 value_ = [NSString stringWithUTF8String:value];
1784 + (NSArray *) _attributeKeys {
1785 return [NSArray arrayWithObjects:
1791 - (NSArray *) attributeKeys {
1792 return [[self class] _attributeKeys];
1795 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1796 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1799 - (NSString *) operator {
1803 - (NSString *) value {
1809 /* CydiaClause Class {{{ */
1810 @interface CydiaClause : NSObject {
1811 _H<NSString> package_;
1812 _H<CydiaOperation> version_;
1815 - (NSString *) package;
1816 - (CydiaOperation *) version;
1820 @implementation CydiaClause
1822 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1823 if ((self = [super init]) != nil) {
1824 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1826 if (const char *version = dep.TargetVer())
1827 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1829 version_ = (id) [NSNull null];
1833 + (NSArray *) _attributeKeys {
1834 return [NSArray arrayWithObjects:
1840 - (NSArray *) attributeKeys {
1841 return [[self class] _attributeKeys];
1844 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1845 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1848 - (NSString *) package {
1852 - (CydiaOperation *) version {
1858 /* CydiaRelation Class {{{ */
1859 @interface CydiaRelation : NSObject {
1860 _H<NSString> relationship_;
1861 _H<NSMutableArray> clauses_;
1864 - (NSString *) relationship;
1865 - (NSArray *) clauses;
1869 @implementation CydiaRelation
1871 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1872 if ((self = [super init]) != nil) {
1873 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1874 clauses_ = [NSMutableArray arrayWithCapacity:8];
1876 pkgCache::DepIterator start;
1877 pkgCache::DepIterator end;
1878 dep.GlobOr(start, end); // ++dep
1881 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1883 // yes, seriously. (wtf?)
1891 + (NSArray *) _attributeKeys {
1892 return [NSArray arrayWithObjects:
1898 - (NSArray *) attributeKeys {
1899 return [[self class] _attributeKeys];
1902 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1903 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1906 - (NSString *) relationship {
1907 return relationship_;
1910 - (NSArray *) clauses {
1914 - (void) addClause:(CydiaClause *)clause {
1915 [clauses_ addObject:clause];
1920 /* Package Class {{{ */
1921 struct ParsedPackage {
1925 CYString architecture_;
1928 CYString depiction_;
1935 @interface Package : NSObject {
1938 uint32_t essential_ : 1;
1939 uint32_t obsolete_ : 1;
1940 uint32_t ignored_ : 1;
1941 uint32_t pooled_ : 1;
1947 _transient Database *database_;
1949 pkgCache::VerIterator version_;
1950 pkgCache::PkgIterator iterator_;
1951 pkgCache::VerFileIterator file_;
1957 CYString installed_;
1959 const char *section_;
1960 _transient NSString *section$_;
1964 PackageValue *metadata_;
1965 ParsedPackage *parsed_;
1967 _H<NSMutableArray> tags_;
1970 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1971 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1973 - (pkgCache::PkgIterator) iterator;
1976 - (NSString *) section;
1977 - (NSString *) simpleSection;
1979 - (NSString *) longSection;
1980 - (NSString *) shortSection;
1984 - (MIMEAddress *) maintainer;
1986 - (NSString *) longDescription;
1987 - (NSString *) shortDescription;
1990 - (PackageValue *) metadata;
1993 - (bool) subscribed;
1994 - (bool) setSubscribed:(bool)subscribed;
1998 - (NSString *) latest;
1999 - (NSString *) installed;
2000 - (BOOL) uninstalled;
2003 - (BOOL) upgradableAndEssential:(BOOL)essential;
2006 - (BOOL) unfiltered;
2010 - (BOOL) halfConfigured;
2011 - (BOOL) halfInstalled;
2013 - (NSString *) mode;
2016 - (NSString *) name;
2018 - (NSString *) homepage;
2019 - (NSString *) depiction;
2020 - (MIMEAddress *) author;
2022 - (NSString *) support;
2024 - (NSArray *) files;
2025 - (NSArray *) warnings;
2026 - (NSArray *) applications;
2028 - (Source *) source;
2031 - (BOOL) matches:(NSArray *)query;
2033 - (BOOL) hasTag:(NSString *)tag;
2034 - (NSString *) primaryPurpose;
2035 - (NSArray *) purposes;
2036 - (bool) isCommercial;
2038 - (void) setIndex:(size_t)index;
2040 - (CYString &) cyname;
2042 - (uint32_t) compareBySection:(NSArray *)sections;
2047 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
2048 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2049 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2050 - (bool) isVisibleInSection:(NSString *)section source:(Source *)source;
2051 - (bool) isVisibleInSource:(Source *)source;
2055 uint32_t PackageChangesRadix(Package *self, void *) {
2060 uint32_t timestamp : 30;
2061 uint32_t ignored : 1;
2062 uint32_t upgradable : 1;
2066 bool upgradable([self upgradableAndEssential:YES]);
2067 value.bits.upgradable = upgradable ? 1 : 0;
2070 value.bits.timestamp = 0;
2071 value.bits.ignored = [self ignored] ? 0 : 1;
2072 value.bits.upgradable = 1;
2074 value.bits.timestamp = [self seen] >> 2;
2075 value.bits.ignored = 0;
2076 value.bits.upgradable = 0;
2079 return _not(uint32_t) - value.key;
2082 uint32_t PackagePrefixRadix(Package *self, void *context) {
2083 size_t offset(reinterpret_cast<size_t>(context));
2084 CYString &name([self cyname]);
2086 size_t size(name.size());
2089 char *text(name.data());
2092 if (!isdigit(text[0]))
2096 while (size != digits && isdigit(text[digits]))
2104 if (offset == 0 && zeros != 0) {
2105 memset(data, '0', zeros);
2106 memcpy(data + zeros, text, 4 - zeros);
2108 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2109 if (size <= offset - zeros)
2112 text += offset - zeros;
2113 size -= offset - zeros;
2116 memcpy(data, text, 4);
2118 memcpy(data, text, size);
2119 memset(data + size, 0, 4 - size);
2122 for (size_t i(0); i != 4; ++i)
2123 if (isalpha(data[i]))
2131 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2133 /* XXX: ntohl may be more honest */
2134 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2137 CYString &(*PackageName)(Package *self, SEL sel);
2139 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2140 _profile(PackageNameCompare)
2141 CYString &lhi(PackageName(lhs, @selector(cyname)));
2142 CYString &rhi(PackageName(rhs, @selector(cyname)));
2143 CFStringRef lhn(lhi), rhn(rhi);
2146 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2147 else if (rhn == NULL)
2148 return NSOrderedDescending;
2150 _profile(PackageNameCompare$NumbersLast)
2151 if (!lhi.empty() && !rhi.empty()) {
2152 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2153 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2154 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2155 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2156 return lha ? NSOrderedAscending : NSOrderedDescending;
2160 CFIndex length = CFStringGetLength(lhn);
2162 _profile(PackageNameCompare$Compare)
2163 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2168 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2169 return PackageNameCompare(*lhs, *rhs, context);
2172 struct PackageNameOrdering :
2173 std::binary_function<Package *, Package *, bool>
2175 _finline bool operator ()(Package *lhs, Package *rhs) const {
2176 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2180 @implementation Package
2182 - (NSString *) description {
2183 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2188 apr_pool_destroy(pool_);
2189 if (parsed_ != NULL)
2194 + (NSString *) webScriptNameForSelector:(SEL)selector {
2196 else if (selector == @selector(clear))
2198 else if (selector == @selector(getField:))
2200 else if (selector == @selector(getRecord))
2201 return @"getRecord";
2202 else if (selector == @selector(hasTag:))
2204 else if (selector == @selector(install))
2206 else if (selector == @selector(remove))
2212 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2213 return [self webScriptNameForSelector:selector] == nil;
2216 + (NSArray *) _attributeKeys {
2217 return [NSArray arrayWithObjects:
2238 @"shortDescription",
2250 - (NSArray *) attributeKeys {
2251 return [[self class] _attributeKeys];
2254 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2255 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2258 - (NSArray *) relations {
2259 @synchronized (database_) {
2260 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2261 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2262 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2266 - (NSString *) architecture {
2268 @synchronized (database_) {
2269 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2272 - (NSString *) getField:(NSString *)name {
2273 @synchronized (database_) {
2274 if ([database_ era] != era_ || file_.end())
2277 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2279 const char *start, *end;
2280 if (!parser.Find([name UTF8String], start, end))
2281 return (NSString *) [NSNull null];
2283 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2286 - (NSString *) getRecord {
2287 @synchronized (database_) {
2288 if ([database_ era] != era_ || file_.end())
2291 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2293 const char *start, *end;
2294 parser.GetRec(start, end);
2296 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2300 if (parsed_ != NULL)
2302 @synchronized (database_) {
2303 if ([database_ era] != era_ || file_.end())
2306 ParsedPackage *parsed(new ParsedPackage);
2309 _profile(Package$parse)
2310 pkgRecords::Parser *parser;
2312 _profile(Package$parse$Lookup)
2313 parser = &[database_ records]->Lookup(file_);
2319 _profile(Package$parse$Find)
2324 {"architecture", &parsed->architecture_},
2325 {"icon", &parsed->icon_},
2326 {"depiction", &parsed->depiction_},
2327 {"homepage", &parsed->homepage_},
2328 {"website", &website},
2330 {"support", &parsed->support_},
2331 {"author", &parsed->author_},
2332 {"md5sum", &parsed->md5sum_},
2335 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2336 const char *start, *end;
2338 if (parser->Find(names[i].name_, start, end)) {
2339 CYString &value(*names[i].value_);
2340 _profile(Package$parse$Value)
2341 value.set(pool_, start, end - start);
2347 _profile(Package$parse$Tagline)
2348 const char *start, *end;
2349 if (parser->ShortDesc(start, end)) {
2350 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2353 while (stop != start && stop[-1] == '\r')
2355 parsed->tagline_.set(pool_, start, stop - start);
2359 _profile(Package$parse$Retain)
2360 if (parsed->homepage_.empty())
2361 parsed->homepage_ = website;
2362 if (parsed->homepage_ == parsed->depiction_)
2363 parsed->homepage_.clear();
2364 if (parsed->support_.empty())
2365 parsed->support_ = bugs;
2370 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2371 if ((self = [super init]) != nil) {
2372 _profile(Package$initWithVersion)
2374 apr_pool_create(&pool_, NULL);
2380 database_ = database;
2381 era_ = [database era];
2385 pkgCache::PkgIterator iterator(version.ParentPkg());
2386 iterator_ = iterator;
2388 _profile(Package$initWithVersion$Version)
2389 if (!version_.end())
2390 file_ = version_.FileList();
2392 pkgCache &cache([database_ cache]);
2393 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2397 _profile(Package$initWithVersion$Cache)
2398 name_.set(NULL, iterator.Display());
2400 latest_.set(NULL, StripVersion_(version_.VerStr()));
2402 pkgCache::VerIterator current(iterator.CurrentVer());
2404 installed_.set(NULL, StripVersion_(current.VerStr()));
2407 _profile(Package$initWithVersion$Tags)
2408 pkgCache::TagIterator tag(iterator.TagList());
2410 tags_ = [NSMutableArray arrayWithCapacity:8];
2412 goto tag; for (; !tag.end(); ++tag) tag: {
2413 const char *name(tag.Name());
2414 NSString *string((NSString *) CYStringCreate(name));
2418 [tags_ addObject:[string autorelease]];
2420 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2421 if (strcmp(name + 6, "enduser") == 0)
2423 else if (strcmp(name + 6, "hacker") == 0)
2425 else if (strcmp(name + 6, "developer") == 0)
2427 else if (strcmp(name + 6, "cydia") == 0)
2433 if (strncmp(name, "cydia::", 7) == 0) {
2434 if (strcmp(name + 7, "essential") == 0)
2436 else if (strcmp(name + 7, "obsolete") == 0)
2443 _profile(Package$initWithVersion$Metadata)
2444 const char *mixed(iterator.Name());
2445 size_t size(strlen(mixed));
2446 char lower[size + 1];
2448 for (size_t i(0); i != size; ++i)
2449 lower[i] = mixed[i] | 0x20;
2452 PackageValue *metadata(PackageFind(lower, size));
2453 metadata_ = metadata;
2455 id_.set(NULL, metadata->name_, size);
2457 const char *latest(version_.VerStr());
2458 size_t length(strlen(latest));
2460 uint16_t vhash(hashlittle(latest, length));
2462 size_t capped(std::min<size_t>(8, length));
2463 latest = latest + length - capped;
2465 if (metadata->first_ == 0)
2466 metadata->first_ = now_;
2468 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2469 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2470 metadata->vhash_ = vhash;
2471 metadata->last_ = now_;
2472 } else if (metadata->last_ == 0)
2473 metadata->last_ = metadata->first_;
2476 _profile(Package$initWithVersion$Section)
2477 section_ = version_.Section();
2480 _profile(Package$initWithVersion$Flags)
2481 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2482 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2487 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2488 pkgCache::VerIterator version;
2490 _profile(Package$packageWithIterator$GetCandidateVer)
2491 version = [database policy]->GetCandidateVer(iterator);
2499 _profile(Package$packageWithIterator$Allocate)
2500 package = [Package allocWithZone:zone];
2503 _profile(Package$packageWithIterator$Initialize)
2505 initWithVersion:version
2512 _profile(Package$packageWithIterator$Autorelease)
2513 package = [package autorelease];
2519 - (pkgCache::PkgIterator) iterator {
2523 - (NSString *) section {
2524 if (section$_ == nil) {
2525 if (section_ == NULL)
2528 _profile(Package$section$mappedSectionForPointer)
2529 section$_ = [database_ mappedSectionForPointer:section_];
2534 - (NSString *) simpleSection {
2535 if (NSString *section = [self section])
2536 return Simplify(section);
2541 - (NSString *) longSection {
2542 return LocalizeSection([self section]);
2545 - (NSString *) shortSection {
2546 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2549 - (NSString *) uri {
2552 pkgIndexFile *index;
2553 pkgCache::PkgFileIterator file(file_.File());
2554 if (![database_ list].FindIndex(file, index))
2556 return [NSString stringWithUTF8String:iterator_->Path];
2557 //return [NSString stringWithUTF8String:file.Site()];
2558 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2562 - (MIMEAddress *) maintainer {
2563 @synchronized (database_) {
2564 if ([database_ era] != era_ || file_.end())
2567 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2568 const std::string &maintainer(parser->Maintainer());
2569 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2572 - (NSString *) md5sum {
2573 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2577 @synchronized (database_) {
2578 if ([database_ era] != era_ || version_.end())
2581 return version_->InstalledSize;
2584 - (NSString *) longDescription {
2585 @synchronized (database_) {
2586 if ([database_ era] != era_ || file_.end())
2589 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2590 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2592 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2593 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2594 if ([lines count] < 2)
2597 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2598 for (size_t i(1), e([lines count]); i != e; ++i) {
2599 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2600 [trimmed addObject:trim];
2603 return [trimmed componentsJoinedByString:@"\n"];
2606 - (NSString *) shortDescription {
2607 if (parsed_ != NULL)
2608 return static_cast<NSString *>(parsed_->tagline_);
2610 @synchronized (database_) {
2611 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2613 const char *start, *end;
2614 if (!parser.ShortDesc(start, end))
2617 if (end - start > 200)
2621 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2624 while (end != start && end[-1] == '\r')
2628 return [(id) CYStringCreate(start, end - start) autorelease];
2632 _profile(Package$index)
2633 CFStringRef name((CFStringRef) [self name]);
2634 if (CFStringGetLength(name) == 0)
2636 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2637 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2639 return toupper(character);
2643 - (PackageValue *) metadata {
2648 PackageValue *metadata([self metadata]);
2649 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2652 - (bool) subscribed {
2653 return [self metadata]->subscribed_;
2656 - (bool) setSubscribed:(bool)subscribed {
2657 PackageValue *metadata([self metadata]);
2658 if (metadata->subscribed_ == subscribed)
2660 metadata->subscribed_ = subscribed;
2668 - (NSString *) latest {
2672 - (NSString *) installed {
2676 - (BOOL) uninstalled {
2677 return installed_.empty();
2681 return !version_.end();
2684 - (BOOL) upgradableAndEssential:(BOOL)essential {
2685 _profile(Package$upgradableAndEssential)
2686 pkgCache::VerIterator current(iterator_.CurrentVer());
2688 return essential && essential_;
2690 return !version_.end() && version_ != current;
2694 - (BOOL) essential {
2699 return [database_ cache][iterator_].InstBroken();
2702 - (BOOL) unfiltered {
2703 _profile(Package$unfiltered$obsolete)
2704 if (_unlikely(obsolete_))
2708 _profile(Package$unfiltered$role)
2709 if (_unlikely(role_ > 3))
2717 if (![self unfiltered])
2722 _profile(Package$visible$section)
2723 section = [self section];
2726 _profile(Package$visible$isSectionVisible)
2727 if (!isSectionVisible(section))
2735 unsigned char current(iterator_->CurrentState);
2736 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2739 - (BOOL) halfConfigured {
2740 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2743 - (BOOL) halfInstalled {
2744 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2748 @synchronized (database_) {
2749 if ([database_ era] != era_ || iterator_.end())
2752 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2753 return state.Mode != pkgDepCache::ModeKeep;
2756 - (NSString *) mode {
2757 @synchronized (database_) {
2758 if ([database_ era] != era_ || iterator_.end())
2761 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2763 switch (state.Mode) {
2764 case pkgDepCache::ModeDelete:
2765 if ((state.iFlags & pkgDepCache::Purge) != 0)
2769 case pkgDepCache::ModeKeep:
2770 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2771 return @"REINSTALL";
2772 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2776 case pkgDepCache::ModeInstall:
2777 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2778 return @"REINSTALL";
2779 else*/ switch (state.Status) {
2781 return @"DOWNGRADE";
2787 return @"NEW_INSTALL";
2798 - (NSString *) name {
2799 return name_.empty() ? id_ : name_;
2802 - (UIImage *) icon {
2803 NSString *section = [self simpleSection];
2806 if (parsed_ != NULL)
2807 if (NSString *href = parsed_->icon_)
2808 if ([href hasPrefix:@"file:///"])
2809 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2810 if (icon == nil) if (section != nil)
2811 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2812 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2813 if ([dicon hasPrefix:@"file:///"])
2814 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2816 icon = [UIImage applicationImageNamed:@"unknown.png"];
2820 - (NSString *) homepage {
2821 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2824 - (NSString *) depiction {
2825 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2828 - (MIMEAddress *) author {
2829 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2832 - (NSString *) support {
2833 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
2836 - (NSArray *) files {
2837 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2838 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2841 fin.open([path UTF8String]);
2846 while (std::getline(fin, line))
2847 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2852 - (NSString *) state {
2853 @synchronized (database_) {
2854 if ([database_ era] != era_ || file_.end())
2857 switch (iterator_->CurrentState) {
2858 case pkgCache::State::NotInstalled:
2859 return @"NotInstalled";
2860 case pkgCache::State::UnPacked:
2862 case pkgCache::State::HalfConfigured:
2863 return @"HalfConfigured";
2864 case pkgCache::State::HalfInstalled:
2865 return @"HalfInstalled";
2866 case pkgCache::State::ConfigFiles:
2867 return @"ConfigFiles";
2868 case pkgCache::State::Installed:
2869 return @"Installed";
2870 case pkgCache::State::TriggersAwaited:
2871 return @"TriggersAwaited";
2872 case pkgCache::State::TriggersPending:
2873 return @"TriggersPending";
2876 return (NSString *) [NSNull null];
2879 - (NSString *) selection {
2880 @synchronized (database_) {
2881 if ([database_ era] != era_ || file_.end())
2884 switch (iterator_->SelectedState) {
2885 case pkgCache::State::Unknown:
2887 case pkgCache::State::Install:
2889 case pkgCache::State::Hold:
2891 case pkgCache::State::DeInstall:
2892 return @"DeInstall";
2893 case pkgCache::State::Purge:
2897 return (NSString *) [NSNull null];
2900 - (NSArray *) warnings {
2901 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2902 const char *name(iterator_.Name());
2904 size_t length(strlen(name));
2905 if (length < 2) invalid:
2906 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2907 else for (size_t i(0); i != length; ++i)
2909 /* XXX: technically this is not allowed */
2910 (name[i] < 'A' || name[i] > 'Z') &&
2911 (name[i] < 'a' || name[i] > 'z') &&
2912 (name[i] < '0' || name[i] > '9') &&
2913 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2916 if (strcmp(name, "cydia") != 0) {
2919 bool _private = false;
2922 bool repository = [[self section] isEqualToString:@"Repositories"];
2924 if (NSArray *files = [self files])
2925 for (NSString *file in files)
2926 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2928 else if (!user && [file isEqualToString:@"/User"])
2930 else if (!_private && [file isEqualToString:@"/private"])
2932 else if (!stash && [file isEqualToString:@"/var/stash"])
2935 /* XXX: this is not sensitive enough. only some folders are valid. */
2936 if (cydia && !repository)
2937 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2939 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2941 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2943 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2946 return [warnings count] == 0 ? nil : warnings;
2949 - (NSArray *) applications {
2950 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2952 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2954 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2955 if (NSArray *files = [self files])
2956 for (NSString *file in files)
2957 if (application_r(file)) {
2958 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2959 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2960 if ([id isEqualToString:me])
2963 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2965 display = application_r[1];
2967 NSString *bundle([file stringByDeletingLastPathComponent]);
2968 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2969 // XXX: maybe this should check if this is really a string, not just for length
2970 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
2972 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2974 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2975 [applications addObject:application];
2977 [application addObject:id];
2978 [application addObject:display];
2979 [application addObject:url];
2982 return [applications count] == 0 ? nil : applications;
2985 - (Source *) source {
2986 if (source_ == nil) {
2987 @synchronized (database_) {
2988 if ([database_ era] != era_ || file_.end())
2989 source_ = (Source *) [NSNull null];
2991 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2995 return source_ == (Source *) [NSNull null] ? nil : source_;
3002 - (BOOL) matches:(NSArray *)query {
3003 if (query == nil || [query count] == 0)
3012 string = [self name];
3013 length = [string length];
3015 for (NSString *term in query) {
3016 range = [string rangeOfString:term options:MatchCompareOptions_];
3017 if (range.location != NSNotFound)
3018 rank_ -= 6 * 1000000 / length;
3023 length = [string length];
3025 for (NSString *term in query) {
3026 range = [string rangeOfString:term options:MatchCompareOptions_];
3027 if (range.location != NSNotFound)
3028 rank_ -= 6 * 1000000 / length;
3032 string = [self shortDescription];
3033 length = [string length];
3034 NSUInteger stop(std::min<NSUInteger>(length, 200));
3036 for (NSString *term in query) {
3037 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3038 if (range.location != NSNotFound)
3039 rank_ -= 2 * 100000;
3045 - (NSArray *) tags {
3049 - (BOOL) hasTag:(NSString *)tag {
3050 return tags_ == nil ? NO : [tags_ containsObject:tag];
3053 - (NSString *) primaryPurpose {
3054 for (NSString *tag in (NSArray *) tags_)
3055 if ([tag hasPrefix:@"purpose::"])
3056 return [tag substringFromIndex:9];
3060 - (NSArray *) purposes {
3061 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3062 for (NSString *tag in (NSArray *) tags_)
3063 if ([tag hasPrefix:@"purpose::"])
3064 [purposes addObject:[tag substringFromIndex:9]];
3065 return [purposes count] == 0 ? nil : purposes;
3068 - (bool) isCommercial {
3069 return [self hasTag:@"cydia::commercial"];
3072 - (void) setIndex:(size_t)index {
3073 if (metadata_->index_ != index)
3074 metadata_->index_ = index;
3077 - (CYString &) cyname {
3078 return name_.empty() ? id_ : name_;
3081 - (uint32_t) compareBySection:(NSArray *)sections {
3082 NSString *section([self section]);
3083 for (size_t i(0), e([sections count]); i != e; ++i) {
3084 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3088 return _not(uint32_t);
3092 @synchronized (database_) {
3093 pkgProblemResolver *resolver = [database_ resolver];
3094 resolver->Clear(iterator_);
3096 pkgCacheFile &cache([database_ cache]);
3097 cache->SetReInstall(iterator_, false);
3098 cache->MarkKeep(iterator_, false);
3102 @synchronized (database_) {
3103 pkgProblemResolver *resolver = [database_ resolver];
3104 resolver->Clear(iterator_);
3105 resolver->Protect(iterator_);
3107 pkgCacheFile &cache([database_ cache]);
3108 cache->SetReInstall(iterator_, false);
3109 cache->MarkInstall(iterator_, false);
3111 pkgDepCache::StateCache &state((*cache)[iterator_]);
3112 if (!state.Install())
3113 cache->SetReInstall(iterator_, true);
3117 @synchronized (database_) {
3118 pkgProblemResolver *resolver = [database_ resolver];
3119 resolver->Clear(iterator_);
3120 resolver->Remove(iterator_);
3121 resolver->Protect(iterator_);
3123 pkgCacheFile &cache([database_ cache]);
3124 cache->SetReInstall(iterator_, false);
3125 cache->MarkDelete(iterator_, true);
3128 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3129 _profile(Package$isUnfilteredAndSearchedForBy)
3132 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3133 value &= [self unfiltered];
3136 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3137 value &= [self matches:query];
3144 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3145 if ([search length] == 0)
3148 _profile(Package$isUnfilteredAndSelectedForBy)
3151 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3152 value &= [self unfiltered];
3155 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3156 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3163 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3164 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3167 - (bool) isVisibleInSection:(NSString *)name source:(Source *)source {
3168 NSString *section([self section]);
3172 section == nil && [name length] == 0 ||
3173 [name isEqualToString:section]
3176 [self source] == source
3177 ) && [self visible];
3180 - (bool) isVisibleInSource:(Source *)source {
3181 return [self source] == source && [self visible];
3186 /* Section Class {{{ */
3187 @interface Section : NSObject {
3192 _H<NSString> localized_;
3195 - (NSComparisonResult) compareByLocalized:(Section *)section;
3196 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3197 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3198 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3199 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3200 - (NSString *) name;
3207 - (void) addToCount;
3209 - (void) setCount:(size_t)count;
3210 - (NSString *) localized;
3214 @implementation Section
3216 - (NSComparisonResult) compareByLocalized:(Section *)section {
3217 NSString *lhs(localized_);
3218 NSString *rhs([section localized]);
3220 /*if ([lhs length] != 0 && [rhs length] != 0) {
3221 unichar lhc = [lhs characterAtIndex:0];
3222 unichar rhc = [rhs characterAtIndex:0];
3224 if (isalpha(lhc) && !isalpha(rhc))
3225 return NSOrderedAscending;
3226 else if (!isalpha(lhc) && isalpha(rhc))
3227 return NSOrderedDescending;
3230 return [lhs compare:rhs options:LaxCompareOptions_];
3233 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3234 if ((self = [self initWithName:name localize:NO]) != nil) {
3235 if (localized != nil)
3236 localized_ = localized;
3240 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3241 return [self initWithName:name row:0 localize:localize];
3244 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3245 if ((self = [super init]) != nil) {
3250 localized_ = LocalizeSection(name_);
3254 /* XXX: localize the index thingees */
3255 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3256 if ((self = [super init]) != nil) {
3257 name_ = [NSString stringWithCharacters:&index length:1];
3263 - (NSString *) name {
3283 - (void) addToCount {
3287 - (void) setCount:(size_t)count {
3291 - (NSString *) localized {
3298 class CydiaLogCleaner :
3299 public pkgArchiveCleaner
3302 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3307 /* Database Implementation {{{ */
3308 @implementation Database
3310 + (Database *) sharedInstance {
3311 static _H<Database> instance;
3312 if (instance == nil)
3313 instance = [[[Database alloc] init] autorelease];
3321 - (void) releasePackages {
3322 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3323 CFArrayRemoveAllValues(packages_);
3327 // XXX: actually implement this thing
3329 [self releasePackages];
3330 apr_pool_destroy(pool_);
3331 NSRecycleZone(zone_);
3335 - (void) _readCydia:(NSNumber *)fd {
3336 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3337 std::istream is(&ib);
3340 static Pcre finish_r("^finish:([^:]*)$");
3342 while (std::getline(is, line)) {
3343 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3345 const char *data(line.c_str());
3346 size_t size = line.size();
3347 lprintf("C:%s\n", data);
3349 if (finish_r(data, size)) {
3350 NSString *finish = finish_r[1];
3351 int index = [Finishes_ indexOfObject:finish];
3352 if (index != INT_MAX && index > Finish_)
3362 - (void) _readStatus:(NSNumber *)fd {
3363 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3364 std::istream is(&ib);
3367 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3368 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3370 while (std::getline(is, line)) {
3371 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3373 const char *data(line.c_str());
3374 size_t size(line.size());
3375 lprintf("S:%s\n", data);
3377 if (conffile_r(data, size)) {
3378 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3379 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3380 } else if (strncmp(data, "status: ", 8) == 0) {
3381 // status: <package>: {unpacked,half-configured,installed}
3382 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3383 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3384 } else if (strncmp(data, "processing: ", 12) == 0) {
3385 // processing: configure: config-test
3386 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3387 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3388 } else if (pmstatus_r(data, size)) {
3389 std::string type([pmstatus_r[1] UTF8String]);
3391 NSString *package = pmstatus_r[2];
3392 if ([package isEqualToString:@"dpkg-exec"])
3395 float percent([pmstatus_r[3] floatValue]);
3396 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3398 NSString *string = pmstatus_r[4];
3400 if (type == "pmerror") {
3401 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3402 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3403 } else if (type == "pmstatus") {
3404 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3405 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3406 } else if (type == "pmconffile")
3407 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3409 lprintf("E:unknown pmstatus\n");
3411 lprintf("E:unknown status\n");
3419 - (void) _readOutput:(NSNumber *)fd {
3420 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3421 std::istream is(&ib);
3424 while (std::getline(is, line)) {
3425 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3427 lprintf("O:%s\n", line.c_str());
3429 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3430 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3442 - (Package *) packageWithName:(NSString *)name {
3445 @synchronized (self) {
3446 if (static_cast<pkgDepCache *>(cache_) == NULL)
3448 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3449 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3453 if ((self = [super init]) != nil) {
3460 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3461 apr_pool_create(&pool_, NULL);
3463 size_t capacity(MetaFile_->active_);
3469 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3470 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3474 _assert(pipe(fds) != -1);
3477 _config->Set("APT::Keep-Fds::", cydiafd_);
3478 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3481 detachNewThreadSelector:@selector(_readCydia:)
3483 withObject:[NSNumber numberWithInt:fds[0]]
3486 _assert(pipe(fds) != -1);
3490 detachNewThreadSelector:@selector(_readStatus:)
3492 withObject:[NSNumber numberWithInt:fds[0]]
3495 _assert(pipe(fds) != -1);
3496 _assert(dup2(fds[0], 0) != -1);
3497 _assert(close(fds[0]) != -1);
3499 input_ = fdopen(fds[1], "a");
3501 _assert(pipe(fds) != -1);
3502 _assert(dup2(fds[1], 1) != -1);
3503 _assert(close(fds[1]) != -1);
3506 detachNewThreadSelector:@selector(_readOutput:)
3508 withObject:[NSNumber numberWithInt:fds[0]]
3513 - (pkgCacheFile &) cache {
3517 - (pkgDepCache::Policy *) policy {
3521 - (pkgRecords *) records {
3525 - (pkgProblemResolver *) resolver {
3529 - (pkgAcquire &) fetcher {
3533 - (pkgSourceList &) list {
3537 - (NSArray *) packages {
3538 return (NSArray *) packages_;
3541 - (NSArray *) sources {
3545 - (Source *) sourceWithKey:(NSString *)key {
3546 for (Source *source in [self sources]) {
3547 if ([[source key] isEqualToString:key])
3552 - (bool) popErrorWithTitle:(NSString *)title {
3555 while (!_error->empty()) {
3557 bool warning(!_error->PopMessage(error));
3562 size_t size(error.size());
3563 if (size == 0 || error[size - 1] != '\n')
3565 error.resize(size - 1);
3568 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3570 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3571 if (warning && no_pubkey(error.c_str()))
3574 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3580 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3581 return [self popErrorWithTitle:title] || !success;
3584 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3585 @synchronized (self) {
3588 [self releasePackages];
3591 [sourceList_ removeAllObjects];
3611 apr_pool_clear(pool_);
3613 NSRecycleZone(zone_);
3614 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3616 int chk(creat("/tmp/cydia.chk", 0644));
3620 if (invocation != nil)
3621 [invocation invoke];
3623 NSString *title(UCLocalize("DATABASE"));
3625 list_ = new pkgSourceList();
3626 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3629 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3630 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3631 [sourceList_ addObject:object];
3635 OpProgress progress;
3637 if (!cache_.Open(progress, true)) {
3638 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3639 while (!_error->empty()) {
3641 bool warning(!_error->PopMessage(error));
3643 lprintf("cache_.Open():[%s]\n", error.c_str());
3645 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3649 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3650 repair = @selector(configure);
3651 //else if (error == "The package lists or status file could not be parsed or opened.")
3652 // repair = @selector(update);
3653 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3654 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3655 // else if (error == "Malformed Status line")
3656 // else if (error == "The list of sources could not be read.")
3658 if (repair != NULL) {
3660 [delegate_ repairWithSelector:repair];
3669 unlink("/tmp/cydia.chk");
3671 now_ = [[NSDate date] timeIntervalSince1970];
3673 policy_ = new pkgDepCache::Policy();
3674 records_ = new pkgRecords(cache_);
3675 resolver_ = new pkgProblemResolver(cache_);
3676 fetcher_ = new pkgAcquire(&status_);
3679 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3680 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3684 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3687 if (cache_->BrokenCount() != 0) {
3688 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3691 if (cache_->BrokenCount() != 0) {
3692 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3696 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3700 for (Source *object in (id) sourceList_) {
3701 metaIndex *source([object metaIndex]);
3702 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3703 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3704 // XXX: this could be more intelligent
3705 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3706 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3708 sourceMap_[cached->ID] = object;
3713 /*std::vector<Package *> packages;
3714 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3719 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3720 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3721 //packages.push_back(package);
3722 CFArrayAppendValue(packages_, CFRetain(package));
3726 /*if (packages.empty())
3727 packages_ = [[NSArray alloc] init];
3729 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3732 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3733 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3734 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3742 /*if (!packages.empty())
3743 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3744 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3746 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3748 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3750 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3754 size_t count(CFArrayGetCount(packages_));
3755 MetaFile_->active_ = count;
3757 for (size_t index(0); index != count; ++index)
3758 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3765 @synchronized (self) {
3767 resolver_ = new pkgProblemResolver(cache_);
3769 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3770 if (!cache_[iterator].Keep())
3771 cache_->MarkKeep(iterator, false);
3772 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3773 cache_->SetReInstall(iterator, false);
3776 - (void) configure {
3777 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3779 system([dpkg UTF8String]);
3784 @synchronized (self) {
3785 // XXX: I don't remember this condition
3790 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3792 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3794 if ([self popErrorWithTitle:title])
3798 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3800 CydiaLogCleaner cleaner;
3801 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3808 fetcher_->Shutdown();
3810 pkgRecords records(cache_);
3812 lock_ = new FileFd();
3813 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3815 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3817 if ([self popErrorWithTitle:title])
3821 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3824 manager_ = (_system->CreatePM(cache_));
3825 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3832 bool substrate(RestartSubstrate_);
3833 RestartSubstrate_ = false;
3835 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3837 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3839 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3841 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3842 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3845 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3847 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3849 [self popErrorWithTitle:title];
3853 bool failed = false;
3854 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3855 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3857 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3860 std::string uri = (*item)->DescURI();
3861 std::string error = (*item)->ErrorText;
3863 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3866 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3867 [delegate_ addProgressEventOnMainThread:event forTask:title];
3870 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3878 RestartSubstrate_ = true;
3881 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3882 if ([self popErrorWithTitle:title])
3885 if (result == pkgPackageManager::Failed) {
3890 if (result != pkgPackageManager::Completed) {
3895 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3897 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3899 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3900 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3903 if (![before isEqualToArray:after])
3908 NSString *title(UCLocalize("UPGRADE"));
3909 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3915 [self updateWithStatus:status_];
3918 - (void) updateWithStatus:(CancelStatus &)status {
3919 NSString *title(UCLocalize("REFRESHING_DATA"));
3922 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3926 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3927 if ([self popErrorWithTitle:title])
3930 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3932 bool success(ListUpdate(status, list, PulseInterval_));
3933 if (status.WasCancelled())
3936 [self popErrorWithTitle:title forOperation:success];
3937 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3941 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3944 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3945 delegate_ = delegate;
3948 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3949 progress_ = delegate;
3950 status_.setDelegate(delegate);
3953 - (NSObject<ProgressDelegate> *) progressDelegate {
3957 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3958 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3959 return i == sourceMap_.end() ? nil : i->second;
3962 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
3963 for (Source *source in (id) sourceList_)
3964 [source setFetch:fetch forURI:uri];
3967 - (NSString *) mappedSectionForPointer:(const char *)section {
3968 _H<NSString> *mapped;
3970 _profile(Database$mappedSectionForPointer$Cache)
3971 mapped = §ions_[section];
3974 if (*mapped == NULL) {
3975 size_t length(strlen(section));
3976 char spaced[length + 1];
3978 _profile(Database$mappedSectionForPointer$Replace)
3979 for (size_t index(0); index != length; ++index)
3980 spaced[index] = section[index] == '_' ? ' ' : section[index];
3981 spaced[length] = '\0';
3986 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3987 string = [NSString stringWithUTF8String:spaced];
3990 _profile(Database$mappedSectionForPointer$Map)
3991 string = [SectionMap_ objectForKey:string] ?: string;
4001 static _H<NSMutableSet> Diversions_;
4003 @interface Diversion : NSObject {
4006 _H<NSString> format_;
4011 @implementation Diversion
4013 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4014 if ((self = [super init]) != nil) {
4015 pattern_ = [from UTF8String];
4021 - (NSString *) divert:(NSString *)url {
4022 return !pattern_(url) ? nil : pattern_->*format_;
4025 + (NSURL *) divertURL:(NSURL *)url {
4027 NSString *href([url absoluteString]);
4029 for (Diversion *diversion in (id) Diversions_)
4030 if (NSString *diverted = [diversion divert:href]) {
4032 NSLog(@"div: %@", diverted);
4034 url = [NSURL URLWithString:diverted];
4041 - (NSString *) key {
4045 - (NSUInteger) hash {
4049 - (BOOL) isEqual:(Diversion *)object {
4050 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4055 @interface CydiaObject : NSObject {
4056 _H<CyteWebViewController> indirect_;
4057 _transient id delegate_;
4060 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4066 @interface CydiaWebViewController : CyteWebViewController {
4067 _H<CydiaObject> cydia_;
4070 + (void) addDiversion:(Diversion *)diversion;
4071 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4072 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4073 - (void) setDelegate:(id)delegate;
4077 /* Web Scripting {{{ */
4078 @implementation CydiaObject
4080 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4081 if ((self = [super init]) != nil) {
4082 indirect_ = (CyteWebViewController *) indirect;
4086 - (void) setDelegate:(id)delegate {
4087 delegate_ = delegate;
4090 + (NSArray *) _attributeKeys {
4091 return [NSArray arrayWithObjects:
4094 @"coreFoundationVersionNumber",
4111 - (NSArray *) attributeKeys {
4112 return [[self class] _attributeKeys];
4115 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4116 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4119 - (NSString *) version {
4123 - (NSString *) build {
4127 - (NSString *) coreFoundationVersionNumber {
4128 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4131 - (NSString *) device {
4132 return UniqueIdentifier();
4135 - (NSString *) firmware {
4136 return [[UIDevice currentDevice] systemVersion];
4139 - (NSString *) hostname {
4140 return [[UIDevice currentDevice] name];
4143 - (NSString *) idiom {
4144 return (id) Idiom_ ?: [NSNull null];
4147 - (NSString *) mcc {
4148 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4149 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4153 - (NSString *) mnc {
4154 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4155 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4159 - (NSString *) operator {
4160 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4161 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4165 - (NSString *) bbsnum {
4166 return (id) BBSNum_ ?: [NSNull null];
4169 - (NSString *) ecid {
4170 return (id) ChipID_ ?: [NSNull null];
4173 - (NSString *) serial {
4174 return SerialNumber_;
4177 - (NSString *) role {
4178 return (id) [NSNull null];
4181 - (NSString *) model {
4182 return [NSString stringWithUTF8String:Machine_];
4185 - (NSString *) token {
4186 return (id) Token_ ?: [NSNull null];
4189 + (NSString *) webScriptNameForSelector:(SEL)selector {
4191 else if (selector == @selector(addBridgedHost:))
4192 return @"addBridgedHost";
4193 else if (selector == @selector(addInsecureHost:))
4194 return @"addInsecureHost";
4195 else if (selector == @selector(addInternalRedirect::))
4196 return @"addInternalRedirect";
4197 else if (selector == @selector(addPipelinedHost:scheme:))
4198 return @"addPipelinedHost";
4199 else if (selector == @selector(addSource:::))
4200 return @"addSource";
4201 else if (selector == @selector(addTokenHost:))
4202 return @"addTokenHost";
4203 else if (selector == @selector(addTrivialSource:))
4204 return @"addTrivialSource";
4205 else if (selector == @selector(close))
4207 else if (selector == @selector(du:))
4209 else if (selector == @selector(stringWithFormat:arguments:))
4211 else if (selector == @selector(getAllSources))
4212 return @"getAllSources";
4213 else if (selector == @selector(getApplicationInfo:value:))
4214 return @"getApplicationInfoValue";
4215 else if (selector == @selector(getKernelNumber:))
4216 return @"getKernelNumber";
4217 else if (selector == @selector(getKernelString:))
4218 return @"getKernelString";
4219 else if (selector == @selector(getInstalledPackages))
4220 return @"getInstalledPackages";
4221 else if (selector == @selector(getIORegistryEntry::))
4222 return @"getIORegistryEntry";
4223 else if (selector == @selector(getLocaleIdentifier))
4224 return @"getLocaleIdentifier";
4225 else if (selector == @selector(getPreferredLanguages))
4226 return @"getPreferredLanguages";
4227 else if (selector == @selector(getPackageById:))
4228 return @"getPackageById";
4229 else if (selector == @selector(getMetadataKeys))
4230 return @"getMetadataKeys";
4231 else if (selector == @selector(getMetadataValue:))
4232 return @"getMetadataValue";
4233 else if (selector == @selector(getSessionValue:))
4234 return @"getSessionValue";
4235 else if (selector == @selector(installPackages:))
4236 return @"installPackages";
4237 else if (selector == @selector(isReachable:))
4238 return @"isReachable";
4239 else if (selector == @selector(localizedStringForKey:value:table:))
4241 else if (selector == @selector(popViewController:))
4242 return @"popViewController";
4243 else if (selector == @selector(refreshSources))
4244 return @"refreshSources";
4245 else if (selector == @selector(registerFrame:))
4246 return @"registerFrame";
4247 else if (selector == @selector(removeButton))
4248 return @"removeButton";
4249 else if (selector == @selector(saveConfig))
4250 return @"saveConfig";
4251 else if (selector == @selector(setMetadataValue::))
4252 return @"setMetadataValue";
4253 else if (selector == @selector(setSessionValue::))
4254 return @"setSessionValue";
4255 else if (selector == @selector(substitutePackageNames:))
4256 return @"substitutePackageNames";
4257 else if (selector == @selector(scrollToBottom:))
4258 return @"scrollToBottom";
4259 else if (selector == @selector(setAllowsNavigationAction:))
4260 return @"setAllowsNavigationAction";
4261 else if (selector == @selector(setBadgeValue:))
4262 return @"setBadgeValue";
4263 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4264 return @"setButtonImage";
4265 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4266 return @"setButtonTitle";
4267 else if (selector == @selector(setHidesBackButton:))
4268 return @"setHidesBackButton";
4269 else if (selector == @selector(setHidesNavigationBar:))
4270 return @"setHidesNavigationBar";
4271 else if (selector == @selector(setNavigationBarStyle:))
4272 return @"setNavigationBarStyle";
4273 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4274 return @"setNavigationBarTintColor";
4275 else if (selector == @selector(setPasteboardString:))
4276 return @"setPasteboardString";
4277 else if (selector == @selector(setPasteboardURL:))
4278 return @"setPasteboardURL";
4279 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4280 return @"setScrollAlwaysBounceVertical";
4281 else if (selector == @selector(setScrollIndicatorStyle:))
4282 return @"setScrollIndicatorStyle";
4283 else if (selector == @selector(setToken:))
4285 else if (selector == @selector(setViewportWidth:))
4286 return @"setViewportWidth";
4287 else if (selector == @selector(statfs:))
4289 else if (selector == @selector(supports:))
4291 else if (selector == @selector(unload))
4297 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4298 return [self webScriptNameForSelector:selector] == nil;
4301 - (BOOL) supports:(NSString *)feature {
4302 return [feature isEqualToString:@"window.open"];
4306 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4309 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4310 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4313 - (void) setScrollIndicatorStyle:(NSString *)style {
4314 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4317 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4318 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4321 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4323 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4324 return (id) [NSNull null];
4325 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4327 return (id) [NSNull null];
4328 return [info objectForKey:key];
4331 - (NSNumber *) getKernelNumber:(NSString *)name {
4332 const char *string([name UTF8String]);
4335 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4336 return (id) [NSNull null];
4338 if (size != sizeof(int))
4339 return (id) [NSNull null];
4342 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4343 return (id) [NSNull null];
4345 return [NSNumber numberWithInt:value];
4348 - (NSString *) getKernelString:(NSString *)name {
4349 const char *string([name UTF8String]);
4352 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4353 return (id) [NSNull null];
4355 char value[size + 1];
4356 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4357 return (id) [NSNull null];
4359 // XXX: just in case you request something ludicrous
4362 return [NSString stringWithCString:value];
4365 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4366 NSObject *value(CYIOGetValue([path UTF8String], entry));
4369 if ([value isKindOfClass:[NSData class]])
4370 value = CYHex((NSData *) value);
4375 - (NSArray *) getMetadataKeys {
4376 @synchronized (Values_) {
4377 return [Values_ allKeys];
4380 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4381 WebFrame *frame([iframe contentFrame]);
4382 [indirect_ registerFrame:frame];
4385 - (id) getMetadataValue:(NSString *)key {
4386 @synchronized (Values_) {
4387 return [Values_ objectForKey:key];
4390 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4391 @synchronized (Values_) {
4392 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4393 [Values_ removeObjectForKey:key];
4395 [Values_ setObject:value forKey:key];
4397 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4400 - (id) getSessionValue:(NSString *)key {
4401 @synchronized (SessionData_) {
4402 return [SessionData_ objectForKey:key];
4405 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4406 @synchronized (SessionData_) {
4407 if (value == (id) [WebUndefined undefined])
4408 [SessionData_ removeObjectForKey:key];
4410 [SessionData_ setObject:value forKey:key];
4413 - (void) addBridgedHost:(NSString *)host {
4414 @synchronized (HostConfig_) {
4415 [BridgedHosts_ addObject:host];
4418 - (void) addInsecureHost:(NSString *)host {
4419 @synchronized (HostConfig_) {
4420 [InsecureHosts_ addObject:host];
4423 - (void) addTokenHost:(NSString *)host {
4424 @synchronized (HostConfig_) {
4425 [TokenHosts_ addObject:host];
4428 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4429 @synchronized (HostConfig_) {
4430 if (scheme != (id) [WebUndefined undefined])
4431 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4433 [PipelinedHosts_ addObject:host];
4436 - (void) popViewController:(NSNumber *)value {
4437 if (value == (id) [WebUndefined undefined])
4438 value = [NSNumber numberWithBool:YES];
4439 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4442 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4443 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4445 for (NSString *section in sections)
4446 [array addObject:section];
4448 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4451 distribution, @"Distribution",
4453 nil] waitUntilDone:NO];
4456 - (void) addTrivialSource:(NSString *)href {
4457 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4460 - (void) refreshSources {
4461 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4464 - (void) saveConfig {
4465 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4468 - (NSArray *) getAllSources {
4469 return [[Database sharedInstance] sources];
4472 - (NSArray *) getInstalledPackages {
4473 Database *database([Database sharedInstance]);
4474 @synchronized (database) {
4475 NSArray *packages([database packages]);
4476 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4477 for (Package *package in packages)
4478 if (![package uninstalled])
4479 [installed addObject:package];
4483 - (Package *) getPackageById:(NSString *)id {
4484 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4488 return (Package *) [NSNull null];
4491 - (NSString *) getLocaleIdentifier {
4492 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4495 - (NSArray *) getPreferredLanguages {
4499 - (NSArray *) statfs:(NSString *)path {
4502 if (path == nil || statfs([path UTF8String], &stat) == -1)
4505 return [NSArray arrayWithObjects:
4506 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4507 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4508 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4512 - (NSNumber *) du:(NSString *)path {
4513 NSNumber *value(nil);
4516 _assert(pipe(fds) != -1);
4518 pid_t pid(ExecFork());
4520 _assert(dup2(fds[1], 1) != -1);
4521 _assert(close(fds[0]) != -1);
4522 _assert(close(fds[1]) != -1);
4523 /* XXX: this should probably not use du */
4524 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4527 _assert(close(fds[1]) != -1);
4529 if (FILE *du = fdopen(fds[0], "r")) {
4531 while (fgets(line, sizeof(line), du) != NULL) {
4532 size_t length(strlen(line));
4533 while (length != 0 && line[length - 1] == '\n')
4534 line[--length] = '\0';
4535 if (char *tab = strchr(line, '\t')) {
4537 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4543 _assert(close(fds[0]) != -1);
4550 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4553 - (NSNumber *) isReachable:(NSString *)name {
4554 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4557 - (void) installPackages:(NSArray *)packages {
4558 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4561 - (NSString *) substitutePackageNames:(NSString *)message {
4562 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4563 for (size_t i(0), e([words count]); i != e; ++i) {
4564 NSString *word([words objectAtIndex:i]);
4565 if (Package *package = [[Database sharedInstance] packageWithName:word])
4566 [words replaceObjectAtIndex:i withObject:[package name]];
4569 return [words componentsJoinedByString:@" "];
4572 - (void) removeButton {
4573 [indirect_ removeButton];
4576 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4577 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4580 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4581 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4584 - (void) setBadgeValue:(id)value {
4585 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4588 - (void) setAllowsNavigationAction:(NSString *)value {
4589 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4592 - (void) setHidesBackButton:(NSString *)value {
4593 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4596 - (void) setHidesNavigationBar:(NSString *)value {
4597 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4600 - (void) setNavigationBarStyle:(NSString *)value {
4601 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4604 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4605 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4606 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4607 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4610 - (void) setPasteboardString:(NSString *)value {
4611 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4614 - (void) setPasteboardURL:(NSString *)value {
4615 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4618 - (void) _setToken:(NSString *)token {
4622 [Metadata_ removeObjectForKey:@"Token"];
4624 [Metadata_ setObject:Token_ forKey:@"Token"];
4629 - (void) setToken:(NSString *)token {
4630 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4633 - (void) scrollToBottom:(NSNumber *)animated {
4634 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4637 - (void) setViewportWidth:(float)width {
4638 [indirect_ setViewportWidthOnMainThread:width];
4641 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4642 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4643 unsigned count([arguments count]);
4645 for (unsigned i(0); i != count; ++i)
4646 values[i] = [arguments objectAtIndex:i];
4647 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4650 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4651 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4653 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4655 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4661 @interface NSURL (CydiaSecure)
4664 @implementation NSURL (CydiaSecure)
4666 - (bool) isCydiaSecure {
4667 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4670 @synchronized (HostConfig_) {
4671 if ([InsecureHosts_ containsObject:[self host]])
4680 /* Cydia Browser Controller {{{ */
4681 @implementation CydiaWebViewController
4683 - (NSURL *) navigationURL {
4684 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4687 + (void) _initialize {
4688 [super _initialize];
4690 Diversions_ = [NSMutableSet setWithCapacity:0];
4693 + (void) addDiversion:(Diversion *)diversion {
4694 [Diversions_ addObject:diversion];
4697 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4698 [super webView:view didClearWindowObject:window forFrame:frame];
4699 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4702 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4703 WebDataSource *source([frame dataSource]);
4704 NSURLResponse *response([source response]);
4705 NSURL *url([response URL]);
4706 NSString *scheme([[url scheme] lowercaseString]);
4708 bool bridged(false);
4710 @synchronized (HostConfig_) {
4711 if ([scheme isEqualToString:@"file"])
4713 else if ([scheme isEqualToString:@"https"])
4714 if ([BridgedHosts_ containsObject:[url host]])
4719 [window setValue:cydia forKey:@"cydia"];
4722 - (void) _setupMail:(MFMailComposeViewController *)controller {
4723 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4725 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4726 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4729 - (NSURL *) URLWithURL:(NSURL *)url {
4730 return [Diversion divertURL:url];
4733 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4734 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4737 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4738 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4740 NSURL *url([copy URL]);
4741 NSString *href([url absoluteString]);
4742 NSString *host([url host]);
4744 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4745 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4746 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4747 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4750 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4751 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4753 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4757 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4758 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4759 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4760 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4765 @synchronized (HostConfig_) {
4766 bridged = [BridgedHosts_ containsObject:host];
4767 token = [TokenHosts_ containsObject:host];
4770 if ([url isCydiaSecure]) {
4772 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4773 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4775 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4776 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4783 - (void) setDelegate:(id)delegate {
4784 [super setDelegate:delegate];
4785 [cydia_ setDelegate:delegate];
4788 - (NSString *) applicationNameForUserAgent {
4793 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4794 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4800 @interface AppCacheController : CydiaWebViewController {
4805 @implementation AppCacheController
4807 - (void) didReceiveMemoryWarning {
4808 // XXX: this doesn't work
4811 - (bool) retainsNetworkActivityIndicator {
4819 @interface NSObject (CydiaScript)
4820 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4823 @implementation NSObject (CydiaScript)
4825 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4831 @implementation NSArray (CydiaScript)
4833 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4834 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4835 for (size_t i(0), e([self count]); i != e; ++i)
4836 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4842 @implementation NSDictionary (CydiaScript)
4844 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4845 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4847 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4854 /* Confirmation Controller {{{ */
4855 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4856 if (!iterator.end())
4857 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4858 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4860 pkgCache::PkgIterator package(dep.TargetPkg());
4863 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4870 @protocol ConfirmationControllerDelegate
4871 - (void) cancelAndClear:(bool)clear;
4872 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4876 @interface ConfirmationController : CydiaWebViewController {
4877 _transient Database *database_;
4879 _H<UIAlertView> essential_;
4881 _H<NSDictionary> changes_;
4882 _H<NSMutableArray> issues_;
4883 _H<NSDictionary> sizes_;
4888 - (id) initWithDatabase:(Database *)database;
4892 @implementation ConfirmationController
4896 RestartSubstrate_ = true;
4897 [delegate_ confirmWithNavigationController:[self navigationController]];
4900 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4901 NSString *context([alert context]);
4903 if ([context isEqualToString:@"remove"]) {
4904 if (button == [alert cancelButtonIndex])
4905 [self dismissModalViewControllerAnimated:YES];
4906 else if (button == [alert firstOtherButtonIndex]) {
4907 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
4910 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4911 } else if ([context isEqualToString:@"unable"]) {
4912 [self dismissModalViewControllerAnimated:YES];
4913 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4915 [super alertView:alert clickedButtonAtIndex:button];
4919 - (void) _doContinue {
4920 [delegate_ cancelAndClear:NO];
4921 [self dismissModalViewControllerAnimated:YES];
4924 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4925 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4929 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4930 [super webView:view didClearWindowObject:window forFrame:frame];
4932 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4933 (id) changes_, @"changes",
4934 (id) issues_, @"issues",
4935 (id) sizes_, @"sizes",
4937 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4940 - (id) initWithDatabase:(Database *)database {
4941 if ((self = [super init]) != nil) {
4942 database_ = database;
4944 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4945 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4946 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4947 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4948 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4952 pkgCacheFile &cache([database_ cache]);
4953 NSArray *packages([database_ packages]);
4954 pkgDepCache::Policy *policy([database_ policy]);
4956 issues_ = [NSMutableArray arrayWithCapacity:4];
4958 for (Package *package in packages) {
4959 pkgCache::PkgIterator iterator([package iterator]);
4960 NSString *name([package id]);
4962 if ([package broken]) {
4963 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4965 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4967 reasons, @"reasons",
4970 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4974 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4975 pkgCache::DepIterator start;
4976 pkgCache::DepIterator end;
4977 dep.GlobOr(start, end); // ++dep
4979 if (!cache->IsImportantDep(end))
4981 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4984 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4986 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4987 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4988 clauses, @"clauses",
4992 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4994 pkgCache::PkgIterator target(start.TargetPkg());
4995 if (target->ProvidesList != 0)
4996 reason = @"missing";
4998 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5000 reason = @"installed";
5001 installed = [NSString stringWithUTF8String:ver.VerStr()];
5002 } else if (!cache[target].CandidateVerIter(cache).end())
5003 reason = @"uninstalled";
5004 else if (target->ProvidesList == 0)
5005 reason = @"uninstallable";
5007 reason = @"virtual";
5010 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5011 [NSString stringWithUTF8String:start.CompType()], @"operator",
5012 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5015 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5016 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5017 version, @"version",
5019 installed, @"installed",
5022 // yes, seriously. (wtf?)
5030 pkgDepCache::StateCache &state(cache[iterator]);
5032 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
5034 if (state.NewInstall())
5035 [installs addObject:name];
5036 // XXX: else if (state.Install())
5037 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5038 [reinstalls addObject:name];
5039 // XXX: move before previous if
5040 else if (state.Upgrade())
5041 [upgrades addObject:name];
5042 else if (state.Downgrade())
5043 [downgrades addObject:name];
5044 else if (!state.Delete())
5045 // XXX: _assert(state.Keep());
5047 else if (special_r(name))
5048 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5049 [NSNull null], @"package",
5050 [NSArray arrayWithObjects:
5051 [NSDictionary dictionaryWithObjectsAndKeys:
5052 @"Conflicts", @"relationship",
5053 [NSArray arrayWithObjects:
5054 [NSDictionary dictionaryWithObjectsAndKeys:
5056 [NSNull null], @"version",
5057 @"installed", @"reason",
5064 if ([package essential])
5066 [removes addObject:name];
5069 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5070 substrate_ |= DepSubstrate(iterator.CurrentVer());
5075 else if (Advanced_) {
5076 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5078 essential_ = [[[UIAlertView alloc]
5079 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5080 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5082 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5084 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5088 [essential_ setContext:@"remove"];
5089 [essential_ setNumberOfRows:2];
5091 essential_ = [[[UIAlertView alloc]
5092 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5093 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5095 cancelButtonTitle:UCLocalize("OKAY")
5096 otherButtonTitles:nil
5099 [essential_ setContext:@"unable"];
5102 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5103 installs, @"installs",
5104 reinstalls, @"reinstalls",
5105 upgrades, @"upgrades",
5106 downgrades, @"downgrades",
5107 removes, @"removes",
5110 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5111 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5112 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5115 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5119 - (UIBarButtonItem *) leftButton {
5120 return [[[UIBarButtonItem alloc]
5121 initWithTitle:UCLocalize("CANCEL")
5122 style:UIBarButtonItemStylePlain
5124 action:@selector(cancelButtonClicked)
5129 - (void) applyRightButton {
5130 if ([issues_ count] == 0 && ![self isLoading])
5131 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5132 initWithTitle:UCLocalize("CONFIRM")
5133 style:UIBarButtonItemStyleDone
5135 action:@selector(confirmButtonClicked)
5138 [[self navigationItem] setRightBarButtonItem:nil];
5142 - (void) cancelButtonClicked {
5143 [delegate_ cancelAndClear:YES];
5144 [self dismissModalViewControllerAnimated:YES];
5148 - (void) confirmButtonClicked {
5149 if (essential_ != nil)
5159 /* Progress Data {{{ */
5160 @interface CydiaProgressData : NSObject {
5161 _transient id delegate_;
5170 _H<NSMutableArray> events_;
5171 _H<NSString> title_;
5173 _H<NSString> status_;
5174 _H<NSString> finish_;
5179 @implementation CydiaProgressData
5181 + (NSArray *) _attributeKeys {
5182 return [NSArray arrayWithObjects:
5194 - (NSArray *) attributeKeys {
5195 return [[self class] _attributeKeys];
5198 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5199 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5203 if ((self = [super init]) != nil) {
5204 events_ = [NSMutableArray arrayWithCapacity:32];
5212 - (void) setDelegate:(id)delegate {
5213 delegate_ = delegate;
5216 - (void) setPercent:(float)value {
5220 - (NSNumber *) percent {
5221 return [NSNumber numberWithFloat:percent_];
5224 - (void) setCurrent:(float)value {
5228 - (NSNumber *) current {
5229 return [NSNumber numberWithFloat:current_];
5232 - (void) setTotal:(float)value {
5236 - (NSNumber *) total {
5237 return [NSNumber numberWithFloat:total_];
5240 - (void) setSpeed:(float)value {
5244 - (NSNumber *) speed {
5245 return [NSNumber numberWithFloat:speed_];
5248 - (NSArray *) events {
5252 - (void) removeAllEvents {
5253 [events_ removeAllObjects];
5256 - (void) addEvent:(CydiaProgressEvent *)event {
5257 [events_ addObject:event];
5260 - (void) setTitle:(NSString *)text {
5264 - (NSString *) title {
5268 - (void) setFinish:(NSString *)text {
5272 - (NSString *) finish {
5273 return (id) finish_ ?: [NSNull null];
5276 - (void) setRunning:(bool)running {
5280 - (NSNumber *) running {
5281 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5286 /* Progress Controller {{{ */
5287 @interface ProgressController : CydiaWebViewController <
5290 _transient Database *database_;
5291 _H<CydiaProgressData, 1> progress_;
5295 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5297 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5299 - (void) setTitle:(NSString *)title;
5300 - (void) setCancellable:(bool)cancellable;
5304 @implementation ProgressController
5307 [database_ setProgressDelegate:nil];
5311 - (UIBarButtonItem *) leftButton {
5312 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5313 initWithTitle:UCLocalize("CANCEL")
5314 style:UIBarButtonItemStylePlain
5316 action:@selector(cancel)
5317 ] autorelease] : nil;
5320 - (void) updateCancel {
5321 [super applyLeftButton];
5324 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5325 if ((self = [super init]) != nil) {
5326 database_ = database;
5327 delegate_ = delegate;
5329 [database_ setProgressDelegate:self];
5331 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5332 [progress_ setDelegate:self];
5334 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5336 [scroller_ setBackgroundColor:[UIColor blackColor]];
5338 [[self navigationItem] setHidesBackButton:YES];
5340 [self updateCancel];
5344 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5345 [super webView:view didClearWindowObject:window forFrame:frame];
5346 [window setValue:progress_ forKey:@"cydiaProgress"];
5349 - (void) updateProgress {
5350 [self dispatchEvent:@"CydiaProgressUpdate"];
5353 - (void) viewWillAppear:(BOOL)animated {
5354 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5355 [super viewWillAppear:animated];
5358 - (void) reloadSpringBoard {
5359 if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
5360 system("/bin/launchctl stop com.apple.backboardd");
5362 system("/usr/bin/killall backboardd SpringBoard sbreload");
5366 pid_t pid(ExecFork());
5371 pid_t pid(ExecFork());
5373 execl("/usr/bin/sbreload", "sbreload", NULL);
5383 system("/usr/bin/killall backboardd SpringBoard sbreload");
5387 UpdateExternalStatus(0);
5390 [delegate_ saveState];
5394 [delegate_ returnToCydia];
5398 [delegate_ terminateWithSuccess];
5399 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5400 [delegate_ suspendWithAnimation:YES];
5402 [delegate_ suspend];*/
5414 UIProgressHUD *hud([delegate_ addProgressHUD]);
5415 [hud setText:UCLocalize("LOADING")];
5416 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5422 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5423 SBReboot(SBSSpringBoardServerPort());
5425 reboot2(RB_AUTOBOOT);
5432 - (void) setTitle:(NSString *)title {
5433 [progress_ setTitle:title];
5434 [self updateProgress];
5437 - (UIBarButtonItem *) rightButton {
5438 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5439 initWithTitle:UCLocalize("CLOSE")
5440 style:UIBarButtonItemStylePlain
5442 action:@selector(close)
5446 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5447 UpdateExternalStatus(1);
5449 [progress_ setRunning:true];
5450 [self setTitle:title];
5451 // implicit updateProgress
5453 SHA1SumValue notifyconf; {
5455 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5458 MMap mmap(file, MMap::ReadOnly);
5460 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5461 notifyconf = sha1.Result();
5465 SHA1SumValue springlist; {
5467 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5470 MMap mmap(file, MMap::ReadOnly);
5472 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5473 springlist = sha1.Result();
5477 if (invocation != nil) {
5478 [invocation yieldToSelector:@selector(invoke)];
5479 [self setTitle:@"COMPLETE"];
5484 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5487 MMap mmap(file, MMap::ReadOnly);
5489 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5490 if (!(notifyconf == sha1.Result()))
5497 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5500 MMap mmap(file, MMap::ReadOnly);
5502 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5503 if (!(springlist == sha1.Result()))
5509 if (RestartSubstrate_)
5513 RestartSubstrate_ = false;
5516 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5517 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5518 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5519 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5520 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5523 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5525 [progress_ setRunning:false];
5526 [self updateProgress];
5528 [self applyRightButton];
5531 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5532 [progress_ addEvent:event];
5533 [self updateProgress];
5536 - (bool) isProgressCancelled {
5537 return cancel_ == 2;
5542 [self updateCancel];
5545 - (void) setCancellable:(bool)cancellable {
5546 unsigned cancel(cancel_);
5550 else if (cancel_ == 0)
5553 if (cancel != cancel_)
5554 [self updateCancel];
5557 - (void) setProgressCancellable:(NSNumber *)cancellable {
5558 [self setCancellable:[cancellable boolValue]];
5561 - (void) setProgressPercent:(NSNumber *)percent {
5562 [progress_ setPercent:[percent floatValue]];
5563 [self updateProgress];
5566 - (void) setProgressStatus:(NSDictionary *)status {
5567 if (status == nil) {
5568 [progress_ setCurrent:0];
5569 [progress_ setTotal:0];
5570 [progress_ setSpeed:0];
5572 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5574 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5575 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5576 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5579 [self updateProgress];
5585 /* Package Cell {{{ */
5586 @interface PackageCell : CyteTableViewCell <
5587 CyteTableViewCellDelegate
5591 _H<NSString> description_;
5593 _H<NSString> source_;
5595 _H<UIImage> placard_;
5599 - (PackageCell *) init;
5600 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5602 - (void) drawContentRect:(CGRect)rect;
5606 @implementation PackageCell
5608 - (PackageCell *) init {
5609 CGRect frame(CGRectMake(0, 0, 320, 74));
5610 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5611 UIView *content([self contentView]);
5612 CGRect bounds([content bounds]);
5614 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5615 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5616 [content addSubview:content_];
5618 [content_ setDelegate:self];
5619 [content_ setOpaque:YES];
5623 - (NSString *) accessibilityLabel {
5627 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5628 summarized_ = summary;
5638 [content_ setBackgroundColor:[UIColor whiteColor]];
5642 Source *source = [package source];
5644 icon_ = [package icon];
5646 if (NSString *name = [package name])
5647 name_ = [NSString stringWithString:name];
5649 if (NSString *description = [package shortDescription])
5650 description_ = [NSString stringWithString:description];
5652 commercial_ = [package isCommercial];
5654 NSString *label = nil;
5655 bool trusted = false;
5657 if (source != nil) {
5658 label = [source label];
5659 trusted = [source trusted];
5660 } else if ([[package id] isEqualToString:@"firmware"])
5661 label = UCLocalize("APPLE");
5663 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5665 NSString *from(label);
5667 NSString *section = [package simpleSection];
5668 if (section != nil && ![section isEqualToString:label]) {
5669 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5670 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5673 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5675 if (NSString *purpose = [package primaryPurpose])
5676 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5681 if (NSString *mode = [package mode]) {
5682 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5683 color = RemovingColor_;
5684 placard = @"removing";
5686 color = InstallingColor_;
5687 placard = @"installing";
5690 color = [UIColor whiteColor];
5692 if ([package installed] != nil)
5693 placard = @"installed";
5698 [content_ setBackgroundColor:color];
5701 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5704 [self setNeedsDisplay];
5705 [content_ setNeedsDisplay];
5708 - (void) drawSummaryContentRect:(CGRect)rect {
5709 bool highlighted(highlighted_);
5710 float width([self bounds].size.width);
5714 rect.size = [(UIImage *) icon_ size];
5716 while (rect.size.width > 16 || rect.size.height > 16) {
5717 rect.size.width /= 2;
5718 rect.size.height /= 2;
5721 rect.origin.x = 19 - rect.size.width / 2;
5722 rect.origin.y = 19 - rect.size.height / 2;
5724 [icon_ drawInRect:rect];
5727 if (badge_ != nil) {
5729 rect.size = [(UIImage *) badge_ size];
5731 rect.size.width /= 4;
5732 rect.size.height /= 4;
5734 rect.origin.x = 25 - rect.size.width / 2;
5735 rect.origin.y = 25 - rect.size.height / 2;
5737 [badge_ drawInRect:rect];
5740 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5744 UISetColor(commercial_ ? Purple_ : Black_);
5745 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5747 if (placard_ != nil)
5748 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5751 - (void) drawNormalContentRect:(CGRect)rect {
5752 bool highlighted(highlighted_);
5753 float width([self bounds].size.width);
5757 rect.size = [(UIImage *) icon_ size];
5759 while (rect.size.width > 32 || rect.size.height > 32) {
5760 rect.size.width /= 2;
5761 rect.size.height /= 2;
5764 rect.origin.x = 25 - rect.size.width / 2;
5765 rect.origin.y = 25 - rect.size.height / 2;
5767 [icon_ drawInRect:rect];
5770 if (badge_ != nil) {
5772 rect.size = [(UIImage *) badge_ size];
5774 rect.size.width /= 2;
5775 rect.size.height /= 2;
5777 rect.origin.x = 36 - rect.size.width / 2;
5778 rect.origin.y = 36 - rect.size.height / 2;
5780 [badge_ drawInRect:rect];
5783 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5787 UISetColor(commercial_ ? Purple_ : Black_);
5788 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5789 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5792 UISetColor(commercial_ ? Purplish_ : Gray_);
5793 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5795 if (placard_ != nil)
5796 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5799 - (void) drawContentRect:(CGRect)rect {
5801 [self drawSummaryContentRect:rect];
5803 [self drawNormalContentRect:rect];
5808 /* Section Cell {{{ */
5809 @interface SectionCell : CyteTableViewCell <
5810 CyteTableViewCellDelegate
5812 _H<NSString> basic_;
5813 _H<NSString> section_;
5815 _H<NSString> count_;
5817 _H<UISwitch> switch_;
5821 - (void) setSection:(Section *)section editing:(BOOL)editing;
5825 @implementation SectionCell
5827 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5828 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5829 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5830 // XXX: this initial frame is wrong, but is fixed later
5831 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5832 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5834 UIView *content([self contentView]);
5835 CGRect bounds([content bounds]);
5837 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5838 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5839 [content addSubview:content_];
5840 [content_ setBackgroundColor:[UIColor whiteColor]];
5842 [content_ setDelegate:self];
5846 - (void) onSwitch:(id)sender {
5847 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5848 if (metadata == nil) {
5849 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5850 [Sections_ setObject:metadata forKey:basic_];
5853 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5857 - (void) setSection:(Section *)section editing:(BOOL)editing {
5858 if (editing != editing_) {
5860 [switch_ removeFromSuperview];
5862 [self addSubview:switch_];
5871 if (section == nil) {
5872 name_ = UCLocalize("ALL_PACKAGES");
5875 basic_ = [section name];
5876 section_ = [section localized];
5878 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5879 count_ = [NSString stringWithFormat:@"%d", [section count]];
5882 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5885 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5886 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5888 [content_ setNeedsDisplay];
5891 - (void) setFrame:(CGRect)frame {
5892 [super setFrame:frame];
5894 CGRect rect([switch_ frame]);
5895 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
5898 - (NSString *) accessibilityLabel {
5902 - (void) drawContentRect:(CGRect)rect {
5903 bool highlighted(highlighted_ && !editing_);
5905 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
5907 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5910 float width(rect.size.width);
5912 width -= 9 + [switch_ frame].size.width;
5916 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:UILineBreakModeTailTruncation];
5918 CGSize size = [count_ sizeWithFont:Font14_];
5920 UISetColor(Folder_);
5922 [count_ drawAtPoint:CGPointMake(10 + (30 - size.width) / 2, 18) withFont:Font12Bold_];
5928 /* File Table {{{ */
5929 @interface FileTable : CyteViewController <
5930 UITableViewDataSource,
5933 _transient Database *database_;
5934 _H<Package> package_;
5936 _H<NSMutableArray> files_;
5937 _H<UITableView, 2> list_;
5940 - (id) initWithDatabase:(Database *)database;
5941 - (void) setPackage:(Package *)package;
5945 @implementation FileTable
5947 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5948 return files_ == nil ? 0 : [files_ count];
5951 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5955 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5956 static NSString *reuseIdentifier = @"Cell";
5958 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5960 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5961 [cell setFont:[UIFont systemFontOfSize:16]];
5963 [cell setText:[files_ objectAtIndex:indexPath.row]];
5964 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5969 - (NSURL *) navigationURL {
5970 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5974 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5975 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5976 [list_ setRowHeight:24.0f];
5977 [(UITableView *) list_ setDataSource:self];
5978 [list_ setDelegate:self];
5979 [self setView:list_];
5982 - (void) viewDidLoad {
5983 [super viewDidLoad];
5985 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5988 - (void) releaseSubviews {
5994 [super releaseSubviews];
5997 - (id) initWithDatabase:(Database *)database {
5998 if ((self = [super init]) != nil) {
5999 database_ = database;
6003 - (void) setPackage:(Package *)package {
6007 files_ = [NSMutableArray arrayWithCapacity:32];
6009 if (package != nil) {
6011 name_ = [package id];
6013 if (NSArray *files = [package files])
6014 [files_ addObjectsFromArray:files];
6016 if ([files_ count] != 0) {
6017 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6018 [files_ removeObjectAtIndex:0];
6019 [files_ sortUsingSelector:@selector(compareByPath:)];
6021 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6022 [stack addObject:@"/"];
6024 for (int i(0), e([files_ count]); i != e; ++i) {
6025 NSString *file = [files_ objectAtIndex:i];
6026 while (![file hasPrefix:[stack lastObject]])
6027 [stack removeLastObject];
6028 NSString *directory = [stack lastObject];
6029 [stack addObject:[file stringByAppendingString:@"/"]];
6030 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6031 ([stack count] - 2) * 3, "",
6032 [file substringFromIndex:[directory length]]
6041 - (void) reloadData {
6044 [self setPackage:[database_ packageWithName:name_]];
6049 /* Package Controller {{{ */
6050 @interface CYPackageController : CydiaWebViewController <
6051 UIActionSheetDelegate
6053 _transient Database *database_;
6054 _H<Package> package_;
6057 _H<NSMutableArray> buttons_;
6058 _H<UIBarButtonItem> button_;
6061 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6065 @implementation CYPackageController
6067 - (NSURL *) navigationURL {
6068 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6071 /* XXX: this is not safe at all... localization of /fail/ */
6072 - (void) _clickButtonWithName:(NSString *)name {
6073 if ([name isEqualToString:UCLocalize("CLEAR")])
6074 [delegate_ clearPackage:package_];
6075 else if ([name isEqualToString:UCLocalize("INSTALL")])
6076 [delegate_ installPackage:package_];
6077 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6078 [delegate_ installPackage:package_];
6079 else if ([name isEqualToString:UCLocalize("REMOVE")])
6080 [delegate_ removePackage:package_];
6081 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6082 [delegate_ installPackage:package_];
6083 else _assert(false);
6086 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6087 NSString *context([sheet context]);
6089 if ([context isEqualToString:@"modify"]) {
6090 if (button != [sheet cancelButtonIndex]) {
6091 NSString *buttonName = [buttons_ objectAtIndex:button];
6092 [self _clickButtonWithName:buttonName];
6095 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6099 - (bool) _allowJavaScriptPanel {
6104 - (void) _customButtonClicked {
6105 int count([buttons_ count]);
6110 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6112 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6113 [buttons addObjectsFromArray:buttons_];
6115 UIActionSheet *sheet = [[[UIActionSheet alloc]
6118 cancelButtonTitle:nil
6119 destructiveButtonTitle:nil
6120 otherButtonTitles:nil
6123 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6125 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6126 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6128 [sheet setContext:@"modify"];
6130 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6134 - (void) reloadButtonClicked {
6135 if (commercial_ && function_ == nil && [package_ uninstalled])
6137 [self customButtonClicked];
6140 - (void) applyLoadingTitle {
6141 // Don't show "Loading" as the title. Ever.
6144 - (UIBarButtonItem *) rightButton {
6149 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6150 if ((self = [super init]) != nil) {
6151 database_ = database;
6152 buttons_ = [NSMutableArray arrayWithCapacity:4];
6153 name_ = name == nil ? @"" : [NSString stringWithString:name];
6154 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6158 - (void) reloadData {
6161 package_ = [database_ packageWithName:name_];
6163 [buttons_ removeAllObjects];
6165 if (package_ != nil) {
6166 [(Package *) package_ parse];
6168 commercial_ = [package_ isCommercial];
6170 if ([package_ mode] != nil)
6171 [buttons_ addObject:UCLocalize("CLEAR")];
6172 if ([package_ source] == nil);
6173 else if ([package_ upgradableAndEssential:NO])
6174 [buttons_ addObject:UCLocalize("UPGRADE")];
6175 else if ([package_ uninstalled])
6176 [buttons_ addObject:UCLocalize("INSTALL")];
6178 [buttons_ addObject:UCLocalize("REINSTALL")];
6179 if (![package_ uninstalled])
6180 [buttons_ addObject:UCLocalize("REMOVE")];
6184 switch ([buttons_ count]) {
6185 case 0: title = nil; break;
6186 case 1: title = [buttons_ objectAtIndex:0]; break;
6187 default: title = UCLocalize("MODIFY"); break;
6190 button_ = [[[UIBarButtonItem alloc]
6192 style:UIBarButtonItemStylePlain
6194 action:@selector(customButtonClicked)
6198 - (bool) isLoading {
6199 return commercial_ ? [super isLoading] : false;
6205 /* Package List Controller {{{ */
6206 @interface PackageListController : CyteViewController <
6207 UITableViewDataSource,
6210 _transient Database *database_;
6212 _H<NSArray> packages_;
6213 _H<NSMutableArray> sections_;
6214 _H<UITableView, 2> list_;
6215 _H<NSMutableArray> index_;
6216 _H<NSMutableDictionary> indices_;
6217 _H<NSString> title_;
6218 unsigned reloading_;
6221 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6222 - (void) setDelegate:(id)delegate;
6223 - (void) resetCursor;
6228 @implementation PackageListController
6230 - (NSURL *) referrerURL {
6231 return [self navigationURL];
6234 - (bool) isSummarized {
6238 - (bool) showsSections {
6242 - (void) deselectWithAnimation:(BOOL)animated {
6243 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6246 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6247 CGRect base = [[self view] bounds];
6248 base.size.height -= bounds.size.height;
6249 base.origin = [list_ frame].origin;
6251 [UIView beginAnimations:nil context:NULL];
6252 [UIView setAnimationBeginsFromCurrentState:YES];
6253 [UIView setAnimationCurve:curve];
6254 [UIView setAnimationDuration:duration];
6255 [list_ setFrame:base];
6256 [UIView commitAnimations];
6259 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6260 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6263 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6264 [self resizeForKeyboardBounds:bounds duration:0];
6267 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6268 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6269 *curve = UIViewAnimationCurveEaseInOut;
6271 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6273 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6276 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6279 - (void) keyboardWillShow:(NSNotification *)notification {
6282 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6283 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6285 NSTimeInterval duration;
6286 UIViewAnimationCurve curve;
6287 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6289 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);
6290 UIViewController *base = self;
6291 while ([base parentOrPresentingViewController] != nil)
6292 base = [base parentOrPresentingViewController];
6293 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6294 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6296 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6297 intersection.size.height += CYStatusBarHeight();
6299 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6302 - (void) keyboardWillHide:(NSNotification *)notification {
6303 NSTimeInterval duration;
6304 UIViewAnimationCurve curve;
6305 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6307 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6310 - (void) viewWillAppear:(BOOL)animated {
6311 [super viewWillAppear:animated];
6313 [self resizeForKeyboardBounds:CGRectZero];
6314 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6315 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6318 - (void) viewWillDisappear:(BOOL)animated {
6319 [super viewWillDisappear:animated];
6321 [self resizeForKeyboardBounds:CGRectZero];
6322 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6323 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6326 - (void) viewDidAppear:(BOOL)animated {
6327 [super viewDidAppear:animated];
6328 [self deselectWithAnimation:animated];
6331 - (void) didSelectPackage:(Package *)package {
6332 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6333 [view setDelegate:delegate_];
6334 [[self navigationController] pushViewController:view animated:YES];
6337 #if TryIndexedCollation
6338 + (BOOL) hasIndexedCollation {
6339 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6343 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6344 NSInteger count([sections_ count]);
6345 return count == 0 ? 1 : count;
6348 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6349 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6351 return [[sections_ objectAtIndex:section] name];
6354 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6355 if ([sections_ count] == 0)
6357 return [[sections_ objectAtIndex:section] count];
6360 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6361 @synchronized (database_) {
6362 if ([database_ era] != era_)
6365 Section *section([sections_ objectAtIndex:[path section]]);
6366 NSInteger row([path row]);
6367 Package *package([packages_ objectAtIndex:([section row] + row)]);
6368 return [[package retain] autorelease];
6371 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6372 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6374 cell = [[[PackageCell alloc] init] autorelease];
6376 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6377 [cell setPackage:package asSummary:[self isSummarized]];
6381 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6382 Package *package([self packageAtIndexPath:path]);
6383 package = [database_ packageWithName:[package id]];
6384 [self didSelectPackage:package];
6387 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6388 if (![self showsSections])
6394 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6395 #if TryIndexedCollation
6396 if ([[self class] hasIndexedCollation]) {
6397 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6404 - (void) updateHeight {
6405 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6408 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6409 if ((self = [super init]) != nil) {
6410 database_ = database;
6411 title_ = [title copy];
6412 [[self navigationItem] setTitle:title_];
6417 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6418 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6419 [self setView:view];
6421 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6422 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6423 [view addSubview:list_];
6425 // XXX: is 20 the most optimal number here?
6426 [list_ setSectionIndexMinimumDisplayRowCount:20];
6428 [(UITableView *) list_ setDataSource:self];
6429 [list_ setDelegate:self];
6431 [self updateHeight];
6434 - (void) releaseSubviews {
6442 [super releaseSubviews];
6445 - (void) setDelegate:(id)delegate {
6446 delegate_ = delegate;
6449 - (bool) shouldYield {
6453 - (bool) shouldBlock {
6457 - (NSMutableArray *) _reloadPackages {
6458 @synchronized (database_) {
6459 era_ = [database_ era];
6460 NSArray *packages([database_ packages]);
6462 return [NSMutableArray arrayWithArray:packages];
6465 - (void) _reloadData {
6466 if (reloading_ != 0) {
6474 if ([self shouldYield]) {
6478 if (![self shouldBlock])
6481 hud = [delegate_ addProgressHUD];
6482 [hud setText:UCLocalize("LOADING")];
6486 packages = [self yieldToSelector:@selector(_reloadPackages)];
6489 [delegate_ removeProgressHUD:hud];
6490 } while (reloading_ == 2);
6492 packages = [self _reloadPackages];
6495 @synchronized (database_) {
6496 if (era_ != [database_ era])
6500 packages_ = packages;
6502 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6503 sections_ = [NSMutableArray arrayWithCapacity:16];
6505 Section *section = nil;
6507 #if TryIndexedCollation
6508 if ([[self class] hasIndexedCollation]) {
6509 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6511 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6512 NSArray *titles = [collation sectionIndexTitles];
6515 _profile(PackageTable$reloadData$Section)
6516 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6520 _profile(PackageTable$reloadData$Section$Package)
6521 package = [packages_ objectAtIndex:offset];
6522 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6525 while (secidx < index) {
6528 _profile(PackageTable$reloadData$Section$Allocate)
6529 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6532 _profile(PackageTable$reloadData$Section$Add)
6533 [sections_ addObject:section];
6537 [section addToCount];
6543 index_ = [NSMutableArray arrayWithCapacity:32];
6545 bool sectioned([self showsSections]);
6547 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6548 [sections_ addObject:section];
6551 _profile(PackageTable$reloadData$Section)
6552 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6556 _profile(PackageTable$reloadData$Section$Package)
6557 package = [packages_ objectAtIndex:offset];
6558 index = [package index];
6561 if (sectioned && (section == nil || [section index] != index)) {
6562 _profile(PackageTable$reloadData$Section$Allocate)
6563 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6566 [index_ addObject:[section name]];
6567 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6569 _profile(PackageTable$reloadData$Section$Add)
6570 [sections_ addObject:section];
6574 [section addToCount];
6579 [self updateHeight];
6581 _profile(PackageTable$reloadData$List)
6582 [(UITableView *) list_ setDataSource:self];
6587 - (void) reloadData {
6590 if ([self shouldYield])
6591 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6596 - (void) resetCursor {
6597 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6600 - (void) clearData {
6601 [self updateHeight];
6603 [list_ setDataSource:nil];
6611 /* Filtered Package List Controller {{{ */
6612 @interface FilteredPackageListController : PackageListController {
6615 _H<NSObject> object_;
6616 _H<NSObject> stuff_;
6619 - (void) setObject:(id)object;
6620 - (void) setStuff:(id)object;
6621 - (void) setObject:(id)object andStuff:(id)stuff;
6623 - (void) setObject:(id)object forFilter:(SEL)filter;
6624 - (void) setObject:(id)object andStuff:(id)stuff forFilter:(SEL)filter;
6627 - (void) setFilter:(SEL)filter;
6629 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6633 @implementation FilteredPackageListController
6639 - (void) setFilter:(SEL)filter {
6640 @synchronized (self) {
6643 /* XXX: this is an unsafe optimization of doomy hell */
6644 Method method(class_getInstanceMethod([Package class], filter));
6645 _assert(method != NULL);
6646 imp_ = method_getImplementation(method);
6647 _assert(imp_ != NULL);
6650 - (void) setObject:(id)object {
6651 @synchronized (self) {
6655 - (void) setStuff:(id)stuff {
6656 @synchronized (self) {
6660 - (void) setObject:(id)object andStuff:(id)stuff {
6661 @synchronized (self) {
6666 - (void) setObject:(id)object forFilter:(SEL)filter {
6667 @synchronized (self) {
6668 [self setFilter:filter];
6672 - (void) setObject:(id)object andStuff:(id)stuff forFilter:(SEL)filter {
6673 @synchronized (self) {
6674 [self setFilter:filter];
6679 - (NSMutableArray *) _reloadPackages {
6680 @synchronized (database_) {
6681 era_ = [database_ era];
6682 NSArray *packages([database_ packages]);
6684 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6688 _H<NSObject> object;
6691 @synchronized (self) {
6698 _profile(PackageTable$reloadData$Filter)
6699 for (Package *package in packages)
6700 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id, id)>(imp))(package, filter, object, stuff))
6701 [filtered addObject:package];
6707 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6708 if ((self = [super initWithDatabase:database title:title]) != nil) {
6709 [self setFilter:filter];
6714 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object with:(id)stuff {
6715 if ((self = [super initWithDatabase:database title:title]) != nil) {
6716 [self setFilter:filter];
6725 /* Home Controller {{{ */
6726 @interface HomeController : CydiaWebViewController {
6727 CFRunLoopRef runloop_;
6728 SCNetworkReachabilityRef reachability_;
6733 @implementation HomeController
6735 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6736 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6740 if ((self = [super init]) != nil) {
6741 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6744 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6745 if (reachability_ != NULL) {
6746 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6747 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6749 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6750 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6757 if (reachability_ != NULL && runloop_ != NULL)
6758 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6762 - (NSURL *) navigationURL {
6763 return [NSURL URLWithString:@"cydia://home"];
6766 - (void) aboutButtonClicked {
6767 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6769 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6770 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6771 [alert setCancelButtonIndex:0];
6774 @"Copyright \u00a9 2008-2013\n"
6777 "Jay Freeman (saurik)\n"
6778 "saurik@saurik.com\n"
6779 "http://www.saurik.com/"
6785 - (UIBarButtonItem *) leftButton {
6786 return [[[UIBarButtonItem alloc]
6787 initWithTitle:UCLocalize("ABOUT")
6788 style:UIBarButtonItemStylePlain
6790 action:@selector(aboutButtonClicked)
6797 /* Cydia Navigation Controller Interface {{{ */
6798 @interface UINavigationController (Cydia)
6800 - (NSArray *) navigationURLCollection;
6801 - (void) unloadData;
6806 /* Cydia Tab Bar Controller {{{ */
6807 @interface CydiaTabBarController : CyteTabBarController <
6808 UITabBarControllerDelegate,
6811 _transient Database *database_;
6813 _H<UIActivityIndicatorView> indicator_;
6816 // XXX: ok, "updatedelegate_"?...
6817 _transient NSObject<CydiaDelegate> *updatedelegate_;
6820 - (NSArray *) navigationURLCollection;
6821 - (void) beginUpdate;
6826 @implementation CydiaTabBarController
6828 - (NSArray *) navigationURLCollection {
6829 NSMutableArray *items([NSMutableArray array]);
6831 // XXX: Should this deal with transient view controllers?
6832 for (id navigation in [self viewControllers]) {
6833 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6835 [items addObject:stack];
6841 - (id) initWithDatabase:(Database *)database {
6842 if ((self = [super init]) != nil) {
6843 database_ = database;
6844 [self setDelegate:self];
6846 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6847 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6849 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6853 - (void) setUpdate:(NSDate *)date {
6857 - (void) beginUpdate {
6858 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6859 UITabBarItem *item([controller tabBarItem]);
6861 [item setBadgeValue:@""];
6862 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6864 [indicator_ startAnimating];
6865 [badge addSubview:indicator_];
6867 [updatedelegate_ retainNetworkActivityIndicator];
6871 detachNewThreadSelector:@selector(performUpdate)
6877 - (void) performUpdate {
6878 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6880 SourceStatus status(self, database_);
6881 [database_ updateWithStatus:status];
6884 performSelectorOnMainThread:@selector(completeUpdate)
6892 - (void) stopUpdateWithSelector:(SEL)selector {
6894 [updatedelegate_ releaseNetworkActivityIndicator];
6896 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6897 [[controller tabBarItem] setBadgeValue:nil];
6899 [indicator_ removeFromSuperview];
6900 [indicator_ stopAnimating];
6902 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6905 - (void) completeUpdate {
6908 [self stopUpdateWithSelector:@selector(reloadData)];
6911 - (void) cancelUpdate {
6912 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
6915 - (void) cancelPressed {
6916 [self cancelUpdate];
6923 - (bool) isSourceCancelled {
6927 - (void) startSourceFetch:(NSString *)uri {
6930 - (void) stopSourceFetch:(NSString *)uri {
6933 - (void) setUpdateDelegate:(id)delegate {
6934 updatedelegate_ = delegate;
6937 - (UIView *) transitionView {
6938 if (![self respondsToSelector:@selector(_transitionView)])
6939 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6940 else if (kCFCoreFoundationVersionNumber < 800)
6941 return [self _transitionView];
6943 return [[[self _transitionView] superview] superview];
6949 /* Cydia Navigation Controller Implementation {{{ */
6950 @implementation UINavigationController (Cydia)
6952 - (NSArray *) navigationURLCollection {
6953 NSMutableArray *stack([NSMutableArray array]);
6955 for (CyteViewController *controller in [self viewControllers]) {
6956 NSString *url = [[controller navigationURL] absoluteString];
6958 [stack addObject:url];
6964 - (void) reloadData {
6967 UIViewController *visible([self visibleViewController]);
6969 [visible reloadData];
6971 // on the iPad, this view controller is ALSO visible. :(
6973 if (UIViewController *top = [self topViewController])
6978 - (void) unloadData {
6979 for (CyteViewController *page in [self viewControllers])
6988 /* Cydia:// Protocol {{{ */
6989 @interface CydiaURLProtocol : NSURLProtocol {
6994 @implementation CydiaURLProtocol
6996 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6997 NSURL *url([request URL]);
7001 NSString *scheme([[url scheme] lowercaseString]);
7002 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7004 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7010 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7014 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7015 id<NSURLProtocolClient> client([self client]);
7017 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7019 NSData *data(UIImagePNGRepresentation(icon));
7021 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7022 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7023 [client URLProtocol:self didLoadData:data];
7024 [client URLProtocolDidFinishLoading:self];
7028 - (void) startLoading {
7029 id<NSURLProtocolClient> client([self client]);
7030 NSURLRequest *request([self request]);
7032 NSURL *url([request URL]);
7033 NSString *href([url absoluteString]);
7034 NSString *scheme([[url scheme] lowercaseString]);
7038 if ([scheme isEqualToString:@"cydia"])
7039 path = [href substringFromIndex:8];
7040 else if ([scheme isEqualToString:@"about"])
7041 path = [href substringFromIndex:12];
7042 else _assert(false);
7044 NSRange slash([path rangeOfString:@"/"]);
7047 if (slash.location == NSNotFound) {
7051 command = [path substringToIndex:slash.location];
7052 path = [path substringFromIndex:(slash.location + 1)];
7055 Database *database([Database sharedInstance]);
7057 if ([command isEqualToString:@"package-icon"]) {
7060 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7061 Package *package([database packageWithName:path]);
7065 UIImage *icon([package icon]);
7066 [self _returnPNGWithImage:icon forRequest:request];
7067 } else if ([command isEqualToString:@"uikit-image"]) {
7070 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7071 UIImage *icon(_UIImageWithName(path));
7072 [self _returnPNGWithImage:icon forRequest:request];
7073 } else if ([command isEqualToString:@"section-icon"]) {
7076 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7077 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7079 icon = [UIImage applicationImageNamed:@"unknown.png"];
7080 [self _returnPNGWithImage:icon forRequest:request];
7082 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7086 - (void) stopLoading {
7092 /* Section Controller {{{ */
7093 @interface SectionController : FilteredPackageListController {
7095 _H<NSString> section_;
7098 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7102 @implementation SectionController
7104 - (NSURL *) referrerURL {
7105 NSString *name(section_);
7106 name = name ?: @"*";
7107 NSString *key(key_);
7109 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7112 - (NSURL *) navigationURL {
7113 NSString *name(section_);
7114 name = name ?: @"*";
7115 NSString *key(key_);
7117 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7120 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7123 title = UCLocalize("ALL_PACKAGES");
7124 else if (![section isEqual:@""])
7125 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7127 title = UCLocalize("NO_SECTION");
7129 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:source:) with:section with:source]) != nil) {
7130 key_ = [source key];
7135 - (void) reloadData {
7136 [super setStuff:[database_ sourceWithKey:key_]];
7142 /* Sections Controller {{{ */
7143 @interface SectionsController : CyteViewController <
7144 UITableViewDataSource,
7147 _transient Database *database_;
7149 _H<NSMutableArray> sections_;
7150 _H<NSMutableArray> filtered_;
7151 _H<UITableView, 2> list_;
7154 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7155 - (void) editButtonClicked;
7159 @implementation SectionsController
7161 - (NSURL *) navigationURL {
7162 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7165 - (Source *) source {
7168 return [database_ sourceWithKey:key_];
7171 - (void) updateNavigationItem {
7172 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7173 if ([sections_ count] == 0) {
7174 [[self navigationItem] setRightBarButtonItem:nil];
7176 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7177 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7179 action:@selector(editButtonClicked)
7180 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7184 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7185 [super setEditing:editing animated:animated];
7190 [delegate_ updateData];
7192 [self updateNavigationItem];
7195 - (void) viewDidAppear:(BOOL)animated {
7196 [super viewDidAppear:animated];
7197 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7200 - (void) viewWillDisappear:(BOOL)animated {
7201 [super viewWillDisappear:animated];
7202 [self setEditing:NO];
7205 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7206 Section *section = nil;
7207 int index = [indexPath row];
7208 if (![self isEditing]) {
7211 section = [filtered_ objectAtIndex:index];
7213 section = [sections_ objectAtIndex:index];
7218 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7219 if ([self isEditing])
7220 return [sections_ count];
7222 return [filtered_ count] + 1;
7225 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7229 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7230 static NSString *reuseIdentifier = @"SectionCell";
7232 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7234 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7236 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7241 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7242 if ([self isEditing])
7245 Section *section = [self sectionAtIndexPath:indexPath];
7247 SectionController *controller = [[[SectionController alloc]
7248 initWithDatabase:database_
7249 source:[self source]
7250 section:[section name]
7252 [controller setDelegate:delegate_];
7254 [[self navigationController] pushViewController:controller animated:YES];
7258 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7259 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7260 [list_ setRowHeight:46];
7261 [(UITableView *) list_ setDataSource:self];
7262 [list_ setDelegate:self];
7263 [self setView:list_];
7266 - (void) viewDidLoad {
7267 [super viewDidLoad];
7269 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7272 - (void) releaseSubviews {
7278 [super releaseSubviews];
7281 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7282 if ((self = [super init]) != nil) {
7283 database_ = database;
7284 key_ = [source key];
7288 - (void) reloadData {
7291 NSArray *packages = [database_ packages];
7293 sections_ = [NSMutableArray arrayWithCapacity:16];
7294 filtered_ = [NSMutableArray arrayWithCapacity:16];
7296 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7298 Source *source([self source]);
7301 for (Package *package in packages) {
7302 if (source != nil && [package source] != source)
7305 NSString *name([package section]);
7306 NSString *key(name == nil ? @"" : name);
7310 _profile(SectionsView$reloadData$Section)
7311 section = [sections objectForKey:key];
7312 if (section == nil) {
7313 _profile(SectionsView$reloadData$Section$Allocate)
7314 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7315 [sections setObject:section forKey:key];
7320 [section addToCount];
7322 _profile(SectionsView$reloadData$Filter)
7323 if (![package valid] || ![package visible])
7331 [sections_ addObjectsFromArray:[sections allValues]];
7333 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7335 for (Section *section in (id) sections_) {
7336 size_t count([section row]);
7340 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7341 [section setCount:count];
7342 [filtered_ addObject:section];
7345 [self updateNavigationItem];
7350 - (void) editButtonClicked {
7351 [self setEditing:![self isEditing] animated:YES];
7357 /* Changes Controller {{{ */
7358 @interface ChangesController : CyteViewController <
7359 UITableViewDataSource,
7362 _transient Database *database_;
7364 _H<NSMutableArray> packages_;
7365 _H<NSMutableArray> sections_;
7366 _H<UITableView, 2> list_;
7370 - (id) initWithDatabase:(Database *)database;
7374 @implementation ChangesController
7376 - (NSURL *) navigationURL {
7377 return [NSURL URLWithString:@"cydia://changes"];
7380 - (void) viewDidAppear:(BOOL)animated {
7381 [super viewDidAppear:animated];
7382 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7385 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7386 NSInteger count([sections_ count]);
7387 return count == 0 ? 1 : count;
7390 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7391 if ([sections_ count] == 0)
7393 return [[sections_ objectAtIndex:section] name];
7396 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7397 if ([sections_ count] == 0)
7399 return [[sections_ objectAtIndex:section] count];
7402 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7403 @synchronized (database_) {
7404 if ([database_ era] != era_)
7407 NSUInteger sectionIndex([path section]);
7408 if (sectionIndex >= [sections_ count])
7410 Section *section([sections_ objectAtIndex:sectionIndex]);
7411 NSInteger row([path row]);
7412 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7415 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7416 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7418 cell = [[[PackageCell alloc] init] autorelease];
7420 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7421 [cell setPackage:package asSummary:false];
7425 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7426 Package *package([self packageAtIndexPath:path]);
7427 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[NSString stringWithFormat:@"%@/#!/changes/", UI_]] autorelease]);
7428 [view setDelegate:delegate_];
7429 [[self navigationController] pushViewController:view animated:YES];
7433 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7434 NSString *context([alert context]);
7436 if ([context isEqualToString:@"norefresh"])
7437 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7440 - (void) setLeftBarButtonItem {
7441 if ([delegate_ updating])
7442 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7443 initWithTitle:UCLocalize("CANCEL")
7444 style:UIBarButtonItemStyleDone
7446 action:@selector(cancelButtonClicked)
7447 ] autorelease] animated:YES];
7449 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7450 initWithTitle:UCLocalize("REFRESH")
7451 style:UIBarButtonItemStylePlain
7453 action:@selector(refreshButtonClicked)
7454 ] autorelease] animated:YES];
7457 - (void) refreshButtonClicked {
7458 if ([delegate_ requestUpdate])
7459 [self setLeftBarButtonItem];
7462 - (void) cancelButtonClicked {
7463 [delegate_ cancelUpdate];
7466 - (void) upgradeButtonClicked {
7467 [delegate_ distUpgrade];
7468 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7472 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7473 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7474 [self setView:view];
7476 list_ = [[[UITableView alloc] initWithFrame:[view bounds] style:UITableViewStylePlain] autorelease];
7477 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7478 [list_ setRowHeight:73];
7479 [(UITableView *) list_ setDataSource:self];
7480 [list_ setDelegate:self];
7481 [view addSubview:list_];
7484 - (void) viewDidLoad {
7485 [super viewDidLoad];
7487 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7490 - (void) releaseSubviews {
7496 [super releaseSubviews];
7499 - (id) initWithDatabase:(Database *)database {
7500 if ((self = [super init]) != nil) {
7501 database_ = database;
7505 - (NSMutableArray *) _reloadPackages {
7506 @synchronized (database_) {
7507 era_ = [database_ era];
7508 NSArray *packages([database_ packages]);
7510 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7513 _profile(ChangesController$_reloadPackages$Filter)
7514 for (Package *package in packages)
7515 if ([package upgradableAndEssential:YES] || [package visible])
7516 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7519 _profile(ChangesController$_reloadPackages$radixSort)
7520 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7527 - (void) _reloadData {
7528 [self setLeftBarButtonItem];
7530 NSMutableArray *packages;
7534 UIProgressHUD *hud([delegate_ addProgressHUD]);
7535 [hud setText:UCLocalize("LOADING")];
7536 //NSLog(@"HUD:%@::%@", delegate_, hud);
7537 packages = [self yieldToSelector:@selector(_reloadPackages)];
7538 [delegate_ removeProgressHUD:hud];
7540 packages = [self _reloadPackages];
7543 @synchronized (database_) {
7544 if (era_ != [database_ era])
7547 packages_ = packages;
7548 sections_ = [NSMutableArray arrayWithCapacity:16];
7550 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7551 Section *ignored = nil;
7552 Section *section = nil;
7556 bool unseens = false;
7558 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7560 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7561 Package *package = [packages_ objectAtIndex:offset];
7563 BOOL uae = [package upgradableAndEssential:YES];
7567 time_t seen([package seen]);
7569 if (section == nil || last != seen) {
7573 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7576 _profile(ChangesController$reloadData$Allocate)
7577 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7578 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7579 [sections_ addObject:section];
7583 [section addToCount];
7584 } else if ([package ignored]) {
7585 if (ignored == nil) {
7586 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7588 [ignored addToCount];
7591 [upgradable addToCount];
7596 CFRelease(formatter);
7599 Section *last = [sections_ lastObject];
7600 size_t count = [last count];
7601 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7602 [sections_ removeLastObject];
7605 if ([ignored count] != 0)
7606 [sections_ insertObject:ignored atIndex:0];
7608 [sections_ insertObject:upgradable atIndex:0];
7612 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7613 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7614 style:UIBarButtonItemStylePlain
7616 action:@selector(upgradeButtonClicked)
7617 ] autorelease]) animated:YES];
7622 - (void) reloadData {
7624 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7629 /* Search Controller {{{ */
7630 @interface SearchController : FilteredPackageListController <
7633 _H<UISearchBar, 1> search_;
7637 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7638 - (void) reloadData;
7642 @implementation SearchController
7644 - (NSURL *) referrerURL {
7645 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7648 - (NSURL *) navigationURL {
7649 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7650 return [NSURL URLWithString:@"cydia://search"];
7652 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7655 - (NSArray *) termsForQuery:(NSString *)query {
7656 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7657 for (NSString *component in [query componentsSeparatedByString:@" "])
7658 if ([component length] != 0)
7659 [terms addObject:component];
7664 - (void) useSearch {
7665 [self setObject:[self termsForQuery:[search_ text]] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7670 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7671 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7676 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7677 [search_ resignFirstResponder];
7681 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7682 [search_ setText:@""];
7683 [self searchBarButtonClicked:searchBar];
7686 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7687 [self searchBarButtonClicked:searchBar];
7690 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7691 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7695 - (bool) shouldYield {
7699 - (bool) shouldBlock {
7700 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7703 - (bool) isSummarized {
7704 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7707 - (bool) showsSections {
7711 - (NSMutableArray *) _reloadPackages {
7712 NSMutableArray *packages([super _reloadPackages]);
7713 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7714 [packages radixSortUsingSelector:@selector(rank)];
7718 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7719 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[self termsForQuery:query]])) {
7720 search_ = [[[UISearchBar alloc] init] autorelease];
7721 [search_ setDelegate:self];
7724 [search_ setText:query];
7728 - (void) viewDidAppear:(BOOL)animated {
7729 [super viewDidAppear:animated];
7731 if (!searchloaded_) {
7732 searchloaded_ = YES;
7733 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7734 [search_ layoutSubviews];
7735 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7737 UITextField *textField;
7738 if ([search_ respondsToSelector:@selector(searchField)])
7739 textField = [search_ searchField];
7741 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7743 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7744 [textField setEnablesReturnKeyAutomatically:NO];
7745 [[self navigationItem] setTitleView:textField];
7748 if ([self isSummarized])
7749 [search_ becomeFirstResponder];
7752 - (void) reloadData {
7753 id object([search_ text]);
7754 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7755 object = [self termsForQuery:object];
7757 [self setObject:object];
7763 - (void) didSelectPackage:(Package *)package {
7764 [search_ resignFirstResponder];
7765 [super didSelectPackage:package];
7770 /* Package Settings Controller {{{ */
7771 @interface PackageSettingsController : CyteViewController <
7772 UITableViewDataSource,
7775 _transient Database *database_;
7777 _H<Package> package_;
7778 _H<UITableView, 2> table_;
7779 _H<UISwitch> subscribedSwitch_;
7780 _H<UISwitch> ignoredSwitch_;
7781 _H<UITableViewCell> subscribedCell_;
7782 _H<UITableViewCell> ignoredCell_;
7785 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7789 @implementation PackageSettingsController
7791 - (NSURL *) navigationURL {
7792 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7795 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7796 if (package_ == nil)
7799 if ([package_ installed] == nil)
7805 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7806 if (package_ == nil)
7809 // both sections contain just one item right now.
7813 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7817 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7819 return UCLocalize("SHOW_ALL_CHANGES_EX");
7821 return UCLocalize("IGNORE_UPGRADES_EX");
7824 - (void) onSubscribed:(id)control {
7825 bool value([control isOn]);
7826 if (package_ == nil)
7828 if ([package_ setSubscribed:value])
7829 [delegate_ updateData];
7832 - (void) _updateIgnored {
7833 const char *package([name_ UTF8String]);
7834 bool on([ignoredSwitch_ isOn]);
7836 pid_t pid(ExecFork());
7838 FILE *dpkg(popen("dpkg --set-selections", "w"));
7839 fwrite(package, strlen(package), 1, dpkg);
7842 fwrite(" hold\n", 6, 1, dpkg);
7844 fwrite(" install\n", 9, 1, dpkg);
7852 - (void) onIgnored:(id)control {
7853 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7854 [invocation setTarget:self];
7855 [invocation setSelector:@selector(_updateIgnored)];
7857 [delegate_ reloadDataWithInvocation:invocation];
7860 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7861 if (package_ == nil)
7864 switch ([indexPath section]) {
7865 case 0: return subscribedCell_;
7866 case 1: return ignoredCell_;
7875 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7876 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7877 [self setView:view];
7879 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7880 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7881 [(UITableView *) table_ setDataSource:self];
7882 [table_ setDelegate:self];
7883 [view addSubview:table_];
7885 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7886 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7887 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7889 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7890 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7891 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7893 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7894 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7895 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7896 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7898 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7899 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7900 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7901 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7904 - (void) viewDidLoad {
7905 [super viewDidLoad];
7907 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7910 - (void) releaseSubviews {
7912 subscribedCell_ = nil;
7914 ignoredSwitch_ = nil;
7915 subscribedSwitch_ = nil;
7917 [super releaseSubviews];
7920 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7921 if ((self = [super init]) != nil) {
7922 database_ = database;
7927 - (void) reloadData {
7930 package_ = [database_ packageWithName:name_];
7932 if (package_ != nil) {
7933 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7934 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7935 } // XXX: what now, G?
7937 [table_ reloadData];
7943 /* Installed Controller {{{ */
7944 @interface InstalledController : FilteredPackageListController {
7947 - (id) initWithDatabase:(Database *)database;
7948 - (void) queueStatusDidChange;
7952 @implementation InstalledController
7954 - (NSURL *) referrerURL {
7955 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
7958 - (NSURL *) navigationURL {
7959 return [NSURL URLWithString:@"cydia://installed"];
7962 - (id) initWithDatabase:(Database *)database {
7963 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7964 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("SIMPLE"), UCLocalize("EXPERT"), nil]] autorelease]);
7965 [segmented setSelectedSegmentIndex:0];
7966 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
7967 [[self navigationItem] setTitleView:segmented];
7969 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
7971 [self queueStatusDidChange];
7976 - (void) queueButtonClicked {
7981 - (void) queueStatusDidChange {
7984 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7985 initWithTitle:UCLocalize("QUEUE")
7986 style:UIBarButtonItemStyleDone
7988 action:@selector(queueButtonClicked)
7991 [[self navigationItem] setLeftBarButtonItem:nil];
7996 - (void) modeChanged:(UISegmentedControl *)segmented {
7997 bool simple([segmented selectedSegmentIndex] == 0);
7998 [self setObject:[NSNumber numberWithBool:simple]];
8005 /* Source Cell {{{ */
8006 @interface SourceCell : CyteTableViewCell <
8007 CyteTableViewCellDelegate,
8010 _H<Source, 1> source_;
8013 _H<NSString> origin_;
8014 _H<NSString> label_;
8015 _H<UIActivityIndicatorView> indicator_;
8018 - (void) setSource:(Source *)source;
8019 - (void) setFetch:(NSNumber *)fetch;
8023 @implementation SourceCell
8025 - (void) _setImage:(NSArray *)data {
8026 if ([url_ isEqual:[data objectAtIndex:0]]) {
8027 icon_ = [data objectAtIndex:1];
8028 [content_ setNeedsDisplay];
8032 - (void) _setSource:(NSURL *) url {
8033 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8035 if (NSData *data = [NSURLConnection
8036 sendSynchronousRequest:[NSURLRequest
8038 cachePolicy:NSURLRequestUseProtocolCachePolicy
8042 returningResponse:NULL
8045 if (UIImage *image = [UIImage imageWithData:data])
8046 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8051 - (void) setSource:(Source *)source {
8053 [source_ setDelegate:self];
8055 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8057 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8059 origin_ = [source name];
8060 label_ = [source rooturi];
8062 [content_ setNeedsDisplay];
8064 url_ = [source iconURL];
8065 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8068 - (void) setAllSource {
8070 [indicator_ stopAnimating];
8072 icon_ = [UIImage applicationImageNamed:@"folder.png"];
8073 origin_ = UCLocalize("ALL_SOURCES");
8074 label_ = UCLocalize("ALL_SOURCES_EX");
8075 [content_ setNeedsDisplay];
8078 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8079 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8080 UIView *content([self contentView]);
8081 CGRect bounds([content bounds]);
8083 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8084 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8085 [content_ setBackgroundColor:[UIColor whiteColor]];
8086 [content addSubview:content_];
8088 [content_ setDelegate:self];
8089 [content_ setOpaque:YES];
8091 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8092 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8093 [content addSubview:indicator_];
8095 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8099 - (void) layoutSubviews {
8100 [super layoutSubviews];
8102 UIView *content([self contentView]);
8103 CGRect bounds([content bounds]);
8105 CGRect frame([indicator_ frame]);
8106 frame.origin.x = bounds.size.width - frame.size.width;
8107 frame.origin.y = (bounds.size.height - frame.size.height) / 2;
8109 if (kCFCoreFoundationVersionNumber < 800)
8110 frame.origin.x -= 8;
8111 [indicator_ setFrame:frame];
8114 - (NSString *) accessibilityLabel {
8118 - (void) drawContentRect:(CGRect)rect {
8119 bool highlighted(highlighted_);
8120 float width(rect.size.width);
8124 rect.size = [(UIImage *) icon_ size];
8126 while (rect.size.width > 32 || rect.size.height > 32) {
8127 rect.size.width /= 2;
8128 rect.size.height /= 2;
8131 rect.origin.x = 26 - rect.size.width / 2;
8132 rect.origin.y = 26 - rect.size.height / 2;
8134 [icon_ drawInRect:rect];
8137 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8142 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 61) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8146 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 61) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8149 - (void) setFetch:(NSNumber *)fetch {
8150 if ([fetch boolValue])
8151 [indicator_ startAnimating];
8153 [indicator_ stopAnimating];
8158 /* Sources Controller {{{ */
8159 @interface SourcesController : CyteViewController <
8160 UITableViewDataSource,
8163 _transient Database *database_;
8166 _H<UITableView, 2> list_;
8167 _H<NSMutableArray> sources_;
8171 _H<UIProgressHUD> hud_;
8174 //NSURLConnection *installer_;
8175 NSURLConnection *trivial_bz2_;
8176 NSURLConnection *trivial_gz_;
8177 //NSURLConnection *automatic_;
8182 - (id) initWithDatabase:(Database *)database;
8183 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8187 @implementation SourcesController
8189 - (void) _releaseConnection:(NSURLConnection *)connection {
8190 if (connection != nil) {
8191 [connection cancel];
8192 //[connection setDelegate:nil];
8193 [connection release];
8198 //[self _releaseConnection:installer_];
8199 [self _releaseConnection:trivial_gz_];
8200 [self _releaseConnection:trivial_bz2_];
8201 //[self _releaseConnection:automatic_];
8206 - (NSURL *) navigationURL {
8207 return [NSURL URLWithString:@"cydia://sources"];
8210 - (void) viewDidAppear:(BOOL)animated {
8211 [super viewDidAppear:animated];
8212 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8215 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8219 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8221 return UCLocalize("INDIVIDUAL_SOURCES");
8225 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8228 case 1: return [sources_ count];
8233 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8234 @synchronized (database_) {
8235 if ([database_ era] != era_)
8237 if ([indexPath section] != 1)
8239 NSUInteger index([indexPath row]);
8240 if (index >= [sources_ count])
8242 return [sources_ objectAtIndex:index];
8245 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8246 static NSString *cellIdentifier = @"SourceCell";
8248 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8249 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8250 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8252 Source *source([self sourceAtIndexPath:indexPath]);
8254 [cell setAllSource];
8256 [cell setSource:source];
8261 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8262 SectionsController *controller([[[SectionsController alloc]
8263 initWithDatabase:database_
8264 source:[self sourceAtIndexPath:indexPath]
8267 [controller setDelegate:delegate_];
8268 [[self navigationController] pushViewController:controller animated:YES];
8271 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8272 if ([indexPath section] != 1)
8274 Source *source = [self sourceAtIndexPath:indexPath];
8275 return [source record] != nil;
8278 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8279 _assert([indexPath section] == 1);
8280 if (editingStyle == UITableViewCellEditingStyleDelete) {
8281 Source *source = [self sourceAtIndexPath:indexPath];
8282 if (source == nil) return;
8284 [Sources_ removeObjectForKey:[source key]];
8287 [delegate_ _saveConfig];
8288 [delegate_ reloadDataWithInvocation:nil];
8293 [delegate_ addTrivialSource:href_];
8296 [delegate_ syncData];
8299 - (NSString *) getWarning {
8300 NSString *href(href_);
8301 NSRange colon([href rangeOfString:@"://"]);
8302 if (colon.location != NSNotFound)
8303 href = [href substringFromIndex:(colon.location + 3)];
8304 href = [href stringByAddingPercentEscapes];
8305 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8307 NSURL *url([NSURL URLWithString:href]);
8309 NSStringEncoding encoding;
8310 NSError *error(nil);
8312 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8313 return [warning length] == 0 ? nil : warning;
8317 - (void) _endConnection:(NSURLConnection *)connection {
8318 // XXX: the memory management in this method is horribly awkward
8320 NSURLConnection **field = NULL;
8321 if (connection == trivial_bz2_)
8322 field = &trivial_bz2_;
8323 else if (connection == trivial_gz_)
8324 field = &trivial_gz_;
8325 _assert(field != NULL);
8326 [connection release];
8330 trivial_bz2_ == nil &&
8333 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8335 [delegate_ releaseNetworkActivityIndicator];
8337 [delegate_ removeProgressHUD:hud_];
8341 if (warning != nil) {
8342 UIAlertView *alert = [[[UIAlertView alloc]
8343 initWithTitle:UCLocalize("SOURCE_WARNING")
8346 cancelButtonTitle:UCLocalize("CANCEL")
8348 UCLocalize("ADD_ANYWAY"),
8352 [alert setContext:@"warning"];
8353 [alert setNumberOfRows:1];
8356 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8362 } else if (error_ != nil) {
8363 UIAlertView *alert = [[[UIAlertView alloc]
8364 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8365 message:[error_ localizedDescription]
8367 cancelButtonTitle:UCLocalize("OK")
8368 otherButtonTitles:nil
8371 [alert setContext:@"urlerror"];
8376 UIAlertView *alert = [[[UIAlertView alloc]
8377 initWithTitle:UCLocalize("NOT_REPOSITORY")
8378 message:UCLocalize("NOT_REPOSITORY_EX")
8380 cancelButtonTitle:UCLocalize("OK")
8381 otherButtonTitles:nil
8384 [alert setContext:@"trivial"];
8394 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8395 switch ([response statusCode]) {
8401 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8402 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8404 [self _endConnection:connection];
8407 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8408 [self _endConnection:connection];
8411 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8412 NSURL *url([NSURL URLWithString:href]);
8414 NSMutableURLRequest *request = [NSMutableURLRequest
8416 cachePolicy:NSURLRequestUseProtocolCachePolicy
8420 [request setHTTPMethod:method];
8422 if (Machine_ != NULL)
8423 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8425 if (UniqueID_ != nil)
8426 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8428 if ([url isCydiaSecure]) {
8429 if (UniqueID_ != nil)
8430 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8433 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8436 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8437 NSString *context([alert context]);
8439 if ([context isEqualToString:@"source"]) {
8442 NSString *href = [[alert textField] text];
8444 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8446 if (![href hasSuffix:@"/"])
8447 href_ = [href stringByAppendingString:@"/"];
8451 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8452 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8453 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8457 // XXX: this is stupid
8458 hud_ = [delegate_ addProgressHUD];
8459 [hud_ setText:UCLocalize("VERIFYING_URL")];
8460 [delegate_ retainNetworkActivityIndicator];
8469 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8470 } else if ([context isEqualToString:@"trivial"])
8471 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8472 else if ([context isEqualToString:@"urlerror"])
8473 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8474 else if ([context isEqualToString:@"warning"]) {
8477 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8486 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8490 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8491 BOOL editing([list_ isEditing]);
8494 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8495 initWithTitle:UCLocalize("ADD")
8496 style:UIBarButtonItemStylePlain
8498 action:@selector(addButtonClicked)
8499 ] autorelease] animated:animated];
8500 else if ([delegate_ updating])
8501 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8502 initWithTitle:UCLocalize("CANCEL")
8503 style:UIBarButtonItemStyleDone
8505 action:@selector(cancelButtonClicked)
8506 ] autorelease] animated:animated];
8508 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8509 initWithTitle:UCLocalize("REFRESH")
8510 style:UIBarButtonItemStylePlain
8512 action:@selector(refreshButtonClicked)
8513 ] autorelease] animated:animated];
8515 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8516 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8517 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8519 action:@selector(editButtonClicked)
8520 ] autorelease] animated:animated];
8524 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8525 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8526 [list_ setRowHeight:53];
8527 [(UITableView *) list_ setDataSource:self];
8528 [list_ setDelegate:self];
8529 [self setView:list_];
8532 - (void) viewDidLoad {
8533 [super viewDidLoad];
8535 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8536 [self updateButtonsForEditingStatusAnimated:NO];
8539 - (void) viewWillAppear:(BOOL)animated {
8540 [super viewWillAppear:animated];
8542 [list_ setEditing:NO];
8543 [self updateButtonsForEditingStatusAnimated:NO];
8546 - (void) releaseSubviews {
8551 [super releaseSubviews];
8554 - (id) initWithDatabase:(Database *)database {
8555 if ((self = [super init]) != nil) {
8556 database_ = database;
8560 - (void) reloadData {
8562 [self updateButtonsForEditingStatusAnimated:YES];
8564 @synchronized (database_) {
8565 era_ = [database_ era];
8567 sources_ = [NSMutableArray arrayWithCapacity:16];
8568 [sources_ addObjectsFromArray:[database_ sources]];
8570 [sources_ sortUsingSelector:@selector(compareByName:)];
8573 int count([sources_ count]);
8575 for (int i = 0; i != count; i++) {
8576 if ([[sources_ objectAtIndex:i] record] == nil)
8584 - (void) showAddSourcePrompt {
8585 UIAlertView *alert = [[[UIAlertView alloc]
8586 initWithTitle:UCLocalize("ENTER_APT_URL")
8589 cancelButtonTitle:UCLocalize("CANCEL")
8591 UCLocalize("ADD_SOURCE"),
8595 [alert setContext:@"source"];
8597 [alert setNumberOfRows:1];
8598 [alert addTextFieldWithValue:@"http://" label:@""];
8600 UITextInputTraits *traits = [[alert textField] textInputTraits];
8601 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8602 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8603 [traits setKeyboardType:UIKeyboardTypeURL];
8604 // XXX: UIReturnKeyDone
8605 [traits setReturnKeyType:UIReturnKeyNext];
8610 - (void) addButtonClicked {
8611 [self showAddSourcePrompt];
8614 - (void) refreshButtonClicked {
8615 if ([delegate_ requestUpdate])
8616 [self updateButtonsForEditingStatusAnimated:YES];
8619 - (void) cancelButtonClicked {
8620 [delegate_ cancelUpdate];
8623 - (void) editButtonClicked {
8624 [list_ setEditing:![list_ isEditing] animated:YES];
8625 [self updateButtonsForEditingStatusAnimated:YES];
8631 /* Stash Controller {{{ */
8632 @interface StashController : CyteViewController {
8633 _H<UIActivityIndicatorView> spinner_;
8634 _H<UILabel> status_;
8635 _H<UILabel> caption_;
8640 @implementation StashController
8643 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8644 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8645 [self setView:view];
8647 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8649 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8650 CGRect spinrect = [spinner_ frame];
8651 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8652 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8653 [spinner_ setFrame:spinrect];
8654 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8655 [view addSubview:spinner_];
8656 [spinner_ startAnimating];
8659 captrect.size.width = [[self view] frame].size.width;
8660 captrect.size.height = 40.0f;
8661 captrect.origin.x = 0;
8662 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8663 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8664 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8665 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8666 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8667 [caption_ setTextColor:[UIColor whiteColor]];
8668 [caption_ setBackgroundColor:[UIColor clearColor]];
8669 [caption_ setShadowColor:[UIColor blackColor]];
8670 [caption_ setTextAlignment:UITextAlignmentCenter];
8671 [view addSubview:caption_];
8674 statusrect.size.width = [[self view] frame].size.width;
8675 statusrect.size.height = 30.0f;
8676 statusrect.origin.x = 0;
8677 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8678 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8679 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8680 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8681 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8682 [status_ setTextColor:[UIColor whiteColor]];
8683 [status_ setBackgroundColor:[UIColor clearColor]];
8684 [status_ setShadowColor:[UIColor blackColor]];
8685 [status_ setTextAlignment:UITextAlignmentCenter];
8686 [view addSubview:status_];
8689 - (void) releaseSubviews {
8694 [super releaseSubviews];
8700 @interface CYURLCache : SDURLCache {
8705 @implementation CYURLCache
8707 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8710 else if ([event isEqualToString:@"no-cache"])
8712 else if ([event isEqualToString:@"store"])
8714 else if ([event isEqualToString:@"invalid"])
8716 else if ([event isEqualToString:@"memory"])
8718 else if ([event isEqualToString:@"disk"])
8720 else if ([event isEqualToString:@"miss"])
8723 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8727 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8728 if (NSURLResponse *response = [cached response])
8729 if (NSString *mime = [response MIMEType])
8730 if ([mime isEqualToString:@"text/cache-manifest"]) {
8731 NSURL *url([response URL]);
8734 NSLog(@"###: %@", [url absoluteString]);
8737 @synchronized (HostConfig_) {
8738 [CachedURLs_ addObject:url];
8742 [super storeCachedResponse:cached forRequest:request];
8747 @interface Cydia : UIApplication <
8748 ConfirmationControllerDelegate,
8751 UINavigationControllerDelegate,
8752 UITabBarControllerDelegate
8754 _H<UIWindow> window_;
8755 _H<CydiaTabBarController> tabbar_;
8756 _H<CydiaLoadingViewController> emulated_;
8758 _H<NSMutableArray> essential_;
8759 _H<NSMutableArray> broken_;
8761 Database *database_;
8763 _H<NSURL> starturl_;
8768 _H<StashController> stash_;
8777 @implementation Cydia
8779 - (void) lockSuspend {
8780 if (locked_++ == 0) {
8781 if ($SBSSetInterceptsMenuButtonForever != NULL)
8782 (*$SBSSetInterceptsMenuButtonForever)(true);
8784 [self setIdleTimerDisabled:YES];
8788 - (void) unlockSuspend {
8789 if (--locked_ == 0) {
8790 [self setIdleTimerDisabled:NO];
8792 if ($SBSSetInterceptsMenuButtonForever != NULL)
8793 (*$SBSSetInterceptsMenuButtonForever)(false);
8797 - (void) beginUpdate {
8798 [tabbar_ beginUpdate];
8801 - (void) cancelUpdate {
8802 [tabbar_ cancelUpdate];
8805 - (bool) requestUpdate {
8806 if (IsReachable("cydia.saurik.com")) {
8810 UIAlertView *alert = [[[UIAlertView alloc]
8811 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8812 message:@"Host Unreachable" // XXX: Localize
8814 cancelButtonTitle:UCLocalize("OK")
8815 otherButtonTitles:nil
8818 [alert setContext:@"norefresh"];
8826 return [tabbar_ updating];
8830 if ([broken_ count] != 0) {
8831 int count = [broken_ count];
8833 UIAlertView *alert = [[[UIAlertView alloc]
8834 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8835 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8837 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8839 UCLocalize("TEMPORARY_IGNORE"),
8843 [alert setContext:@"fixhalf"];
8844 [alert setNumberOfRows:2];
8846 } else if (!Ignored_ && [essential_ count] != 0) {
8847 int count = [essential_ count];
8849 UIAlertView *alert = [[[UIAlertView alloc]
8850 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8851 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8853 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8855 UCLocalize("UPGRADE_ESSENTIAL"),
8856 UCLocalize("COMPLETE_UPGRADE"),
8860 [alert setContext:@"upgrade"];
8865 - (void) returnToCydia {
8869 - (void) _saveConfig {
8870 @synchronized (database_) {
8877 NSString *error(nil);
8879 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8881 NSError *error(nil);
8882 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8883 NSLog(@"failure to save metadata data: %@", error);
8888 NSLog(@"failure to serialize metadata: %@", error);
8892 CydiaWriteSources();
8895 // Navigation controller for the queuing badge.
8896 - (UINavigationController *) queueNavigationController {
8897 NSArray *controllers = [tabbar_ viewControllers];
8898 return [controllers objectAtIndex:3];
8901 - (void) unloadData {
8902 [tabbar_ unloadData];
8905 - (void) _updateData {
8909 UINavigationController *navigation = [self queueNavigationController];
8911 id queuedelegate = nil;
8912 if ([[navigation viewControllers] count] > 0)
8913 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8915 [queuedelegate queueStatusDidChange];
8916 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8919 - (void) _refreshIfPossible:(NSDate *)update {
8920 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8922 bool recently = false;
8923 if (update != nil) {
8924 NSTimeInterval interval([update timeIntervalSinceNow]);
8925 if (interval <= 0 && interval > -(15*60))
8929 // Don't automatic refresh if:
8930 // - We already refreshed recently.
8931 // - We already auto-refreshed this launch.
8932 // - Auto-refresh is disabled.
8933 // - Cydia's server is not reachable
8934 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
8935 // If we are cancelling, we need to make sure it knows it's already loaded.
8938 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8940 // We are going to load, so remember that.
8943 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8949 - (void) refreshIfPossible {
8950 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8953 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8954 @synchronized (self) {
8955 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8957 [hud setText:UCLocalize("RELOADING_DATA")];
8959 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8963 [essential_ removeAllObjects];
8964 [broken_ removeAllObjects];
8966 NSArray *packages([database_ packages]);
8967 for (Package *package in packages) {
8969 [broken_ addObject:package];
8970 if ([package upgradableAndEssential:YES] && ![package ignored]) {
8971 if ([package essential] && [package installed] != nil)
8972 [essential_ addObject:package];
8977 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8980 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8981 [changesItem setBadgeValue:badge];
8982 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8983 [self setApplicationIconBadgeNumber:changes];
8986 [changesItem setBadgeValue:nil];
8987 [changesItem setAnimatedBadge:NO];
8988 [self setApplicationIconBadgeNumber:0];
8994 [self removeProgressHUD:hud];
8997 - (void) updateData {
9001 - (void) updateDataAndLoad {
9003 if ([database_ progressDelegate] == nil)
9009 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9012 - (void) disemulate {
9013 if (emulated_ == nil)
9016 [window_ addSubview:[tabbar_ view]];
9017 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9018 [window_ setRootViewController:tabbar_];
9019 [[emulated_ view] removeFromSuperview];
9021 [window_ setUserInteractionEnabled:YES];
9024 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9025 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9027 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9029 UIViewController *parent;
9030 if (emulated_ == nil)
9039 [parent presentModalViewController:navigation animated:YES];
9042 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9043 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9045 if (navigation != nil)
9046 [navigation pushViewController:progress animated:YES];
9048 [self presentModalViewController:progress force:YES];
9050 [progress invoke:invocation withTitle:title];
9054 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9055 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9058 - (void) repairWithInvocation:(NSInvocation *)invocation {
9060 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9064 - (void) repairWithSelector:(SEL)selector {
9065 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9068 - (void) reloadData {
9069 [self reloadDataWithInvocation:nil];
9070 if ([database_ progressDelegate] == nil)
9076 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9079 - (void) addSource:(NSDictionary *) source {
9080 CydiaAddSource(source);
9083 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9084 CydiaAddSource(href, distribution, sections);
9087 - (void) addTrivialSource:(NSString *)href {
9088 CydiaAddSource(href, @"./");
9091 - (void) updateValues {
9096 pkgProblemResolver *resolver = [database_ resolver];
9098 resolver->InstallProtect();
9099 if (!resolver->Resolve(true))
9104 // XXX: this is a really crappy way of doing this.
9105 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9106 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9107 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9108 if ([tabbar_ updating])
9109 [tabbar_ cancelUpdate];
9111 if (![database_ prepare])
9114 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9115 [page setDelegate:self];
9116 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9119 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9120 [tabbar_ presentModalViewController:confirm_ animated:YES];
9126 @synchronized (self) {
9131 - (void) clearPackage:(Package *)package {
9132 @synchronized (self) {
9139 - (void) installPackages:(NSArray *)packages {
9140 @synchronized (self) {
9141 for (Package *package in packages)
9148 - (void) installPackage:(Package *)package {
9149 @synchronized (self) {
9156 - (void) removePackage:(Package *)package {
9157 @synchronized (self) {
9164 - (void) distUpgrade {
9165 @synchronized (self) {
9166 if (![database_ upgrade])
9174 system("su -c /usr/bin/uicache mobile");
9179 UIProgressHUD *hud([self addProgressHUD]);
9180 [hud setText:UCLocalize("LOADING")];
9181 [self yieldToSelector:@selector(_uicache)];
9182 [self removeProgressHUD:hud];
9186 [database_ perform];
9187 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9188 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9191 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9194 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9195 [self unlockSuspend];
9198 - (void) retainNetworkActivityIndicator {
9199 if (activity_++ == 0)
9200 [self setNetworkActivityIndicatorVisible:YES];
9203 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9207 - (void) releaseNetworkActivityIndicator {
9208 if (--activity_ == 0)
9209 [self setNetworkActivityIndicatorVisible:NO];
9212 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9217 - (void) cancelAndClear:(bool)clear {
9218 @synchronized (self) {
9230 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9231 NSString *context([alert context]);
9233 if ([context isEqualToString:@"conffile"]) {
9234 FILE *input = [database_ input];
9235 if (button == [alert cancelButtonIndex])
9236 fprintf(input, "N\n");
9237 else if (button == [alert firstOtherButtonIndex])
9238 fprintf(input, "Y\n");
9241 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9242 } else if ([context isEqualToString:@"fixhalf"]) {
9243 if (button == [alert cancelButtonIndex]) {
9244 @synchronized (self) {
9245 for (Package *broken in (id) broken_) {
9248 NSString *id = [broken id];
9249 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9250 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9251 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9252 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9258 } else if (button == [alert firstOtherButtonIndex]) {
9259 [broken_ removeAllObjects];
9263 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9264 } else if ([context isEqualToString:@"upgrade"]) {
9265 if (button == [alert firstOtherButtonIndex]) {
9266 @synchronized (self) {
9267 for (Package *essential in (id) essential_)
9268 [essential install];
9273 } else if (button == [alert firstOtherButtonIndex] + 1) {
9275 } else if (button == [alert cancelButtonIndex]) {
9279 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9283 - (void) system:(NSString *)command {
9284 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9287 system([command UTF8String]);
9293 - (void) applicationWillSuspend {
9295 [super applicationWillSuspend];
9298 - (BOOL) isSafeToSuspend {
9301 NSLog(@"isSafeToSuspend: locked_ != 0");
9306 // Use external process status API internally.
9307 // This is probably a really bad idea.
9308 // XXX: what is the point of this? does this solve anything at all?
9309 uint64_t status = 0;
9311 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9312 notify_get_state(notify_token, &status);
9313 notify_cancel(notify_token);
9318 NSLog(@"isSafeToSuspend: status != 0");
9324 NSLog(@"isSafeToSuspend: -> true");
9329 - (void) applicationSuspend:(__GSEvent *)event {
9330 if ([self isSafeToSuspend])
9331 [super applicationSuspend:event];
9334 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9335 if ([self isSafeToSuspend])
9336 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9339 - (void) _setSuspended:(BOOL)value {
9340 if ([self isSafeToSuspend])
9341 [super _setSuspended:value];
9344 - (UIProgressHUD *) addProgressHUD {
9345 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9346 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9348 [window_ setUserInteractionEnabled:NO];
9350 UIViewController *target(tabbar_);
9351 if (UIViewController *modal = [target modalViewController])
9354 [hud showInView:[target view]];
9360 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9361 [self unlockSuspend];
9363 [hud removeFromSuperview];
9364 [window_ setUserInteractionEnabled:YES];
9367 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9368 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9371 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9372 NSString *scheme([[url scheme] lowercaseString]);
9373 if ([[url absoluteString] length] <= [scheme length] + 3)
9375 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9376 NSArray *components([path componentsSeparatedByString:@"/"]);
9378 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9379 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9380 if (controller != nil)
9381 [controller setDelegate:self];
9385 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9388 NSString *base([components objectAtIndex:0]);
9390 CyteViewController *controller = nil;
9392 if ([base isEqualToString:@"url"]) {
9393 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9394 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9395 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9396 } else if (!external && [components count] == 1) {
9397 if ([base isEqualToString:@"sources"]) {
9398 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9401 if ([base isEqualToString:@"home"]) {
9402 controller = [[[HomeController alloc] init] autorelease];
9405 if ([base isEqualToString:@"sections"]) {
9406 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9409 if ([base isEqualToString:@"search"]) {
9410 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9413 if ([base isEqualToString:@"changes"]) {
9414 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9417 if ([base isEqualToString:@"installed"]) {
9418 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9420 } else if ([components count] == 2) {
9421 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9423 if ([base isEqualToString:@"package"]) {
9424 controller = [self pageForPackage:argument withReferrer:referrer];
9427 if (!external && [base isEqualToString:@"search"]) {
9428 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9431 if (!external && [base isEqualToString:@"sections"]) {
9432 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9434 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9437 if (!external && [base isEqualToString:@"sources"]) {
9438 if ([argument isEqualToString:@"add"]) {
9439 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9440 [(SourcesController *)controller showAddSourcePrompt];
9442 Source *source([database_ sourceWithKey:argument]);
9443 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9447 if (!external && [base isEqualToString:@"launch"]) {
9448 [self launchApplicationWithIdentifier:argument suspended:NO];
9451 } else if (!external && [components count] == 3) {
9452 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9453 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9455 if ([base isEqualToString:@"package"]) {
9456 if ([arg2 isEqualToString:@"settings"]) {
9457 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9458 } else if ([arg2 isEqualToString:@"files"]) {
9459 if (Package *package = [database_ packageWithName:arg1]) {
9460 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9461 [(FileTable *)controller setPackage:package];
9466 if ([base isEqualToString:@"sections"]) {
9467 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9468 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9469 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9473 [controller setDelegate:self];
9477 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9478 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9481 [tabbar_ setUnselectedViewController:page];
9486 - (void) applicationOpenURL:(NSURL *)url {
9487 [super applicationOpenURL:url];
9492 [self openCydiaURL:url forExternal:YES];
9495 - (void) applicationWillResignActive:(UIApplication *)application {
9496 // Stop refreshing if you get a phone call or lock the device.
9497 if ([tabbar_ updating])
9498 [tabbar_ cancelUpdate];
9500 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9501 [super applicationWillResignActive:application];
9504 - (void) saveState {
9505 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9506 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9507 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9513 - (void) applicationWillTerminate:(UIApplication *)application {
9517 - (void) setConfigurationData:(NSString *)data {
9518 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9520 if (!conffile_r(data)) {
9521 lprintf("E:invalid conffile\n");
9525 NSString *ofile = conffile_r[1];
9526 //NSString *nfile = conffile_r[2];
9528 UIAlertView *alert = [[[UIAlertView alloc]
9529 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9530 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9532 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9534 UCLocalize("ACCEPT_NEW_COPY"),
9535 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9539 [alert setContext:@"conffile"];
9540 [alert setNumberOfRows:2];
9544 - (void) addStashController {
9546 stash_ = [[[StashController alloc] init] autorelease];
9547 [window_ addSubview:[stash_ view]];
9550 - (void) removeStashController {
9551 [[stash_ view] removeFromSuperview];
9553 [self unlockSuspend];
9557 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9558 UpdateExternalStatus(1);
9559 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9560 UpdateExternalStatus(0);
9562 [self removeStashController];
9564 pid_t pid(ExecFork());
9566 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9567 perror("launchctl stop");
9573 - (void) setupViewControllers {
9574 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9576 NSMutableArray *items;
9577 if (kCFCoreFoundationVersionNumber < 800) {
9578 items = [NSMutableArray arrayWithObjects:
9579 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9580 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9581 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9582 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease],
9583 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9586 items = [NSMutableArray arrayWithObjects:
9587 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home7.png"] selectedImage:[UIImage applicationImageNamed:@"home7s.png"]] autorelease],
9588 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install7.png"] selectedImage:[UIImage applicationImageNamed:@"install7s.png"]] autorelease],
9589 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes7.png"] selectedImage:[UIImage applicationImageNamed:@"changes7s.png"]] autorelease],
9590 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage7.png"] selectedImage:[UIImage applicationImageNamed:@"manage7s.png"]] autorelease],
9591 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search7.png"] selectedImage:[UIImage applicationImageNamed:@"search7s.png"]] autorelease],
9595 NSMutableArray *controllers([NSMutableArray array]);
9596 for (UITabBarItem *item in items) {
9597 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9598 [controller setTabBarItem:item];
9599 [controllers addObject:controller];
9601 [tabbar_ setViewControllers:controllers];
9603 [tabbar_ setUpdateDelegate:self];
9606 - (void) _sendMemoryWarningNotification {
9607 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9608 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9610 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9613 - (void) _sendMemoryWarningNotifications {
9615 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9621 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9623 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9626 - (void) applicationDidFinishLaunching:(id)unused {
9627 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9630 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9631 [self setApplicationSupportsShakeToEdit:NO];
9633 @synchronized (HostConfig_) {
9634 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9637 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9638 initWithMemoryCapacity:524288
9639 diskCapacity:10485760
9640 diskPath:[NSString stringWithFormat:@"%@/SDURLCache", Cache_]
9643 [CydiaWebViewController _initialize];
9645 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9647 // this would disallow http{,s} URLs from accessing this data
9648 //[WebView registerURLSchemeAsLocal:@"cydia"];
9650 Font12_ = [UIFont systemFontOfSize:12];
9651 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9652 Font14_ = [UIFont systemFontOfSize:14];
9653 Font18_ = [UIFont systemFontOfSize:18];
9654 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9655 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9657 essential_ = [NSMutableArray arrayWithCapacity:4];
9658 broken_ = [NSMutableArray arrayWithCapacity:4];
9660 // XXX: I really need this thing... like, seriously... I'm sorry
9661 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9663 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9664 [window_ orderFront:self];
9665 [window_ makeKey:self];
9666 [window_ setHidden:NO];
9669 [self addStashController];
9670 // XXX: this would be much cleaner as a yieldToSelector:
9671 // that way the removeStashController could happen right here inline
9672 // we also could no longer require the useless stash_ field anymore
9673 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9678 int error(stat("/", &root));
9679 _assert(error != -1);
9681 #define Stash_(path) do { \
9682 struct stat folder; \
9683 int error(lstat((path), &folder)); \
9684 if (error != -1 && ( \
9685 folder.st_dev == root.st_dev && \
9686 S_ISDIR(folder.st_mode) \
9687 ) || error == -1 && ( \
9688 errno == ENOENT || \
9693 Stash_("/Applications");
9694 Stash_("/Library/Ringtones");
9695 Stash_("/Library/Wallpaper");
9696 //Stash_("/usr/bin");
9697 Stash_("/usr/include");
9698 Stash_("/usr/lib/pam");
9699 Stash_("/usr/share");
9700 //Stash_("/var/lib");
9702 database_ = [Database sharedInstance];
9703 [database_ setDelegate:self];
9705 [window_ setUserInteractionEnabled:NO];
9706 [self setupViewControllers];
9708 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9709 [window_ addSubview:[emulated_ view]];
9710 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9711 [window_ setRootViewController:emulated_];
9713 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9717 - (NSArray *) defaultStartPages {
9718 NSMutableArray *standard = [NSMutableArray array];
9719 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9720 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9721 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9722 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9723 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9729 if ([emulated_ modalViewController] != nil)
9730 [emulated_ dismissModalViewControllerAnimated:YES];
9731 [window_ setUserInteractionEnabled:NO];
9733 [self reloadDataWithInvocation:nil];
9734 [self refreshIfPossible];
9739 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9740 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9741 int standardIndex = 0;
9742 NSArray *standard = [self defaultStartPages];
9749 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9750 if (valid && closed != nil) {
9751 NSTimeInterval interval([closed timeIntervalSinceNow]);
9752 // XXX: Is 30 minutes the optimal time here?
9753 if (interval <= -(30*60))
9757 if (valid && [saved count] != [standard count])
9761 for (unsigned int i = 0; i < [standard count]; i++) {
9762 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9763 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9764 // but it's good enough for now.
9765 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9772 NSArray *items = nil;
9774 [tabbar_ setSelectedIndex:savedIndex];
9777 [tabbar_ setSelectedIndex:standardIndex];
9781 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9782 NSArray *stack = [items objectAtIndex:tab];
9783 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9784 NSMutableArray *current = [NSMutableArray array];
9786 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9787 NSString *addr = [stack objectAtIndex:nav];
9788 NSURL *url = [NSURL URLWithString:addr];
9789 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9791 [current addObject:page];
9794 [navigation setViewControllers:current];
9797 // (Try to) show the startup URL.
9798 if (starturl_ != nil) {
9799 [self openCydiaURL:starturl_ forExternal:NO];
9804 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9805 if (item != nil && IsWildcat_) {
9806 [sheet showFromBarButtonItem:item animated:YES];
9808 [sheet showInView:window_];
9812 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9813 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9814 [progress setTitle:task];
9815 [progress addProgressEvent:event];
9818 - (void) addProgressEventForTask:(NSArray *)data {
9819 CydiaProgressEvent *event([data objectAtIndex:0]);
9820 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9821 [self addProgressEvent:event forTask:task];
9824 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9825 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9831 id Alloc_(id self, SEL selector) {
9832 id object = alloc_(self, selector);
9833 lprintf("[%s]A-%p\n", self->isa->name, object);
9838 id Dealloc_(id self, SEL selector) {
9839 id object = dealloc_(self, selector);
9840 lprintf("[%s]D-%p\n", self->isa->name, object);
9844 static NSSet *MobilizedFiles_;
9846 static NSURL *MobilizeURL(NSURL *url) {
9847 NSString *path([url path]);
9848 if ([path hasPrefix:@"/var/root/"]) {
9849 NSString *file([path substringFromIndex:10]);
9850 if ([MobilizedFiles_ containsObject:file])
9851 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9857 Class $CFXPreferencesPropertyListSource;
9858 @class CFXPreferencesPropertyListSource;
9860 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9861 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9862 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9863 url = MobilizeURL(url);
9864 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9865 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9871 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9872 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9873 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9874 url = MobilizeURL(url);
9875 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9876 //NSLog(@"%@ %@", [url absoluteString], value);
9882 Class $NSURLConnection;
9884 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9885 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
9887 NSURL *url([copy URL]);
9889 NSString *host([url host]);
9890 NSString *scheme([[url scheme] lowercaseString]);
9892 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9894 @synchronized (HostConfig_) {
9895 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9896 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9897 [copy setHTTPShouldUsePipelining:YES];
9899 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9900 if ([control isEqualToString:@"max-age=0"])
9901 if ([CachedURLs_ containsObject:url]) {
9903 NSLog(@"~~~: %@", url);
9906 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9908 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9909 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9910 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9914 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9920 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
9921 CGSize size([[UIScreen mainScreen] bounds].size);
9922 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
9923 if ([$WAKWindow hasLandscapeOrientation])
9924 std::swap(size.width, size.height);*/
9928 Class $NSUserDefaults;
9930 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
9931 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
9932 return [NSString stringWithFormat:@"%@/LocalStorage", Cache_];
9933 return _NSUserDefaults$objectForKey$(self, _cmd, key);
9936 int main(int argc, char *argv[]) {
9937 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9941 UpdateExternalStatus(0);
9943 UIScreen *screen([UIScreen mainScreen]);
9944 if ([screen respondsToSelector:@selector(scale)])
9945 ScreenScale_ = [screen scale];
9949 UIDevice *device([UIDevice currentDevice]);
9950 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
9951 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9952 if (idiom == UIUserInterfaceIdiomPad)
9956 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
9958 Pcre pattern("^([0-9]+\\.[0-9]+)");
9960 if (pattern([device systemVersion]))
9961 Firmware_ = pattern[1];
9962 if (pattern(Cydia_))
9963 Major_ = pattern[1];
9965 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9967 HostConfig_ = [[[NSObject alloc] init] autorelease];
9968 @synchronized (HostConfig_) {
9969 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9970 TokenHosts_ = [NSMutableSet setWithCapacity:4];
9971 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9972 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9973 CachedURLs_ = [NSMutableSet setWithCapacity:32];
9976 NSString *ui(@"ui/ios");
9978 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
9979 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
9982 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9984 MobilizedFiles_ = [NSMutableSet setWithObjects:
9985 @"Library/Preferences/com.apple.Accessibility.plist",
9986 @"Library/Preferences/com.apple.preferences.sounds.plist",
9989 /* Library Hacks {{{ */
9990 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9992 $WAKWindow = objc_getClass("WAKWindow");
9993 if ($WAKWindow != NULL)
9994 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
9995 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
9997 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9999 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10000 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10001 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10002 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10005 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10006 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10007 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10008 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10011 $NSURLConnection = objc_getClass("NSURLConnection");
10012 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10013 if (NSURLConnection$init$ != NULL) {
10014 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10015 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10018 $NSUserDefaults = objc_getClass("NSUserDefaults");
10019 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10020 if (NSUserDefaults$objectForKey$ != NULL) {
10021 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10022 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10025 /* Set Locale {{{ */
10026 Locale_ = CFLocaleCopyCurrent();
10027 Languages_ = [NSLocale preferredLanguages];
10029 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10030 //NSLog(@"%@", [Languages_ description]);
10033 if (Locale_ != NULL)
10034 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10035 else if (Languages_ != nil && [Languages_ count] != 0)
10036 lang = [[Languages_ objectAtIndex:0] UTF8String];
10038 // XXX: consider just setting to C and then falling through?
10041 if (lang != NULL) {
10042 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10043 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10046 NSLog(@"Setting Language: %s", lang);
10048 if (lang != NULL) {
10049 setenv("LANG", lang, true);
10050 std::setlocale(LC_ALL, lang);
10054 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10056 /* Parse Arguments {{{ */
10057 bool substrate(false);
10063 for (int argi(1); argi != argc; ++argi)
10064 if (strcmp(argv[argi], "--") == 0) {
10066 argv[argi] = argv[0];
10072 for (int argi(1); argi != arge; ++argi)
10073 if (strcmp(args[argi], "--substrate") == 0)
10076 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10080 App_ = [[NSBundle mainBundle] bundlePath];
10086 if (access("/var/mobile/Library/Keyboard/UserDictionary.sqlite", F_OK) == 0)
10087 system("mkdir -p /var/root/Library/Keyboard; cp -af /var/mobile/Library/Keyboard/UserDictionary.sqlite /var/root/Library/Keyboard/");
10089 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/root"] retain];
10091 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10092 alloc_ = alloc->method_imp;
10093 alloc->method_imp = (IMP) &Alloc_;*/
10095 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10096 dealloc_ = dealloc->method_imp;
10097 dealloc->method_imp = (IMP) &Dealloc_;*/
10099 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10100 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10102 /* System Information {{{ */
10106 size = sizeof(maxproc);
10107 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10108 perror("sysctlbyname(\"kern.maxproc\", ?)");
10109 else if (maxproc < 64) {
10111 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10112 perror("sysctlbyname(\"kern.maxproc\", #)");
10115 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10116 char *osversion = new char[size];
10117 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10118 perror("sysctlbyname(\"kern.osversion\", ?)");
10120 System_ = [NSString stringWithUTF8String:osversion];
10122 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10123 char *machine = new char[size];
10124 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10125 perror("sysctlbyname(\"hw.machine\", ?)");
10127 Machine_ = machine;
10129 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10130 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10131 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10133 UniqueID_ = UniqueIdentifier(device);
10135 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10136 Product_ = [info objectForKey:@"SafariProductVersion"];
10137 Safari_ = [info objectForKey:@"CFBundleVersion"];
10140 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10142 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10143 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10144 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10145 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10146 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10147 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10149 UserAgent_ = agent;
10151 /* Load Database {{{ */
10153 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10155 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10157 if (Metadata_ == NULL)
10158 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10160 Settings_ = [Metadata_ objectForKey:@"Settings"];
10162 Packages_ = [Metadata_ objectForKey:@"Packages"];
10164 Values_ = [Metadata_ objectForKey:@"Values"];
10165 Sections_ = [Metadata_ objectForKey:@"Sections"];
10166 Sources_ = [Metadata_ objectForKey:@"Sources"];
10168 Token_ = [Metadata_ objectForKey:@"Token"];
10170 Version_ = [Metadata_ objectForKey:@"Version"];
10173 if (Values_ == nil) {
10174 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10175 [Metadata_ setObject:Values_ forKey:@"Values"];
10178 if (Sections_ == nil) {
10179 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10180 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10183 if (Sources_ == nil) {
10184 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10185 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10188 if (Version_ == nil) {
10189 Version_ = [NSNumber numberWithUnsignedInt:0];
10190 [Metadata_ setObject:Version_ forKey:@"Version"];
10193 if ([Version_ unsignedIntValue] == 0) {
10194 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10195 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10196 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10197 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10199 Version_ = [NSNumber numberWithUnsignedInt:1];
10200 [Metadata_ setObject:Version_ forKey:@"Version"];
10202 [Metadata_ removeObjectForKey:@"LastUpdate"];
10208 CydiaWriteSources();
10211 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10214 if (Packages_ != nil) {
10216 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10220 [Metadata_ removeObjectForKey:@"Packages"];
10226 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10228 #define MobileSubstrate_(name) \
10229 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10230 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10231 if (handle == NULL) \
10232 NSLog(@"%s", dlerror()); \
10235 MobileSubstrate_(Activator)
10236 MobileSubstrate_(libstatusbar)
10237 MobileSubstrate_(SimulatedKeyEvents)
10238 MobileSubstrate_(WinterBoard)
10240 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10241 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10243 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10245 if (access("/User", F_OK) != 0 || version != 6) {
10247 system("/usr/libexec/cydia/firmware.sh");
10251 _assert([[NSFileManager defaultManager]
10252 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10253 withIntermediateDirectories:YES
10258 if (access("/tmp/cydia.chk", F_OK) == 0) {
10259 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10260 _assert(errno == ENOENT);
10261 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10262 _assert(errno == ENOENT);
10265 /* APT Initialization {{{ */
10266 _assert(pkgInitConfig(*_config));
10267 _assert(pkgInitSystem(*_config, _system));
10270 _config->Set("APT::Acquire::Translation", lang);
10272 // XXX: this timeout might be important :(
10273 //_config->Set("Acquire::http::Timeout", 15);
10275 _config->Set("Acquire::http::MaxParallel", 3);
10277 /* Color Choices {{{ */
10278 space_ = CGColorSpaceCreateDeviceRGB();
10280 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10281 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10282 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10283 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10284 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10285 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10286 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10287 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10288 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10289 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10291 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10292 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10294 /* UIKit Configuration {{{ */
10295 // XXX: I have a feeling this was important
10296 //UIKeyboardDisableAutomaticAppearance();
10299 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10301 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10302 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10303 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10305 PulseInterval_ = fast ? 50000 : 500000;
10307 Colon_ = UCLocalize("COLON_DELIMITED");
10308 Elision_ = UCLocalize("ELISION");
10309 Error_ = UCLocalize("ERROR");
10310 Warning_ = UCLocalize("WARNING");
10313 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10315 CGColorSpaceRelease(space_);
10316 CFRelease(Locale_);