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;
1085 - (void) resetFetch;
1087 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1091 /* SourceStatus {{{ */
1092 class SourceStatus :
1096 _transient NSObject<FetchDelegate> *delegate_;
1097 _transient Database *database_;
1100 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1101 delegate_(delegate),
1106 void Set(bool fetch, pkgAcquire::ItemDesc &desc) {
1108 [database_ setFetch:fetch forURI:desc.Owner->DescURI().c_str()];
1111 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1115 virtual void Done(pkgAcquire::ItemDesc &desc) {
1119 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1123 virtual bool Pulse_(pkgAcquire *Owner) {
1124 for (pkgAcquire::ItemCIterator item = Owner->ItemsBegin(); item != Owner->ItemsEnd(); ++item)
1125 if ((*item)->ID != 0);
1126 else if ((*item)->Status == pkgAcquire::Item::StatIdle) {
1128 [database_ setFetch:true forURI:(*item)->DescURI().c_str()];
1129 } else (*item)->ID = 0;
1130 return ![delegate_ isSourceCancelled];
1133 virtual void Stop() {
1134 pkgAcquireStatus::Stop();
1135 [database_ resetFetch];
1139 /* ProgressEvent Implementation {{{ */
1140 @implementation CydiaProgressEvent
1142 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1143 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1146 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1147 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1148 [event setPackage:package];
1152 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1153 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1155 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1156 NSArray *fields([description componentsSeparatedByString:@" "]);
1157 [event setItem:fields];
1159 if ([fields count] > 3) {
1160 [event setPackage:[fields objectAtIndex:2]];
1161 [event setVersion:[fields objectAtIndex:3]];
1164 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1169 + (NSArray *) _attributeKeys {
1170 return [NSArray arrayWithObjects:
1180 - (NSArray *) attributeKeys {
1181 return [[self class] _attributeKeys];
1184 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1185 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1188 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1189 if ((self = [super init]) != nil) {
1195 - (NSString *) message {
1199 - (NSString *) type {
1203 - (NSArray *) item {
1204 return (id) item_ ?: [NSNull null];
1207 - (void) setItem:(NSArray *)item {
1211 - (NSString *) package {
1212 return (id) package_ ?: [NSNull null];
1215 - (void) setPackage:(NSString *)package {
1219 - (NSString *) url {
1220 return (id) url_ ?: [NSNull null];
1223 - (void) setURL:(NSString *)url {
1227 - (void) setVersion:(NSString *)version {
1231 - (NSString *) version {
1232 return (id) version_ ?: [NSNull null];
1235 - (NSString *) compound:(NSString *)value {
1237 NSString *mode(nil); {
1238 NSString *type([self type]);
1239 if ([type isEqualToString:kCydiaProgressEventTypeError])
1240 mode = UCLocalize("ERROR");
1241 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1242 mode = UCLocalize("WARNING");
1246 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1252 - (NSString *) compoundMessage {
1253 return [self compound:[self message]];
1256 - (NSString *) compoundTitle {
1259 if (package_ == nil)
1261 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1262 title = [package name];
1266 return [self compound:title];
1272 // Cytore Definitions {{{
1273 struct PackageValue :
1276 Cytore::Offset<PackageValue> next_;
1278 uint32_t index_ : 23;
1279 uint32_t subscribed_ : 1;
1296 Cytore::Offset<PackageValue> packages_[1 << 16];
1299 static Cytore::File<MetaValue> MetaFile_;
1301 // Cytore Helper Functions {{{
1302 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1303 SplitHash nhash = { hashlittle(name, length) };
1305 PackageValue *metadata;
1307 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1308 offset: if (offset->IsNull()) {
1309 *offset = MetaFile_.New<PackageValue>(length + 1);
1310 metadata = &MetaFile_.Get(*offset);
1312 if (metadata == NULL) {
1316 metadata = new PackageValue();
1317 memset(metadata, 0, sizeof(*metadata));
1320 memcpy(metadata->name_, name, length + 1);
1321 metadata->nhash_ = nhash.u16[1];
1323 metadata = &MetaFile_.Get(*offset);
1325 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1326 offset = &metadata->next_;
1334 static void PackageImport(const void *key, const void *value, void *context) {
1335 bool &fail(*reinterpret_cast<bool *>(context));
1338 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1339 NSLog(@"failed to import package %@", key);
1343 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1344 NSDictionary *package((NSDictionary *) value);
1346 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1347 if ([subscribed boolValue] && !metadata->subscribed_)
1348 metadata->subscribed_ = true;
1350 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1351 time_t time([date timeIntervalSince1970]);
1352 if (metadata->first_ > time || metadata->first_ == 0)
1353 metadata->first_ = time;
1356 NSDate *date([package objectForKey:@"LastSeen"]);
1357 NSString *version([package objectForKey:@"LastVersion"]);
1359 if (date != nil && version != nil) {
1360 time_t time([date timeIntervalSince1970]);
1361 if (metadata->last_ < time || metadata->last_ == 0)
1362 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1363 size_t length(strlen(buffer));
1364 uint16_t vhash(hashlittle(buffer, length));
1366 size_t capped(std::min<size_t>(8, length));
1367 char *latest(buffer + length - capped);
1369 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1370 metadata->vhash_ = vhash;
1372 metadata->last_ = time;
1378 /* Source Class {{{ */
1379 @interface Source : NSObject {
1381 Database *database_;
1384 CYString depiction_;
1385 CYString description_;
1391 CYString distribution_;
1397 _H<NSString> authority_;
1399 CYString defaultIcon_;
1401 _H<NSMutableDictionary> record_;
1404 std::set<std::string> fetches_;
1405 std::set<std::string> files_;
1406 _transient NSObject<SourceDelegate> *delegate_;
1409 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1411 - (NSComparisonResult) compareByName:(Source *)source;
1413 - (NSString *) depictionForPackage:(NSString *)package;
1414 - (NSString *) supportForPackage:(NSString *)package;
1416 - (metaIndex *) metaIndex;
1417 - (NSDictionary *) record;
1420 - (NSString *) rooturi;
1421 - (NSString *) distribution;
1422 - (NSString *) type;
1425 - (NSString *) host;
1427 - (NSString *) name;
1428 - (NSString *) shortDescription;
1429 - (NSString *) label;
1430 - (NSString *) origin;
1431 - (NSString *) version;
1433 - (NSString *) defaultIcon;
1434 - (NSURL *) iconURL;
1436 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1437 - (void) resetFetch;
1441 @implementation Source
1443 + (NSString *) webScriptNameForSelector:(SEL)selector {
1445 else if (selector == @selector(addSection:))
1446 return @"addSection";
1447 else if (selector == @selector(getField:))
1449 else if (selector == @selector(removeSection:))
1450 return @"removeSection";
1451 else if (selector == @selector(remove))
1457 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1458 return [self webScriptNameForSelector:selector] == nil;
1461 + (NSArray *) _attributeKeys {
1462 return [NSArray arrayWithObjects:
1473 @"shortDescription",
1480 - (NSArray *) attributeKeys {
1481 return [[self class] _attributeKeys];
1484 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1485 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1488 - (metaIndex *) metaIndex {
1492 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1493 trusted_ = index->IsTrusted();
1495 uri_.set(pool, index->GetURI());
1496 distribution_.set(pool, index->GetDist());
1497 type_.set(pool, index->GetType());
1499 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1500 if (dindex != NULL) {
1501 std::string file(dindex->MetaIndexURI(""));
1502 files_.insert(file + "Release.gpg");
1503 files_.insert(file + "Release");
1504 base_.set(pool, file);
1506 std::vector<IndexTarget *> *targets(dindex->ComputeIndexTargets());
1507 for (std::vector<IndexTarget *>::const_iterator target(targets->begin()); target != targets->end(); ++target) {
1508 std::string file((*target)->URI);
1509 files_.insert(file);
1510 files_.insert(file + ".gz");
1511 files_.insert(file + ".bz2");
1512 files_.insert(file + "Index");
1516 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1519 pkgTagFile tags(&fd);
1521 pkgTagSection section;
1528 {"default-icon", &defaultIcon_},
1529 {"depiction", &depiction_},
1530 {"description", &description_},
1532 {"origin", &origin_},
1533 {"support", &support_},
1534 {"version", &version_},
1537 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1538 const char *start, *end;
1540 if (section.Find(names[i].name_, start, end)) {
1541 CYString &value(*names[i].value_);
1542 value.set(pool, start, end - start);
1548 record_ = [Sources_ objectForKey:[self key]];
1550 NSURL *url([NSURL URLWithString:uri_]);
1554 host_ = [host_ lowercaseString];
1559 authority_ = [url path];
1562 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1563 if ((self = [super init]) != nil) {
1564 era_ = [database era];
1565 database_ = database;
1568 [self setMetaIndex:index inPool:pool];
1572 - (NSString *) getField:(NSString *)name {
1573 @synchronized (database_) {
1574 if ([database_ era] != era_ || index_ == NULL)
1577 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1582 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1587 pkgTagFile tags(&fd);
1589 pkgTagSection section;
1592 const char *start, *end;
1593 if (!section.Find([name UTF8String], start, end))
1594 return (NSString *) [NSNull null];
1596 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1599 - (NSComparisonResult) compareByName:(Source *)source {
1600 NSString *lhs = [self name];
1601 NSString *rhs = [source name];
1603 if ([lhs length] != 0 && [rhs length] != 0) {
1604 unichar lhc = [lhs characterAtIndex:0];
1605 unichar rhc = [rhs characterAtIndex:0];
1607 if (isalpha(lhc) && !isalpha(rhc))
1608 return NSOrderedAscending;
1609 else if (!isalpha(lhc) && isalpha(rhc))
1610 return NSOrderedDescending;
1613 return [lhs compare:rhs options:LaxCompareOptions_];
1616 - (NSString *) depictionForPackage:(NSString *)package {
1617 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1620 - (NSString *) supportForPackage:(NSString *)package {
1621 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1624 - (NSArray *) sections {
1625 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1628 - (void) _addSection:(NSString *)section {
1631 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1632 if (![sections containsObject:section]) {
1633 [sections addObject:section];
1637 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1642 - (bool) addSection:(NSString *)section {
1646 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1650 - (void) _removeSection:(NSString *)section {
1654 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1655 if ([sections containsObject:section]) {
1656 [sections removeObject:section];
1661 - (bool) removeSection:(NSString *)section {
1665 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1670 [Sources_ removeObjectForKey:[self key]];
1675 bool value(record_ != nil);
1676 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1680 - (NSDictionary *) record {
1688 - (NSString *) rooturi {
1692 - (NSString *) distribution {
1693 return distribution_;
1696 - (NSString *) type {
1700 - (NSString *) baseuri {
1701 return base_.empty() ? nil : (id) base_;
1704 - (NSString *) iconuri {
1705 if (NSString *base = [self baseuri])
1706 return [base stringByAppendingString:@"CydiaIcon.png"];
1711 - (NSURL *) iconURL {
1712 if (NSString *uri = [self iconuri])
1713 return [NSURL URLWithString:uri];
1717 - (NSString *) key {
1718 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1721 - (NSString *) host {
1725 - (NSString *) name {
1726 return origin_.empty() ? (id) authority_ : origin_;
1729 - (NSString *) shortDescription {
1730 return description_;
1733 - (NSString *) label {
1734 return label_.empty() ? (id) authority_ : label_;
1737 - (NSString *) origin {
1741 - (NSString *) version {
1745 - (NSString *) defaultIcon {
1746 return defaultIcon_;
1749 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1750 delegate_ = delegate;
1754 return !fetches_.empty();
1757 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1759 if (fetches_.erase(uri) == 0)
1761 } else if (files_.find(uri) == files_.end())
1763 else if (!fetches_.insert(uri).second)
1766 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1769 - (void) resetFetch {
1771 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1776 /* CydiaOperation Class {{{ */
1777 @interface CydiaOperation : NSObject {
1778 _H<NSString> operator_;
1779 _H<NSString> value_;
1782 - (NSString *) operator;
1783 - (NSString *) value;
1787 @implementation CydiaOperation
1789 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1790 if ((self = [super init]) != nil) {
1791 operator_ = [NSString stringWithUTF8String:_operator];
1792 value_ = [NSString stringWithUTF8String:value];
1796 + (NSArray *) _attributeKeys {
1797 return [NSArray arrayWithObjects:
1803 - (NSArray *) attributeKeys {
1804 return [[self class] _attributeKeys];
1807 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1808 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1811 - (NSString *) operator {
1815 - (NSString *) value {
1821 /* CydiaClause Class {{{ */
1822 @interface CydiaClause : NSObject {
1823 _H<NSString> package_;
1824 _H<CydiaOperation> version_;
1827 - (NSString *) package;
1828 - (CydiaOperation *) version;
1832 @implementation CydiaClause
1834 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1835 if ((self = [super init]) != nil) {
1836 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1838 if (const char *version = dep.TargetVer())
1839 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1841 version_ = (id) [NSNull null];
1845 + (NSArray *) _attributeKeys {
1846 return [NSArray arrayWithObjects:
1852 - (NSArray *) attributeKeys {
1853 return [[self class] _attributeKeys];
1856 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1857 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1860 - (NSString *) package {
1864 - (CydiaOperation *) version {
1870 /* CydiaRelation Class {{{ */
1871 @interface CydiaRelation : NSObject {
1872 _H<NSString> relationship_;
1873 _H<NSMutableArray> clauses_;
1876 - (NSString *) relationship;
1877 - (NSArray *) clauses;
1881 @implementation CydiaRelation
1883 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1884 if ((self = [super init]) != nil) {
1885 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1886 clauses_ = [NSMutableArray arrayWithCapacity:8];
1888 pkgCache::DepIterator start;
1889 pkgCache::DepIterator end;
1890 dep.GlobOr(start, end); // ++dep
1893 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1895 // yes, seriously. (wtf?)
1903 + (NSArray *) _attributeKeys {
1904 return [NSArray arrayWithObjects:
1910 - (NSArray *) attributeKeys {
1911 return [[self class] _attributeKeys];
1914 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1915 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1918 - (NSString *) relationship {
1919 return relationship_;
1922 - (NSArray *) clauses {
1926 - (void) addClause:(CydiaClause *)clause {
1927 [clauses_ addObject:clause];
1932 /* Package Class {{{ */
1933 struct ParsedPackage {
1937 CYString architecture_;
1940 CYString depiction_;
1947 @interface Package : NSObject {
1950 uint32_t essential_ : 1;
1951 uint32_t obsolete_ : 1;
1952 uint32_t ignored_ : 1;
1953 uint32_t pooled_ : 1;
1959 _transient Database *database_;
1961 pkgCache::VerIterator version_;
1962 pkgCache::PkgIterator iterator_;
1963 pkgCache::VerFileIterator file_;
1969 CYString installed_;
1971 const char *section_;
1972 _transient NSString *section$_;
1976 PackageValue *metadata_;
1977 ParsedPackage *parsed_;
1979 _H<NSMutableArray> tags_;
1982 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1983 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1985 - (pkgCache::PkgIterator) iterator;
1988 - (NSString *) section;
1989 - (NSString *) simpleSection;
1991 - (NSString *) longSection;
1992 - (NSString *) shortSection;
1996 - (MIMEAddress *) maintainer;
1998 - (NSString *) longDescription;
1999 - (NSString *) shortDescription;
2002 - (PackageValue *) metadata;
2005 - (bool) subscribed;
2006 - (bool) setSubscribed:(bool)subscribed;
2010 - (NSString *) latest;
2011 - (NSString *) installed;
2012 - (BOOL) uninstalled;
2015 - (BOOL) upgradableAndEssential:(BOOL)essential;
2018 - (BOOL) unfiltered;
2022 - (BOOL) halfConfigured;
2023 - (BOOL) halfInstalled;
2025 - (NSString *) mode;
2028 - (NSString *) name;
2030 - (NSString *) homepage;
2031 - (NSString *) depiction;
2032 - (MIMEAddress *) author;
2034 - (NSString *) support;
2036 - (NSArray *) files;
2037 - (NSArray *) warnings;
2038 - (NSArray *) applications;
2040 - (Source *) source;
2043 - (BOOL) matches:(NSArray *)query;
2045 - (BOOL) hasTag:(NSString *)tag;
2046 - (NSString *) primaryPurpose;
2047 - (NSArray *) purposes;
2048 - (bool) isCommercial;
2050 - (void) setIndex:(size_t)index;
2052 - (CYString &) cyname;
2054 - (uint32_t) compareBySection:(NSArray *)sections;
2059 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
2060 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2061 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2062 - (bool) isVisibleInSection:(NSString *)section source:(Source *)source;
2063 - (bool) isVisibleInSource:(Source *)source;
2067 uint32_t PackageChangesRadix(Package *self, void *) {
2072 uint32_t timestamp : 30;
2073 uint32_t ignored : 1;
2074 uint32_t upgradable : 1;
2078 bool upgradable([self upgradableAndEssential:YES]);
2079 value.bits.upgradable = upgradable ? 1 : 0;
2082 value.bits.timestamp = 0;
2083 value.bits.ignored = [self ignored] ? 0 : 1;
2084 value.bits.upgradable = 1;
2086 value.bits.timestamp = [self seen] >> 2;
2087 value.bits.ignored = 0;
2088 value.bits.upgradable = 0;
2091 return _not(uint32_t) - value.key;
2094 uint32_t PackagePrefixRadix(Package *self, void *context) {
2095 size_t offset(reinterpret_cast<size_t>(context));
2096 CYString &name([self cyname]);
2098 size_t size(name.size());
2101 char *text(name.data());
2104 if (!isdigit(text[0]))
2108 while (size != digits && isdigit(text[digits]))
2116 if (offset == 0 && zeros != 0) {
2117 memset(data, '0', zeros);
2118 memcpy(data + zeros, text, 4 - zeros);
2120 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2121 if (size <= offset - zeros)
2124 text += offset - zeros;
2125 size -= offset - zeros;
2128 memcpy(data, text, 4);
2130 memcpy(data, text, size);
2131 memset(data + size, 0, 4 - size);
2134 for (size_t i(0); i != 4; ++i)
2135 if (isalpha(data[i]))
2143 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2145 /* XXX: ntohl may be more honest */
2146 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2149 CYString &(*PackageName)(Package *self, SEL sel);
2151 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2152 _profile(PackageNameCompare)
2153 CYString &lhi(PackageName(lhs, @selector(cyname)));
2154 CYString &rhi(PackageName(rhs, @selector(cyname)));
2155 CFStringRef lhn(lhi), rhn(rhi);
2158 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2159 else if (rhn == NULL)
2160 return NSOrderedDescending;
2162 _profile(PackageNameCompare$NumbersLast)
2163 if (!lhi.empty() && !rhi.empty()) {
2164 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2165 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2166 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2167 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2168 return lha ? NSOrderedAscending : NSOrderedDescending;
2172 CFIndex length = CFStringGetLength(lhn);
2174 _profile(PackageNameCompare$Compare)
2175 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2180 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2181 return PackageNameCompare(*lhs, *rhs, context);
2184 struct PackageNameOrdering :
2185 std::binary_function<Package *, Package *, bool>
2187 _finline bool operator ()(Package *lhs, Package *rhs) const {
2188 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2192 @implementation Package
2194 - (NSString *) description {
2195 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2200 apr_pool_destroy(pool_);
2201 if (parsed_ != NULL)
2206 + (NSString *) webScriptNameForSelector:(SEL)selector {
2208 else if (selector == @selector(clear))
2210 else if (selector == @selector(getField:))
2212 else if (selector == @selector(getRecord))
2213 return @"getRecord";
2214 else if (selector == @selector(hasTag:))
2216 else if (selector == @selector(install))
2218 else if (selector == @selector(remove))
2224 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2225 return [self webScriptNameForSelector:selector] == nil;
2228 + (NSArray *) _attributeKeys {
2229 return [NSArray arrayWithObjects:
2250 @"shortDescription",
2262 - (NSArray *) attributeKeys {
2263 return [[self class] _attributeKeys];
2266 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2267 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2270 - (NSArray *) relations {
2271 @synchronized (database_) {
2272 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2273 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2274 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2278 - (NSString *) architecture {
2280 @synchronized (database_) {
2281 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2284 - (NSString *) getField:(NSString *)name {
2285 @synchronized (database_) {
2286 if ([database_ era] != era_ || file_.end())
2289 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2291 const char *start, *end;
2292 if (!parser.Find([name UTF8String], start, end))
2293 return (NSString *) [NSNull null];
2295 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2298 - (NSString *) getRecord {
2299 @synchronized (database_) {
2300 if ([database_ era] != era_ || file_.end())
2303 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2305 const char *start, *end;
2306 parser.GetRec(start, end);
2308 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2312 if (parsed_ != NULL)
2314 @synchronized (database_) {
2315 if ([database_ era] != era_ || file_.end())
2318 ParsedPackage *parsed(new ParsedPackage);
2321 _profile(Package$parse)
2322 pkgRecords::Parser *parser;
2324 _profile(Package$parse$Lookup)
2325 parser = &[database_ records]->Lookup(file_);
2331 _profile(Package$parse$Find)
2336 {"architecture", &parsed->architecture_},
2337 {"icon", &parsed->icon_},
2338 {"depiction", &parsed->depiction_},
2339 {"homepage", &parsed->homepage_},
2340 {"website", &website},
2342 {"support", &parsed->support_},
2343 {"author", &parsed->author_},
2344 {"md5sum", &parsed->md5sum_},
2347 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2348 const char *start, *end;
2350 if (parser->Find(names[i].name_, start, end)) {
2351 CYString &value(*names[i].value_);
2352 _profile(Package$parse$Value)
2353 value.set(pool_, start, end - start);
2359 _profile(Package$parse$Tagline)
2360 const char *start, *end;
2361 if (parser->ShortDesc(start, end)) {
2362 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2365 while (stop != start && stop[-1] == '\r')
2367 parsed->tagline_.set(pool_, start, stop - start);
2371 _profile(Package$parse$Retain)
2372 if (parsed->homepage_.empty())
2373 parsed->homepage_ = website;
2374 if (parsed->homepage_ == parsed->depiction_)
2375 parsed->homepage_.clear();
2376 if (parsed->support_.empty())
2377 parsed->support_ = bugs;
2382 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2383 if ((self = [super init]) != nil) {
2384 _profile(Package$initWithVersion)
2386 apr_pool_create(&pool_, NULL);
2392 database_ = database;
2393 era_ = [database era];
2397 pkgCache::PkgIterator iterator(version.ParentPkg());
2398 iterator_ = iterator;
2400 _profile(Package$initWithVersion$Version)
2401 if (!version_.end())
2402 file_ = version_.FileList();
2404 pkgCache &cache([database_ cache]);
2405 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2409 _profile(Package$initWithVersion$Cache)
2410 name_.set(NULL, iterator.Display());
2412 latest_.set(NULL, StripVersion_(version_.VerStr()));
2414 pkgCache::VerIterator current(iterator.CurrentVer());
2416 installed_.set(NULL, StripVersion_(current.VerStr()));
2419 _profile(Package$initWithVersion$Tags)
2420 pkgCache::TagIterator tag(iterator.TagList());
2422 tags_ = [NSMutableArray arrayWithCapacity:8];
2424 goto tag; for (; !tag.end(); ++tag) tag: {
2425 const char *name(tag.Name());
2426 NSString *string((NSString *) CYStringCreate(name));
2430 [tags_ addObject:[string autorelease]];
2432 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2433 if (strcmp(name + 6, "enduser") == 0)
2435 else if (strcmp(name + 6, "hacker") == 0)
2437 else if (strcmp(name + 6, "developer") == 0)
2439 else if (strcmp(name + 6, "cydia") == 0)
2445 if (strncmp(name, "cydia::", 7) == 0) {
2446 if (strcmp(name + 7, "essential") == 0)
2448 else if (strcmp(name + 7, "obsolete") == 0)
2455 _profile(Package$initWithVersion$Metadata)
2456 const char *mixed(iterator.Name());
2457 size_t size(strlen(mixed));
2458 char lower[size + 1];
2460 for (size_t i(0); i != size; ++i)
2461 lower[i] = mixed[i] | 0x20;
2464 PackageValue *metadata(PackageFind(lower, size));
2465 metadata_ = metadata;
2467 id_.set(NULL, metadata->name_, size);
2469 const char *latest(version_.VerStr());
2470 size_t length(strlen(latest));
2472 uint16_t vhash(hashlittle(latest, length));
2474 size_t capped(std::min<size_t>(8, length));
2475 latest = latest + length - capped;
2477 if (metadata->first_ == 0)
2478 metadata->first_ = now_;
2480 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2481 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2482 metadata->vhash_ = vhash;
2483 metadata->last_ = now_;
2484 } else if (metadata->last_ == 0)
2485 metadata->last_ = metadata->first_;
2488 _profile(Package$initWithVersion$Section)
2489 section_ = version_.Section();
2492 _profile(Package$initWithVersion$Flags)
2493 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2494 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2499 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2500 pkgCache::VerIterator version;
2502 _profile(Package$packageWithIterator$GetCandidateVer)
2503 version = [database policy]->GetCandidateVer(iterator);
2511 _profile(Package$packageWithIterator$Allocate)
2512 package = [Package allocWithZone:zone];
2515 _profile(Package$packageWithIterator$Initialize)
2517 initWithVersion:version
2524 _profile(Package$packageWithIterator$Autorelease)
2525 package = [package autorelease];
2531 - (pkgCache::PkgIterator) iterator {
2535 - (NSString *) section {
2536 if (section$_ == nil) {
2537 if (section_ == NULL)
2540 _profile(Package$section$mappedSectionForPointer)
2541 section$_ = [database_ mappedSectionForPointer:section_];
2546 - (NSString *) simpleSection {
2547 if (NSString *section = [self section])
2548 return Simplify(section);
2553 - (NSString *) longSection {
2554 return LocalizeSection([self section]);
2557 - (NSString *) shortSection {
2558 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2561 - (NSString *) uri {
2564 pkgIndexFile *index;
2565 pkgCache::PkgFileIterator file(file_.File());
2566 if (![database_ list].FindIndex(file, index))
2568 return [NSString stringWithUTF8String:iterator_->Path];
2569 //return [NSString stringWithUTF8String:file.Site()];
2570 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2574 - (MIMEAddress *) maintainer {
2575 @synchronized (database_) {
2576 if ([database_ era] != era_ || file_.end())
2579 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2580 const std::string &maintainer(parser->Maintainer());
2581 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2584 - (NSString *) md5sum {
2585 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2589 @synchronized (database_) {
2590 if ([database_ era] != era_ || version_.end())
2593 return version_->InstalledSize;
2596 - (NSString *) longDescription {
2597 @synchronized (database_) {
2598 if ([database_ era] != era_ || file_.end())
2601 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2602 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2604 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2605 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2606 if ([lines count] < 2)
2609 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2610 for (size_t i(1), e([lines count]); i != e; ++i) {
2611 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2612 [trimmed addObject:trim];
2615 return [trimmed componentsJoinedByString:@"\n"];
2618 - (NSString *) shortDescription {
2619 if (parsed_ != NULL)
2620 return static_cast<NSString *>(parsed_->tagline_);
2622 @synchronized (database_) {
2623 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2625 const char *start, *end;
2626 if (!parser.ShortDesc(start, end))
2629 if (end - start > 200)
2633 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2636 while (end != start && end[-1] == '\r')
2640 return [(id) CYStringCreate(start, end - start) autorelease];
2644 _profile(Package$index)
2645 CFStringRef name((CFStringRef) [self name]);
2646 if (CFStringGetLength(name) == 0)
2648 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2649 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2651 return toupper(character);
2655 - (PackageValue *) metadata {
2660 PackageValue *metadata([self metadata]);
2661 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2664 - (bool) subscribed {
2665 return [self metadata]->subscribed_;
2668 - (bool) setSubscribed:(bool)subscribed {
2669 PackageValue *metadata([self metadata]);
2670 if (metadata->subscribed_ == subscribed)
2672 metadata->subscribed_ = subscribed;
2680 - (NSString *) latest {
2684 - (NSString *) installed {
2688 - (BOOL) uninstalled {
2689 return installed_.empty();
2693 return !version_.end();
2696 - (BOOL) upgradableAndEssential:(BOOL)essential {
2697 _profile(Package$upgradableAndEssential)
2698 pkgCache::VerIterator current(iterator_.CurrentVer());
2700 return essential && essential_;
2702 return !version_.end() && version_ != current;
2706 - (BOOL) essential {
2711 return [database_ cache][iterator_].InstBroken();
2714 - (BOOL) unfiltered {
2715 _profile(Package$unfiltered$obsolete)
2716 if (_unlikely(obsolete_))
2720 _profile(Package$unfiltered$role)
2721 if (_unlikely(role_ > 3))
2729 if (![self unfiltered])
2734 _profile(Package$visible$section)
2735 section = [self section];
2738 _profile(Package$visible$isSectionVisible)
2739 if (!isSectionVisible(section))
2747 unsigned char current(iterator_->CurrentState);
2748 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2751 - (BOOL) halfConfigured {
2752 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2755 - (BOOL) halfInstalled {
2756 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2760 @synchronized (database_) {
2761 if ([database_ era] != era_ || iterator_.end())
2764 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2765 return state.Mode != pkgDepCache::ModeKeep;
2768 - (NSString *) mode {
2769 @synchronized (database_) {
2770 if ([database_ era] != era_ || iterator_.end())
2773 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2775 switch (state.Mode) {
2776 case pkgDepCache::ModeDelete:
2777 if ((state.iFlags & pkgDepCache::Purge) != 0)
2781 case pkgDepCache::ModeKeep:
2782 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2783 return @"REINSTALL";
2784 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2788 case pkgDepCache::ModeInstall:
2789 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2790 return @"REINSTALL";
2791 else*/ switch (state.Status) {
2793 return @"DOWNGRADE";
2799 return @"NEW_INSTALL";
2810 - (NSString *) name {
2811 return name_.empty() ? id_ : name_;
2814 - (UIImage *) icon {
2815 NSString *section = [self simpleSection];
2818 if (parsed_ != NULL)
2819 if (NSString *href = parsed_->icon_)
2820 if ([href hasPrefix:@"file:///"])
2821 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2822 if (icon == nil) if (section != nil)
2823 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2824 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2825 if ([dicon hasPrefix:@"file:///"])
2826 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2828 icon = [UIImage applicationImageNamed:@"unknown.png"];
2832 - (NSString *) homepage {
2833 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2836 - (NSString *) depiction {
2837 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2840 - (MIMEAddress *) author {
2841 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2844 - (NSString *) support {
2845 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
2848 - (NSArray *) files {
2849 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2850 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2853 fin.open([path UTF8String]);
2858 while (std::getline(fin, line))
2859 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2864 - (NSString *) state {
2865 @synchronized (database_) {
2866 if ([database_ era] != era_ || file_.end())
2869 switch (iterator_->CurrentState) {
2870 case pkgCache::State::NotInstalled:
2871 return @"NotInstalled";
2872 case pkgCache::State::UnPacked:
2874 case pkgCache::State::HalfConfigured:
2875 return @"HalfConfigured";
2876 case pkgCache::State::HalfInstalled:
2877 return @"HalfInstalled";
2878 case pkgCache::State::ConfigFiles:
2879 return @"ConfigFiles";
2880 case pkgCache::State::Installed:
2881 return @"Installed";
2882 case pkgCache::State::TriggersAwaited:
2883 return @"TriggersAwaited";
2884 case pkgCache::State::TriggersPending:
2885 return @"TriggersPending";
2888 return (NSString *) [NSNull null];
2891 - (NSString *) selection {
2892 @synchronized (database_) {
2893 if ([database_ era] != era_ || file_.end())
2896 switch (iterator_->SelectedState) {
2897 case pkgCache::State::Unknown:
2899 case pkgCache::State::Install:
2901 case pkgCache::State::Hold:
2903 case pkgCache::State::DeInstall:
2904 return @"DeInstall";
2905 case pkgCache::State::Purge:
2909 return (NSString *) [NSNull null];
2912 - (NSArray *) warnings {
2913 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2914 const char *name(iterator_.Name());
2916 size_t length(strlen(name));
2917 if (length < 2) invalid:
2918 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2919 else for (size_t i(0); i != length; ++i)
2921 /* XXX: technically this is not allowed */
2922 (name[i] < 'A' || name[i] > 'Z') &&
2923 (name[i] < 'a' || name[i] > 'z') &&
2924 (name[i] < '0' || name[i] > '9') &&
2925 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2928 if (strcmp(name, "cydia") != 0) {
2931 bool _private = false;
2934 bool repository = [[self section] isEqualToString:@"Repositories"];
2936 if (NSArray *files = [self files])
2937 for (NSString *file in files)
2938 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2940 else if (!user && [file isEqualToString:@"/User"])
2942 else if (!_private && [file isEqualToString:@"/private"])
2944 else if (!stash && [file isEqualToString:@"/var/stash"])
2947 /* XXX: this is not sensitive enough. only some folders are valid. */
2948 if (cydia && !repository)
2949 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2951 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2953 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2955 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2958 return [warnings count] == 0 ? nil : warnings;
2961 - (NSArray *) applications {
2962 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2964 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2966 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2967 if (NSArray *files = [self files])
2968 for (NSString *file in files)
2969 if (application_r(file)) {
2970 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2971 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2972 if ([id isEqualToString:me])
2975 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2977 display = application_r[1];
2979 NSString *bundle([file stringByDeletingLastPathComponent]);
2980 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2981 // XXX: maybe this should check if this is really a string, not just for length
2982 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
2984 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2986 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2987 [applications addObject:application];
2989 [application addObject:id];
2990 [application addObject:display];
2991 [application addObject:url];
2994 return [applications count] == 0 ? nil : applications;
2997 - (Source *) source {
2998 if (source_ == nil) {
2999 @synchronized (database_) {
3000 if ([database_ era] != era_ || file_.end())
3001 source_ = (Source *) [NSNull null];
3003 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3007 return source_ == (Source *) [NSNull null] ? nil : source_;
3014 - (BOOL) matches:(NSArray *)query {
3015 if (query == nil || [query count] == 0)
3024 string = [self name];
3025 length = [string length];
3027 for (NSString *term in query) {
3028 range = [string rangeOfString:term options:MatchCompareOptions_];
3029 if (range.location != NSNotFound)
3030 rank_ -= 6 * 1000000 / length;
3035 length = [string length];
3037 for (NSString *term in query) {
3038 range = [string rangeOfString:term options:MatchCompareOptions_];
3039 if (range.location != NSNotFound)
3040 rank_ -= 6 * 1000000 / length;
3044 string = [self shortDescription];
3045 length = [string length];
3046 NSUInteger stop(std::min<NSUInteger>(length, 200));
3048 for (NSString *term in query) {
3049 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3050 if (range.location != NSNotFound)
3051 rank_ -= 2 * 100000;
3057 - (NSArray *) tags {
3061 - (BOOL) hasTag:(NSString *)tag {
3062 return tags_ == nil ? NO : [tags_ containsObject:tag];
3065 - (NSString *) primaryPurpose {
3066 for (NSString *tag in (NSArray *) tags_)
3067 if ([tag hasPrefix:@"purpose::"])
3068 return [tag substringFromIndex:9];
3072 - (NSArray *) purposes {
3073 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3074 for (NSString *tag in (NSArray *) tags_)
3075 if ([tag hasPrefix:@"purpose::"])
3076 [purposes addObject:[tag substringFromIndex:9]];
3077 return [purposes count] == 0 ? nil : purposes;
3080 - (bool) isCommercial {
3081 return [self hasTag:@"cydia::commercial"];
3084 - (void) setIndex:(size_t)index {
3085 if (metadata_->index_ != index)
3086 metadata_->index_ = index;
3089 - (CYString &) cyname {
3090 return name_.empty() ? id_ : name_;
3093 - (uint32_t) compareBySection:(NSArray *)sections {
3094 NSString *section([self section]);
3095 for (size_t i(0), e([sections count]); i != e; ++i) {
3096 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3100 return _not(uint32_t);
3104 @synchronized (database_) {
3105 pkgProblemResolver *resolver = [database_ resolver];
3106 resolver->Clear(iterator_);
3108 pkgCacheFile &cache([database_ cache]);
3109 cache->SetReInstall(iterator_, false);
3110 cache->MarkKeep(iterator_, false);
3114 @synchronized (database_) {
3115 pkgProblemResolver *resolver = [database_ resolver];
3116 resolver->Clear(iterator_);
3117 resolver->Protect(iterator_);
3119 pkgCacheFile &cache([database_ cache]);
3120 cache->SetReInstall(iterator_, false);
3121 cache->MarkInstall(iterator_, false);
3123 pkgDepCache::StateCache &state((*cache)[iterator_]);
3124 if (!state.Install())
3125 cache->SetReInstall(iterator_, true);
3129 @synchronized (database_) {
3130 pkgProblemResolver *resolver = [database_ resolver];
3131 resolver->Clear(iterator_);
3132 resolver->Remove(iterator_);
3133 resolver->Protect(iterator_);
3135 pkgCacheFile &cache([database_ cache]);
3136 cache->SetReInstall(iterator_, false);
3137 cache->MarkDelete(iterator_, true);
3140 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3141 _profile(Package$isUnfilteredAndSearchedForBy)
3144 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3145 value &= [self unfiltered];
3148 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3149 value &= [self matches:query];
3156 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3157 if ([search length] == 0)
3160 _profile(Package$isUnfilteredAndSelectedForBy)
3163 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3164 value &= [self unfiltered];
3167 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3168 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3175 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3176 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3179 - (bool) isVisibleInSection:(NSString *)name source:(Source *)source {
3180 NSString *section([self section]);
3184 section == nil && [name length] == 0 ||
3185 [name isEqualToString:section]
3188 [self source] == source
3189 ) && [self visible];
3192 - (bool) isVisibleInSource:(Source *)source {
3193 return [self source] == source && [self visible];
3198 /* Section Class {{{ */
3199 @interface Section : NSObject {
3204 _H<NSString> localized_;
3207 - (NSComparisonResult) compareByLocalized:(Section *)section;
3208 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3209 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3210 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3211 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3212 - (NSString *) name;
3219 - (void) addToCount;
3221 - (void) setCount:(size_t)count;
3222 - (NSString *) localized;
3226 @implementation Section
3228 - (NSComparisonResult) compareByLocalized:(Section *)section {
3229 NSString *lhs(localized_);
3230 NSString *rhs([section localized]);
3232 /*if ([lhs length] != 0 && [rhs length] != 0) {
3233 unichar lhc = [lhs characterAtIndex:0];
3234 unichar rhc = [rhs characterAtIndex:0];
3236 if (isalpha(lhc) && !isalpha(rhc))
3237 return NSOrderedAscending;
3238 else if (!isalpha(lhc) && isalpha(rhc))
3239 return NSOrderedDescending;
3242 return [lhs compare:rhs options:LaxCompareOptions_];
3245 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3246 if ((self = [self initWithName:name localize:NO]) != nil) {
3247 if (localized != nil)
3248 localized_ = localized;
3252 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3253 return [self initWithName:name row:0 localize:localize];
3256 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3257 if ((self = [super init]) != nil) {
3262 localized_ = LocalizeSection(name_);
3266 /* XXX: localize the index thingees */
3267 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3268 if ((self = [super init]) != nil) {
3269 name_ = [NSString stringWithCharacters:&index length:1];
3275 - (NSString *) name {
3295 - (void) addToCount {
3299 - (void) setCount:(size_t)count {
3303 - (NSString *) localized {
3310 class CydiaLogCleaner :
3311 public pkgArchiveCleaner
3314 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3319 /* Database Implementation {{{ */
3320 @implementation Database
3322 + (Database *) sharedInstance {
3323 static _H<Database> instance;
3324 if (instance == nil)
3325 instance = [[[Database alloc] init] autorelease];
3333 - (void) releasePackages {
3334 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3335 CFArrayRemoveAllValues(packages_);
3339 // XXX: actually implement this thing
3341 [self releasePackages];
3342 apr_pool_destroy(pool_);
3343 NSRecycleZone(zone_);
3347 - (void) _readCydia:(NSNumber *)fd {
3348 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3349 std::istream is(&ib);
3352 static Pcre finish_r("^finish:([^:]*)$");
3354 while (std::getline(is, line)) {
3355 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3357 const char *data(line.c_str());
3358 size_t size = line.size();
3359 lprintf("C:%s\n", data);
3361 if (finish_r(data, size)) {
3362 NSString *finish = finish_r[1];
3363 int index = [Finishes_ indexOfObject:finish];
3364 if (index != INT_MAX && index > Finish_)
3374 - (void) _readStatus:(NSNumber *)fd {
3375 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3376 std::istream is(&ib);
3379 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3380 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3382 while (std::getline(is, line)) {
3383 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3385 const char *data(line.c_str());
3386 size_t size(line.size());
3387 lprintf("S:%s\n", data);
3389 if (conffile_r(data, size)) {
3390 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3391 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3392 } else if (strncmp(data, "status: ", 8) == 0) {
3393 // status: <package>: {unpacked,half-configured,installed}
3394 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3395 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3396 } else if (strncmp(data, "processing: ", 12) == 0) {
3397 // processing: configure: config-test
3398 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3399 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3400 } else if (pmstatus_r(data, size)) {
3401 std::string type([pmstatus_r[1] UTF8String]);
3403 NSString *package = pmstatus_r[2];
3404 if ([package isEqualToString:@"dpkg-exec"])
3407 float percent([pmstatus_r[3] floatValue]);
3408 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3410 NSString *string = pmstatus_r[4];
3412 if (type == "pmerror") {
3413 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3414 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3415 } else if (type == "pmstatus") {
3416 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3417 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3418 } else if (type == "pmconffile")
3419 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3421 lprintf("E:unknown pmstatus\n");
3423 lprintf("E:unknown status\n");
3431 - (void) _readOutput:(NSNumber *)fd {
3432 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3433 std::istream is(&ib);
3436 while (std::getline(is, line)) {
3437 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3439 lprintf("O:%s\n", line.c_str());
3441 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3442 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3454 - (Package *) packageWithName:(NSString *)name {
3457 @synchronized (self) {
3458 if (static_cast<pkgDepCache *>(cache_) == NULL)
3460 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3461 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3465 if ((self = [super init]) != nil) {
3472 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3473 apr_pool_create(&pool_, NULL);
3475 size_t capacity(MetaFile_->active_);
3481 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3482 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3486 _assert(pipe(fds) != -1);
3489 _config->Set("APT::Keep-Fds::", cydiafd_);
3490 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3493 detachNewThreadSelector:@selector(_readCydia:)
3495 withObject:[NSNumber numberWithInt:fds[0]]
3498 _assert(pipe(fds) != -1);
3502 detachNewThreadSelector:@selector(_readStatus:)
3504 withObject:[NSNumber numberWithInt:fds[0]]
3507 _assert(pipe(fds) != -1);
3508 _assert(dup2(fds[0], 0) != -1);
3509 _assert(close(fds[0]) != -1);
3511 input_ = fdopen(fds[1], "a");
3513 _assert(pipe(fds) != -1);
3514 _assert(dup2(fds[1], 1) != -1);
3515 _assert(close(fds[1]) != -1);
3518 detachNewThreadSelector:@selector(_readOutput:)
3520 withObject:[NSNumber numberWithInt:fds[0]]
3525 - (pkgCacheFile &) cache {
3529 - (pkgDepCache::Policy *) policy {
3533 - (pkgRecords *) records {
3537 - (pkgProblemResolver *) resolver {
3541 - (pkgAcquire &) fetcher {
3545 - (pkgSourceList &) list {
3549 - (NSArray *) packages {
3550 return (NSArray *) packages_;
3553 - (NSArray *) sources {
3557 - (Source *) sourceWithKey:(NSString *)key {
3558 for (Source *source in [self sources]) {
3559 if ([[source key] isEqualToString:key])
3564 - (bool) popErrorWithTitle:(NSString *)title {
3567 while (!_error->empty()) {
3569 bool warning(!_error->PopMessage(error));
3574 size_t size(error.size());
3575 if (size == 0 || error[size - 1] != '\n')
3577 error.resize(size - 1);
3580 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3582 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3583 if (warning && no_pubkey(error.c_str()))
3586 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3592 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3593 return [self popErrorWithTitle:title] || !success;
3596 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3597 @synchronized (self) {
3600 [self releasePackages];
3603 [sourceList_ removeAllObjects];
3623 apr_pool_clear(pool_);
3625 NSRecycleZone(zone_);
3626 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3628 int chk(creat("/tmp/cydia.chk", 0644));
3632 if (invocation != nil)
3633 [invocation invoke];
3635 NSString *title(UCLocalize("DATABASE"));
3637 list_ = new pkgSourceList();
3638 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3641 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3642 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3643 [sourceList_ addObject:object];
3647 OpProgress progress;
3649 if (!cache_.Open(progress, true)) {
3650 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3651 while (!_error->empty()) {
3653 bool warning(!_error->PopMessage(error));
3655 lprintf("cache_.Open():[%s]\n", error.c_str());
3657 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3661 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3662 repair = @selector(configure);
3663 //else if (error == "The package lists or status file could not be parsed or opened.")
3664 // repair = @selector(update);
3665 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3666 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3667 // else if (error == "Malformed Status line")
3668 // else if (error == "The list of sources could not be read.")
3670 if (repair != NULL) {
3672 [delegate_ repairWithSelector:repair];
3681 unlink("/tmp/cydia.chk");
3683 now_ = [[NSDate date] timeIntervalSince1970];
3685 policy_ = new pkgDepCache::Policy();
3686 records_ = new pkgRecords(cache_);
3687 resolver_ = new pkgProblemResolver(cache_);
3688 fetcher_ = new pkgAcquire(&status_);
3691 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3692 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3696 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3699 if (cache_->BrokenCount() != 0) {
3700 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3703 if (cache_->BrokenCount() != 0) {
3704 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3708 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3712 for (Source *object in (id) sourceList_) {
3713 metaIndex *source([object metaIndex]);
3714 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3715 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3716 // XXX: this could be more intelligent
3717 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3718 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3720 sourceMap_[cached->ID] = object;
3725 /*std::vector<Package *> packages;
3726 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3731 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3732 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3733 //packages.push_back(package);
3734 CFArrayAppendValue(packages_, CFRetain(package));
3738 /*if (packages.empty())
3739 packages_ = [[NSArray alloc] init];
3741 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3744 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3745 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3746 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3754 /*if (!packages.empty())
3755 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3756 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3758 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3760 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3762 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3766 size_t count(CFArrayGetCount(packages_));
3767 MetaFile_->active_ = count;
3769 for (size_t index(0); index != count; ++index)
3770 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3777 @synchronized (self) {
3779 resolver_ = new pkgProblemResolver(cache_);
3781 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3782 if (!cache_[iterator].Keep())
3783 cache_->MarkKeep(iterator, false);
3784 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3785 cache_->SetReInstall(iterator, false);
3788 - (void) configure {
3789 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3791 system([dpkg UTF8String]);
3796 @synchronized (self) {
3797 // XXX: I don't remember this condition
3802 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3804 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3806 if ([self popErrorWithTitle:title])
3810 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3812 CydiaLogCleaner cleaner;
3813 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3820 fetcher_->Shutdown();
3822 pkgRecords records(cache_);
3824 lock_ = new FileFd();
3825 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3827 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3829 if ([self popErrorWithTitle:title])
3833 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3836 manager_ = (_system->CreatePM(cache_));
3837 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3844 bool substrate(RestartSubstrate_);
3845 RestartSubstrate_ = false;
3847 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3849 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3851 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3853 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3854 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3857 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3859 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3861 [self popErrorWithTitle:title];
3865 bool failed = false;
3866 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3867 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3869 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3872 std::string uri = (*item)->DescURI();
3873 std::string error = (*item)->ErrorText;
3875 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3878 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3879 [delegate_ addProgressEventOnMainThread:event forTask:title];
3882 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3890 RestartSubstrate_ = true;
3893 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3894 if ([self popErrorWithTitle:title])
3897 if (result == pkgPackageManager::Failed) {
3902 if (result != pkgPackageManager::Completed) {
3907 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3909 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3911 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3912 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3915 if (![before isEqualToArray:after])
3920 NSString *title(UCLocalize("UPGRADE"));
3921 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3927 [self updateWithStatus:status_];
3930 - (void) updateWithStatus:(CancelStatus &)status {
3931 NSString *title(UCLocalize("REFRESHING_DATA"));
3934 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3938 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3939 if ([self popErrorWithTitle:title])
3942 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3944 bool success(ListUpdate(status, list, PulseInterval_));
3945 if (status.WasCancelled())
3948 [self popErrorWithTitle:title forOperation:success];
3949 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3953 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3956 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3957 delegate_ = delegate;
3960 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3961 progress_ = delegate;
3962 status_.setDelegate(delegate);
3965 - (NSObject<ProgressDelegate> *) progressDelegate {
3969 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3970 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3971 return i == sourceMap_.end() ? nil : i->second;
3974 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
3975 for (Source *source in (id) sourceList_)
3976 [source setFetch:fetch forURI:uri];
3979 - (void) resetFetch {
3980 for (Source *source in (id) sourceList_)
3981 [source resetFetch];
3984 - (NSString *) mappedSectionForPointer:(const char *)section {
3985 _H<NSString> *mapped;
3987 _profile(Database$mappedSectionForPointer$Cache)
3988 mapped = §ions_[section];
3991 if (*mapped == NULL) {
3992 size_t length(strlen(section));
3993 char spaced[length + 1];
3995 _profile(Database$mappedSectionForPointer$Replace)
3996 for (size_t index(0); index != length; ++index)
3997 spaced[index] = section[index] == '_' ? ' ' : section[index];
3998 spaced[length] = '\0';
4003 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4004 string = [NSString stringWithUTF8String:spaced];
4007 _profile(Database$mappedSectionForPointer$Map)
4008 string = [SectionMap_ objectForKey:string] ?: string;
4018 static _H<NSMutableSet> Diversions_;
4020 @interface Diversion : NSObject {
4023 _H<NSString> format_;
4028 @implementation Diversion
4030 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4031 if ((self = [super init]) != nil) {
4032 pattern_ = [from UTF8String];
4038 - (NSString *) divert:(NSString *)url {
4039 return !pattern_(url) ? nil : pattern_->*format_;
4042 + (NSURL *) divertURL:(NSURL *)url {
4044 NSString *href([url absoluteString]);
4046 for (Diversion *diversion in (id) Diversions_)
4047 if (NSString *diverted = [diversion divert:href]) {
4049 NSLog(@"div: %@", diverted);
4051 url = [NSURL URLWithString:diverted];
4058 - (NSString *) key {
4062 - (NSUInteger) hash {
4066 - (BOOL) isEqual:(Diversion *)object {
4067 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4072 @interface CydiaObject : NSObject {
4073 _H<CyteWebViewController> indirect_;
4074 _transient id delegate_;
4077 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4083 @interface CydiaWebViewController : CyteWebViewController {
4084 _H<CydiaObject> cydia_;
4087 + (void) addDiversion:(Diversion *)diversion;
4088 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4089 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4090 - (void) setDelegate:(id)delegate;
4094 /* Web Scripting {{{ */
4095 @implementation CydiaObject
4097 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4098 if ((self = [super init]) != nil) {
4099 indirect_ = (CyteWebViewController *) indirect;
4103 - (void) setDelegate:(id)delegate {
4104 delegate_ = delegate;
4107 + (NSArray *) _attributeKeys {
4108 return [NSArray arrayWithObjects:
4111 @"coreFoundationVersionNumber",
4128 - (NSArray *) attributeKeys {
4129 return [[self class] _attributeKeys];
4132 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4133 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4136 - (NSString *) version {
4140 - (NSString *) build {
4144 - (NSString *) coreFoundationVersionNumber {
4145 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4148 - (NSString *) device {
4149 return UniqueIdentifier();
4152 - (NSString *) firmware {
4153 return [[UIDevice currentDevice] systemVersion];
4156 - (NSString *) hostname {
4157 return [[UIDevice currentDevice] name];
4160 - (NSString *) idiom {
4161 return (id) Idiom_ ?: [NSNull null];
4164 - (NSString *) mcc {
4165 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4166 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4170 - (NSString *) mnc {
4171 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4172 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4176 - (NSString *) operator {
4177 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4178 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4182 - (NSString *) bbsnum {
4183 return (id) BBSNum_ ?: [NSNull null];
4186 - (NSString *) ecid {
4187 return (id) ChipID_ ?: [NSNull null];
4190 - (NSString *) serial {
4191 return SerialNumber_;
4194 - (NSString *) role {
4195 return (id) [NSNull null];
4198 - (NSString *) model {
4199 return [NSString stringWithUTF8String:Machine_];
4202 - (NSString *) token {
4203 return (id) Token_ ?: [NSNull null];
4206 + (NSString *) webScriptNameForSelector:(SEL)selector {
4208 else if (selector == @selector(addBridgedHost:))
4209 return @"addBridgedHost";
4210 else if (selector == @selector(addInsecureHost:))
4211 return @"addInsecureHost";
4212 else if (selector == @selector(addInternalRedirect::))
4213 return @"addInternalRedirect";
4214 else if (selector == @selector(addPipelinedHost:scheme:))
4215 return @"addPipelinedHost";
4216 else if (selector == @selector(addSource:::))
4217 return @"addSource";
4218 else if (selector == @selector(addTokenHost:))
4219 return @"addTokenHost";
4220 else if (selector == @selector(addTrivialSource:))
4221 return @"addTrivialSource";
4222 else if (selector == @selector(close))
4224 else if (selector == @selector(du:))
4226 else if (selector == @selector(stringWithFormat:arguments:))
4228 else if (selector == @selector(getAllSources))
4229 return @"getAllSources";
4230 else if (selector == @selector(getApplicationInfo:value:))
4231 return @"getApplicationInfoValue";
4232 else if (selector == @selector(getKernelNumber:))
4233 return @"getKernelNumber";
4234 else if (selector == @selector(getKernelString:))
4235 return @"getKernelString";
4236 else if (selector == @selector(getInstalledPackages))
4237 return @"getInstalledPackages";
4238 else if (selector == @selector(getIORegistryEntry::))
4239 return @"getIORegistryEntry";
4240 else if (selector == @selector(getLocaleIdentifier))
4241 return @"getLocaleIdentifier";
4242 else if (selector == @selector(getPreferredLanguages))
4243 return @"getPreferredLanguages";
4244 else if (selector == @selector(getPackageById:))
4245 return @"getPackageById";
4246 else if (selector == @selector(getMetadataKeys))
4247 return @"getMetadataKeys";
4248 else if (selector == @selector(getMetadataValue:))
4249 return @"getMetadataValue";
4250 else if (selector == @selector(getSessionValue:))
4251 return @"getSessionValue";
4252 else if (selector == @selector(installPackages:))
4253 return @"installPackages";
4254 else if (selector == @selector(isReachable:))
4255 return @"isReachable";
4256 else if (selector == @selector(localizedStringForKey:value:table:))
4258 else if (selector == @selector(popViewController:))
4259 return @"popViewController";
4260 else if (selector == @selector(refreshSources))
4261 return @"refreshSources";
4262 else if (selector == @selector(registerFrame:))
4263 return @"registerFrame";
4264 else if (selector == @selector(removeButton))
4265 return @"removeButton";
4266 else if (selector == @selector(saveConfig))
4267 return @"saveConfig";
4268 else if (selector == @selector(setMetadataValue::))
4269 return @"setMetadataValue";
4270 else if (selector == @selector(setSessionValue::))
4271 return @"setSessionValue";
4272 else if (selector == @selector(substitutePackageNames:))
4273 return @"substitutePackageNames";
4274 else if (selector == @selector(scrollToBottom:))
4275 return @"scrollToBottom";
4276 else if (selector == @selector(setAllowsNavigationAction:))
4277 return @"setAllowsNavigationAction";
4278 else if (selector == @selector(setBadgeValue:))
4279 return @"setBadgeValue";
4280 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4281 return @"setButtonImage";
4282 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4283 return @"setButtonTitle";
4284 else if (selector == @selector(setHidesBackButton:))
4285 return @"setHidesBackButton";
4286 else if (selector == @selector(setHidesNavigationBar:))
4287 return @"setHidesNavigationBar";
4288 else if (selector == @selector(setNavigationBarStyle:))
4289 return @"setNavigationBarStyle";
4290 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4291 return @"setNavigationBarTintColor";
4292 else if (selector == @selector(setPasteboardString:))
4293 return @"setPasteboardString";
4294 else if (selector == @selector(setPasteboardURL:))
4295 return @"setPasteboardURL";
4296 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4297 return @"setScrollAlwaysBounceVertical";
4298 else if (selector == @selector(setScrollIndicatorStyle:))
4299 return @"setScrollIndicatorStyle";
4300 else if (selector == @selector(setToken:))
4302 else if (selector == @selector(setViewportWidth:))
4303 return @"setViewportWidth";
4304 else if (selector == @selector(statfs:))
4306 else if (selector == @selector(supports:))
4308 else if (selector == @selector(unload))
4314 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4315 return [self webScriptNameForSelector:selector] == nil;
4318 - (BOOL) supports:(NSString *)feature {
4319 return [feature isEqualToString:@"window.open"];
4323 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4326 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4327 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4330 - (void) setScrollIndicatorStyle:(NSString *)style {
4331 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4334 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4335 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4338 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4340 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4341 return (id) [NSNull null];
4342 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4344 return (id) [NSNull null];
4345 return [info objectForKey:key];
4348 - (NSNumber *) getKernelNumber:(NSString *)name {
4349 const char *string([name UTF8String]);
4352 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4353 return (id) [NSNull null];
4355 if (size != sizeof(int))
4356 return (id) [NSNull null];
4359 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4360 return (id) [NSNull null];
4362 return [NSNumber numberWithInt:value];
4365 - (NSString *) getKernelString:(NSString *)name {
4366 const char *string([name UTF8String]);
4369 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4370 return (id) [NSNull null];
4372 char value[size + 1];
4373 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4374 return (id) [NSNull null];
4376 // XXX: just in case you request something ludicrous
4379 return [NSString stringWithCString:value];
4382 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4383 NSObject *value(CYIOGetValue([path UTF8String], entry));
4386 if ([value isKindOfClass:[NSData class]])
4387 value = CYHex((NSData *) value);
4392 - (NSArray *) getMetadataKeys {
4393 @synchronized (Values_) {
4394 return [Values_ allKeys];
4397 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4398 WebFrame *frame([iframe contentFrame]);
4399 [indirect_ registerFrame:frame];
4402 - (id) getMetadataValue:(NSString *)key {
4403 @synchronized (Values_) {
4404 return [Values_ objectForKey:key];
4407 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4408 @synchronized (Values_) {
4409 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4410 [Values_ removeObjectForKey:key];
4412 [Values_ setObject:value forKey:key];
4414 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4417 - (id) getSessionValue:(NSString *)key {
4418 @synchronized (SessionData_) {
4419 return [SessionData_ objectForKey:key];
4422 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4423 @synchronized (SessionData_) {
4424 if (value == (id) [WebUndefined undefined])
4425 [SessionData_ removeObjectForKey:key];
4427 [SessionData_ setObject:value forKey:key];
4430 - (void) addBridgedHost:(NSString *)host {
4431 @synchronized (HostConfig_) {
4432 [BridgedHosts_ addObject:host];
4435 - (void) addInsecureHost:(NSString *)host {
4436 @synchronized (HostConfig_) {
4437 [InsecureHosts_ addObject:host];
4440 - (void) addTokenHost:(NSString *)host {
4441 @synchronized (HostConfig_) {
4442 [TokenHosts_ addObject:host];
4445 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4446 @synchronized (HostConfig_) {
4447 if (scheme != (id) [WebUndefined undefined])
4448 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4450 [PipelinedHosts_ addObject:host];
4453 - (void) popViewController:(NSNumber *)value {
4454 if (value == (id) [WebUndefined undefined])
4455 value = [NSNumber numberWithBool:YES];
4456 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4459 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4460 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4462 for (NSString *section in sections)
4463 [array addObject:section];
4465 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4468 distribution, @"Distribution",
4470 nil] waitUntilDone:NO];
4473 - (void) addTrivialSource:(NSString *)href {
4474 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4477 - (void) refreshSources {
4478 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4481 - (void) saveConfig {
4482 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4485 - (NSArray *) getAllSources {
4486 return [[Database sharedInstance] sources];
4489 - (NSArray *) getInstalledPackages {
4490 Database *database([Database sharedInstance]);
4491 @synchronized (database) {
4492 NSArray *packages([database packages]);
4493 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4494 for (Package *package in packages)
4495 if (![package uninstalled])
4496 [installed addObject:package];
4500 - (Package *) getPackageById:(NSString *)id {
4501 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4505 return (Package *) [NSNull null];
4508 - (NSString *) getLocaleIdentifier {
4509 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4512 - (NSArray *) getPreferredLanguages {
4516 - (NSArray *) statfs:(NSString *)path {
4519 if (path == nil || statfs([path UTF8String], &stat) == -1)
4522 return [NSArray arrayWithObjects:
4523 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4524 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4525 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4529 - (NSNumber *) du:(NSString *)path {
4530 NSNumber *value(nil);
4533 _assert(pipe(fds) != -1);
4535 pid_t pid(ExecFork());
4537 _assert(dup2(fds[1], 1) != -1);
4538 _assert(close(fds[0]) != -1);
4539 _assert(close(fds[1]) != -1);
4540 /* XXX: this should probably not use du */
4541 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4544 _assert(close(fds[1]) != -1);
4546 if (FILE *du = fdopen(fds[0], "r")) {
4548 while (fgets(line, sizeof(line), du) != NULL) {
4549 size_t length(strlen(line));
4550 while (length != 0 && line[length - 1] == '\n')
4551 line[--length] = '\0';
4552 if (char *tab = strchr(line, '\t')) {
4554 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4560 _assert(close(fds[0]) != -1);
4567 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4570 - (NSNumber *) isReachable:(NSString *)name {
4571 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4574 - (void) installPackages:(NSArray *)packages {
4575 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4578 - (NSString *) substitutePackageNames:(NSString *)message {
4579 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4580 for (size_t i(0), e([words count]); i != e; ++i) {
4581 NSString *word([words objectAtIndex:i]);
4582 if (Package *package = [[Database sharedInstance] packageWithName:word])
4583 [words replaceObjectAtIndex:i withObject:[package name]];
4586 return [words componentsJoinedByString:@" "];
4589 - (void) removeButton {
4590 [indirect_ removeButton];
4593 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4594 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4597 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4598 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4601 - (void) setBadgeValue:(id)value {
4602 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4605 - (void) setAllowsNavigationAction:(NSString *)value {
4606 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4609 - (void) setHidesBackButton:(NSString *)value {
4610 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4613 - (void) setHidesNavigationBar:(NSString *)value {
4614 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4617 - (void) setNavigationBarStyle:(NSString *)value {
4618 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4621 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4622 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4623 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4624 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4627 - (void) setPasteboardString:(NSString *)value {
4628 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4631 - (void) setPasteboardURL:(NSString *)value {
4632 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4635 - (void) _setToken:(NSString *)token {
4639 [Metadata_ removeObjectForKey:@"Token"];
4641 [Metadata_ setObject:Token_ forKey:@"Token"];
4646 - (void) setToken:(NSString *)token {
4647 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4650 - (void) scrollToBottom:(NSNumber *)animated {
4651 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4654 - (void) setViewportWidth:(float)width {
4655 [indirect_ setViewportWidthOnMainThread:width];
4658 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4659 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4660 unsigned count([arguments count]);
4662 for (unsigned i(0); i != count; ++i)
4663 values[i] = [arguments objectAtIndex:i];
4664 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4667 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4668 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4670 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4672 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4678 @interface NSURL (CydiaSecure)
4681 @implementation NSURL (CydiaSecure)
4683 - (bool) isCydiaSecure {
4684 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4687 @synchronized (HostConfig_) {
4688 if ([InsecureHosts_ containsObject:[self host]])
4697 /* Cydia Browser Controller {{{ */
4698 @implementation CydiaWebViewController
4700 - (NSURL *) navigationURL {
4701 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4704 + (void) _initialize {
4705 [super _initialize];
4707 Diversions_ = [NSMutableSet setWithCapacity:0];
4710 + (void) addDiversion:(Diversion *)diversion {
4711 [Diversions_ addObject:diversion];
4714 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4715 [super webView:view didClearWindowObject:window forFrame:frame];
4716 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4719 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4720 WebDataSource *source([frame dataSource]);
4721 NSURLResponse *response([source response]);
4722 NSURL *url([response URL]);
4723 NSString *scheme([[url scheme] lowercaseString]);
4725 bool bridged(false);
4727 @synchronized (HostConfig_) {
4728 if ([scheme isEqualToString:@"file"])
4730 else if ([scheme isEqualToString:@"https"])
4731 if ([BridgedHosts_ containsObject:[url host]])
4736 [window setValue:cydia forKey:@"cydia"];
4739 - (void) _setupMail:(MFMailComposeViewController *)controller {
4740 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4742 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4743 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4746 - (NSURL *) URLWithURL:(NSURL *)url {
4747 return [Diversion divertURL:url];
4750 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4751 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4754 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4755 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4757 NSURL *url([copy URL]);
4758 NSString *href([url absoluteString]);
4759 NSString *host([url host]);
4761 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4762 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4763 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4764 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4767 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4768 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4770 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4774 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4775 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4776 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4777 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4782 @synchronized (HostConfig_) {
4783 bridged = [BridgedHosts_ containsObject:host];
4784 token = [TokenHosts_ containsObject:host];
4787 if ([url isCydiaSecure]) {
4789 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4790 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4792 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4793 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4800 - (void) setDelegate:(id)delegate {
4801 [super setDelegate:delegate];
4802 [cydia_ setDelegate:delegate];
4805 - (NSString *) applicationNameForUserAgent {
4810 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4811 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4817 @interface AppCacheController : CydiaWebViewController {
4822 @implementation AppCacheController
4824 - (void) didReceiveMemoryWarning {
4825 // XXX: this doesn't work
4828 - (bool) retainsNetworkActivityIndicator {
4836 @interface NSObject (CydiaScript)
4837 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4840 @implementation NSObject (CydiaScript)
4842 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4848 @implementation NSArray (CydiaScript)
4850 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4851 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4852 for (size_t i(0), e([self count]); i != e; ++i)
4853 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4859 @implementation NSDictionary (CydiaScript)
4861 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4862 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4864 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4871 /* Confirmation Controller {{{ */
4872 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4873 if (!iterator.end())
4874 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4875 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4877 pkgCache::PkgIterator package(dep.TargetPkg());
4880 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4887 @protocol ConfirmationControllerDelegate
4888 - (void) cancelAndClear:(bool)clear;
4889 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4893 @interface ConfirmationController : CydiaWebViewController {
4894 _transient Database *database_;
4896 _H<UIAlertView> essential_;
4898 _H<NSDictionary> changes_;
4899 _H<NSMutableArray> issues_;
4900 _H<NSDictionary> sizes_;
4905 - (id) initWithDatabase:(Database *)database;
4909 @implementation ConfirmationController
4913 RestartSubstrate_ = true;
4914 [delegate_ confirmWithNavigationController:[self navigationController]];
4917 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4918 NSString *context([alert context]);
4920 if ([context isEqualToString:@"remove"]) {
4921 if (button == [alert cancelButtonIndex])
4922 [self dismissModalViewControllerAnimated:YES];
4923 else if (button == [alert firstOtherButtonIndex]) {
4924 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
4927 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4928 } else if ([context isEqualToString:@"unable"]) {
4929 [self dismissModalViewControllerAnimated:YES];
4930 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4932 [super alertView:alert clickedButtonAtIndex:button];
4936 - (void) _doContinue {
4937 [delegate_ cancelAndClear:NO];
4938 [self dismissModalViewControllerAnimated:YES];
4941 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4942 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4946 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4947 [super webView:view didClearWindowObject:window forFrame:frame];
4949 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4950 (id) changes_, @"changes",
4951 (id) issues_, @"issues",
4952 (id) sizes_, @"sizes",
4954 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4957 - (id) initWithDatabase:(Database *)database {
4958 if ((self = [super init]) != nil) {
4959 database_ = database;
4961 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4962 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4963 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4964 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4965 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4969 pkgCacheFile &cache([database_ cache]);
4970 NSArray *packages([database_ packages]);
4971 pkgDepCache::Policy *policy([database_ policy]);
4973 issues_ = [NSMutableArray arrayWithCapacity:4];
4975 for (Package *package in packages) {
4976 pkgCache::PkgIterator iterator([package iterator]);
4977 NSString *name([package id]);
4979 if ([package broken]) {
4980 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4982 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4984 reasons, @"reasons",
4987 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4991 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4992 pkgCache::DepIterator start;
4993 pkgCache::DepIterator end;
4994 dep.GlobOr(start, end); // ++dep
4996 if (!cache->IsImportantDep(end))
4998 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5001 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5003 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5004 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5005 clauses, @"clauses",
5009 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5011 pkgCache::PkgIterator target(start.TargetPkg());
5012 if (target->ProvidesList != 0)
5013 reason = @"missing";
5015 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5017 reason = @"installed";
5018 installed = [NSString stringWithUTF8String:ver.VerStr()];
5019 } else if (!cache[target].CandidateVerIter(cache).end())
5020 reason = @"uninstalled";
5021 else if (target->ProvidesList == 0)
5022 reason = @"uninstallable";
5024 reason = @"virtual";
5027 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5028 [NSString stringWithUTF8String:start.CompType()], @"operator",
5029 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5032 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5033 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5034 version, @"version",
5036 installed, @"installed",
5039 // yes, seriously. (wtf?)
5047 pkgDepCache::StateCache &state(cache[iterator]);
5049 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
5051 if (state.NewInstall())
5052 [installs addObject:name];
5053 // XXX: else if (state.Install())
5054 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5055 [reinstalls addObject:name];
5056 // XXX: move before previous if
5057 else if (state.Upgrade())
5058 [upgrades addObject:name];
5059 else if (state.Downgrade())
5060 [downgrades addObject:name];
5061 else if (!state.Delete())
5062 // XXX: _assert(state.Keep());
5064 else if (special_r(name))
5065 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5066 [NSNull null], @"package",
5067 [NSArray arrayWithObjects:
5068 [NSDictionary dictionaryWithObjectsAndKeys:
5069 @"Conflicts", @"relationship",
5070 [NSArray arrayWithObjects:
5071 [NSDictionary dictionaryWithObjectsAndKeys:
5073 [NSNull null], @"version",
5074 @"installed", @"reason",
5081 if ([package essential])
5083 [removes addObject:name];
5086 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5087 substrate_ |= DepSubstrate(iterator.CurrentVer());
5092 else if (Advanced_) {
5093 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5095 essential_ = [[[UIAlertView alloc]
5096 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5097 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5099 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5101 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5105 [essential_ setContext:@"remove"];
5106 [essential_ setNumberOfRows:2];
5108 essential_ = [[[UIAlertView alloc]
5109 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5110 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5112 cancelButtonTitle:UCLocalize("OKAY")
5113 otherButtonTitles:nil
5116 [essential_ setContext:@"unable"];
5119 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5120 installs, @"installs",
5121 reinstalls, @"reinstalls",
5122 upgrades, @"upgrades",
5123 downgrades, @"downgrades",
5124 removes, @"removes",
5127 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5128 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5129 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5132 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5136 - (UIBarButtonItem *) leftButton {
5137 return [[[UIBarButtonItem alloc]
5138 initWithTitle:UCLocalize("CANCEL")
5139 style:UIBarButtonItemStylePlain
5141 action:@selector(cancelButtonClicked)
5146 - (void) applyRightButton {
5147 if ([issues_ count] == 0 && ![self isLoading])
5148 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5149 initWithTitle:UCLocalize("CONFIRM")
5150 style:UIBarButtonItemStyleDone
5152 action:@selector(confirmButtonClicked)
5155 [[self navigationItem] setRightBarButtonItem:nil];
5159 - (void) cancelButtonClicked {
5160 [delegate_ cancelAndClear:YES];
5161 [self dismissModalViewControllerAnimated:YES];
5165 - (void) confirmButtonClicked {
5166 if (essential_ != nil)
5176 /* Progress Data {{{ */
5177 @interface CydiaProgressData : NSObject {
5178 _transient id delegate_;
5187 _H<NSMutableArray> events_;
5188 _H<NSString> title_;
5190 _H<NSString> status_;
5191 _H<NSString> finish_;
5196 @implementation CydiaProgressData
5198 + (NSArray *) _attributeKeys {
5199 return [NSArray arrayWithObjects:
5211 - (NSArray *) attributeKeys {
5212 return [[self class] _attributeKeys];
5215 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5216 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5220 if ((self = [super init]) != nil) {
5221 events_ = [NSMutableArray arrayWithCapacity:32];
5229 - (void) setDelegate:(id)delegate {
5230 delegate_ = delegate;
5233 - (void) setPercent:(float)value {
5237 - (NSNumber *) percent {
5238 return [NSNumber numberWithFloat:percent_];
5241 - (void) setCurrent:(float)value {
5245 - (NSNumber *) current {
5246 return [NSNumber numberWithFloat:current_];
5249 - (void) setTotal:(float)value {
5253 - (NSNumber *) total {
5254 return [NSNumber numberWithFloat:total_];
5257 - (void) setSpeed:(float)value {
5261 - (NSNumber *) speed {
5262 return [NSNumber numberWithFloat:speed_];
5265 - (NSArray *) events {
5269 - (void) removeAllEvents {
5270 [events_ removeAllObjects];
5273 - (void) addEvent:(CydiaProgressEvent *)event {
5274 [events_ addObject:event];
5277 - (void) setTitle:(NSString *)text {
5281 - (NSString *) title {
5285 - (void) setFinish:(NSString *)text {
5289 - (NSString *) finish {
5290 return (id) finish_ ?: [NSNull null];
5293 - (void) setRunning:(bool)running {
5297 - (NSNumber *) running {
5298 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5303 /* Progress Controller {{{ */
5304 @interface ProgressController : CydiaWebViewController <
5307 _transient Database *database_;
5308 _H<CydiaProgressData, 1> progress_;
5312 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5314 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5316 - (void) setTitle:(NSString *)title;
5317 - (void) setCancellable:(bool)cancellable;
5321 @implementation ProgressController
5324 [database_ setProgressDelegate:nil];
5328 - (UIBarButtonItem *) leftButton {
5329 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5330 initWithTitle:UCLocalize("CANCEL")
5331 style:UIBarButtonItemStylePlain
5333 action:@selector(cancel)
5334 ] autorelease] : nil;
5337 - (void) updateCancel {
5338 [super applyLeftButton];
5341 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5342 if ((self = [super init]) != nil) {
5343 database_ = database;
5344 delegate_ = delegate;
5346 [database_ setProgressDelegate:self];
5348 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5349 [progress_ setDelegate:self];
5351 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5353 [scroller_ setBackgroundColor:[UIColor blackColor]];
5355 [[self navigationItem] setHidesBackButton:YES];
5357 [self updateCancel];
5361 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5362 [super webView:view didClearWindowObject:window forFrame:frame];
5363 [window setValue:progress_ forKey:@"cydiaProgress"];
5366 - (void) updateProgress {
5367 [self dispatchEvent:@"CydiaProgressUpdate"];
5370 - (void) viewWillAppear:(BOOL)animated {
5371 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5372 [super viewWillAppear:animated];
5375 - (void) reloadSpringBoard {
5376 if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
5377 system("/bin/launchctl stop com.apple.backboardd");
5379 system("/usr/bin/killall backboardd SpringBoard sbreload");
5383 pid_t pid(ExecFork());
5388 pid_t pid(ExecFork());
5390 execl("/usr/bin/sbreload", "sbreload", NULL);
5400 system("/usr/bin/killall backboardd SpringBoard sbreload");
5404 UpdateExternalStatus(0);
5407 [delegate_ saveState];
5411 [delegate_ returnToCydia];
5415 [delegate_ terminateWithSuccess];
5416 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5417 [delegate_ suspendWithAnimation:YES];
5419 [delegate_ suspend];*/
5431 UIProgressHUD *hud([delegate_ addProgressHUD]);
5432 [hud setText:UCLocalize("LOADING")];
5433 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5439 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5440 SBReboot(SBSSpringBoardServerPort());
5442 reboot2(RB_AUTOBOOT);
5449 - (void) setTitle:(NSString *)title {
5450 [progress_ setTitle:title];
5451 [self updateProgress];
5454 - (UIBarButtonItem *) rightButton {
5455 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5456 initWithTitle:UCLocalize("CLOSE")
5457 style:UIBarButtonItemStylePlain
5459 action:@selector(close)
5463 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5464 UpdateExternalStatus(1);
5466 [progress_ setRunning:true];
5467 [self setTitle:title];
5468 // implicit updateProgress
5470 SHA1SumValue notifyconf; {
5472 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5475 MMap mmap(file, MMap::ReadOnly);
5477 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5478 notifyconf = sha1.Result();
5482 SHA1SumValue springlist; {
5484 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5487 MMap mmap(file, MMap::ReadOnly);
5489 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5490 springlist = sha1.Result();
5494 if (invocation != nil) {
5495 [invocation yieldToSelector:@selector(invoke)];
5496 [self setTitle:@"COMPLETE"];
5501 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5504 MMap mmap(file, MMap::ReadOnly);
5506 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5507 if (!(notifyconf == sha1.Result()))
5514 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5517 MMap mmap(file, MMap::ReadOnly);
5519 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5520 if (!(springlist == sha1.Result()))
5526 if (RestartSubstrate_)
5530 RestartSubstrate_ = false;
5533 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5534 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5535 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5536 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5537 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5540 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5542 [progress_ setRunning:false];
5543 [self updateProgress];
5545 [self applyRightButton];
5548 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5549 [progress_ addEvent:event];
5550 [self updateProgress];
5553 - (bool) isProgressCancelled {
5554 return cancel_ == 2;
5559 [self updateCancel];
5562 - (void) setCancellable:(bool)cancellable {
5563 unsigned cancel(cancel_);
5567 else if (cancel_ == 0)
5570 if (cancel != cancel_)
5571 [self updateCancel];
5574 - (void) setProgressCancellable:(NSNumber *)cancellable {
5575 [self setCancellable:[cancellable boolValue]];
5578 - (void) setProgressPercent:(NSNumber *)percent {
5579 [progress_ setPercent:[percent floatValue]];
5580 [self updateProgress];
5583 - (void) setProgressStatus:(NSDictionary *)status {
5584 if (status == nil) {
5585 [progress_ setCurrent:0];
5586 [progress_ setTotal:0];
5587 [progress_ setSpeed:0];
5589 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5591 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5592 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5593 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5596 [self updateProgress];
5602 /* Package Cell {{{ */
5603 @interface PackageCell : CyteTableViewCell <
5604 CyteTableViewCellDelegate
5608 _H<NSString> description_;
5610 _H<NSString> source_;
5612 _H<UIImage> placard_;
5616 - (PackageCell *) init;
5617 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5619 - (void) drawContentRect:(CGRect)rect;
5623 @implementation PackageCell
5625 - (PackageCell *) init {
5626 CGRect frame(CGRectMake(0, 0, 320, 74));
5627 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5628 UIView *content([self contentView]);
5629 CGRect bounds([content bounds]);
5631 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5632 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5633 [content addSubview:content_];
5635 [content_ setDelegate:self];
5636 [content_ setOpaque:YES];
5640 - (NSString *) accessibilityLabel {
5644 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5645 summarized_ = summary;
5655 [content_ setBackgroundColor:[UIColor whiteColor]];
5659 Source *source = [package source];
5661 icon_ = [package icon];
5663 if (NSString *name = [package name])
5664 name_ = [NSString stringWithString:name];
5666 if (NSString *description = [package shortDescription])
5667 description_ = [NSString stringWithString:description];
5669 commercial_ = [package isCommercial];
5671 NSString *label = nil;
5672 bool trusted = false;
5674 if (source != nil) {
5675 label = [source label];
5676 trusted = [source trusted];
5677 } else if ([[package id] isEqualToString:@"firmware"])
5678 label = UCLocalize("APPLE");
5680 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5682 NSString *from(label);
5684 NSString *section = [package simpleSection];
5685 if (section != nil && ![section isEqualToString:label]) {
5686 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5687 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5690 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5692 if (NSString *purpose = [package primaryPurpose])
5693 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5698 if (NSString *mode = [package mode]) {
5699 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5700 color = RemovingColor_;
5701 placard = @"removing";
5703 color = InstallingColor_;
5704 placard = @"installing";
5707 color = [UIColor whiteColor];
5709 if ([package installed] != nil)
5710 placard = @"installed";
5715 [content_ setBackgroundColor:color];
5718 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5721 [self setNeedsDisplay];
5722 [content_ setNeedsDisplay];
5725 - (void) drawSummaryContentRect:(CGRect)rect {
5726 bool highlighted(highlighted_);
5727 float width([self bounds].size.width);
5731 rect.size = [(UIImage *) icon_ size];
5733 while (rect.size.width > 16 || rect.size.height > 16) {
5734 rect.size.width /= 2;
5735 rect.size.height /= 2;
5738 rect.origin.x = 19 - rect.size.width / 2;
5739 rect.origin.y = 19 - rect.size.height / 2;
5741 [icon_ drawInRect:rect];
5744 if (badge_ != nil) {
5746 rect.size = [(UIImage *) badge_ size];
5748 rect.size.width /= 4;
5749 rect.size.height /= 4;
5751 rect.origin.x = 25 - rect.size.width / 2;
5752 rect.origin.y = 25 - rect.size.height / 2;
5754 [badge_ drawInRect:rect];
5757 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5761 UISetColor(commercial_ ? Purple_ : Black_);
5762 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5764 if (placard_ != nil)
5765 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5768 - (void) drawNormalContentRect:(CGRect)rect {
5769 bool highlighted(highlighted_);
5770 float width([self bounds].size.width);
5774 rect.size = [(UIImage *) icon_ size];
5776 while (rect.size.width > 32 || rect.size.height > 32) {
5777 rect.size.width /= 2;
5778 rect.size.height /= 2;
5781 rect.origin.x = 25 - rect.size.width / 2;
5782 rect.origin.y = 25 - rect.size.height / 2;
5784 [icon_ drawInRect:rect];
5787 if (badge_ != nil) {
5789 rect.size = [(UIImage *) badge_ size];
5791 rect.size.width /= 2;
5792 rect.size.height /= 2;
5794 rect.origin.x = 36 - rect.size.width / 2;
5795 rect.origin.y = 36 - rect.size.height / 2;
5797 [badge_ drawInRect:rect];
5800 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5804 UISetColor(commercial_ ? Purple_ : Black_);
5805 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5806 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5809 UISetColor(commercial_ ? Purplish_ : Gray_);
5810 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5812 if (placard_ != nil)
5813 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5816 - (void) drawContentRect:(CGRect)rect {
5818 [self drawSummaryContentRect:rect];
5820 [self drawNormalContentRect:rect];
5825 /* Section Cell {{{ */
5826 @interface SectionCell : CyteTableViewCell <
5827 CyteTableViewCellDelegate
5829 _H<NSString> basic_;
5830 _H<NSString> section_;
5832 _H<NSString> count_;
5834 _H<UISwitch> switch_;
5838 - (void) setSection:(Section *)section editing:(BOOL)editing;
5842 @implementation SectionCell
5844 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5845 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5846 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5847 // XXX: this initial frame is wrong, but is fixed later
5848 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5849 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5851 UIView *content([self contentView]);
5852 CGRect bounds([content bounds]);
5854 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5855 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5856 [content addSubview:content_];
5857 [content_ setBackgroundColor:[UIColor whiteColor]];
5859 [content_ setDelegate:self];
5863 - (void) onSwitch:(id)sender {
5864 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5865 if (metadata == nil) {
5866 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5867 [Sections_ setObject:metadata forKey:basic_];
5870 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5874 - (void) setSection:(Section *)section editing:(BOOL)editing {
5875 if (editing != editing_) {
5877 [switch_ removeFromSuperview];
5879 [self addSubview:switch_];
5888 if (section == nil) {
5889 name_ = UCLocalize("ALL_PACKAGES");
5892 basic_ = [section name];
5893 section_ = [section localized];
5895 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5896 count_ = [NSString stringWithFormat:@"%d", [section count]];
5899 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5902 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5903 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5905 [content_ setNeedsDisplay];
5908 - (void) setFrame:(CGRect)frame {
5909 [super setFrame:frame];
5911 CGRect rect([switch_ frame]);
5912 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
5915 - (NSString *) accessibilityLabel {
5919 - (void) drawContentRect:(CGRect)rect {
5920 bool highlighted(highlighted_ && !editing_);
5922 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
5924 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5927 float width(rect.size.width);
5929 width -= 9 + [switch_ frame].size.width;
5933 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:UILineBreakModeTailTruncation];
5935 CGSize size = [count_ sizeWithFont:Font14_];
5937 UISetColor(Folder_);
5939 [count_ drawAtPoint:CGPointMake(10 + (30 - size.width) / 2, 18) withFont:Font12Bold_];
5945 /* File Table {{{ */
5946 @interface FileTable : CyteViewController <
5947 UITableViewDataSource,
5950 _transient Database *database_;
5951 _H<Package> package_;
5953 _H<NSMutableArray> files_;
5954 _H<UITableView, 2> list_;
5957 - (id) initWithDatabase:(Database *)database;
5958 - (void) setPackage:(Package *)package;
5962 @implementation FileTable
5964 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5965 return files_ == nil ? 0 : [files_ count];
5968 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5972 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5973 static NSString *reuseIdentifier = @"Cell";
5975 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5977 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5978 [cell setFont:[UIFont systemFontOfSize:16]];
5980 [cell setText:[files_ objectAtIndex:indexPath.row]];
5981 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5986 - (NSURL *) navigationURL {
5987 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5991 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5992 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5993 [list_ setRowHeight:24.0f];
5994 [(UITableView *) list_ setDataSource:self];
5995 [list_ setDelegate:self];
5996 [self setView:list_];
5999 - (void) viewDidLoad {
6000 [super viewDidLoad];
6002 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6005 - (void) releaseSubviews {
6011 [super releaseSubviews];
6014 - (id) initWithDatabase:(Database *)database {
6015 if ((self = [super init]) != nil) {
6016 database_ = database;
6020 - (void) setPackage:(Package *)package {
6024 files_ = [NSMutableArray arrayWithCapacity:32];
6026 if (package != nil) {
6028 name_ = [package id];
6030 if (NSArray *files = [package files])
6031 [files_ addObjectsFromArray:files];
6033 if ([files_ count] != 0) {
6034 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6035 [files_ removeObjectAtIndex:0];
6036 [files_ sortUsingSelector:@selector(compareByPath:)];
6038 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6039 [stack addObject:@"/"];
6041 for (int i(0), e([files_ count]); i != e; ++i) {
6042 NSString *file = [files_ objectAtIndex:i];
6043 while (![file hasPrefix:[stack lastObject]])
6044 [stack removeLastObject];
6045 NSString *directory = [stack lastObject];
6046 [stack addObject:[file stringByAppendingString:@"/"]];
6047 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6048 ([stack count] - 2) * 3, "",
6049 [file substringFromIndex:[directory length]]
6058 - (void) reloadData {
6061 [self setPackage:[database_ packageWithName:name_]];
6066 /* Package Controller {{{ */
6067 @interface CYPackageController : CydiaWebViewController <
6068 UIActionSheetDelegate
6070 _transient Database *database_;
6071 _H<Package> package_;
6074 _H<NSMutableArray> buttons_;
6075 _H<UIBarButtonItem> button_;
6078 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6082 @implementation CYPackageController
6084 - (NSURL *) navigationURL {
6085 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6088 /* XXX: this is not safe at all... localization of /fail/ */
6089 - (void) _clickButtonWithName:(NSString *)name {
6090 if ([name isEqualToString:UCLocalize("CLEAR")])
6091 [delegate_ clearPackage:package_];
6092 else if ([name isEqualToString:UCLocalize("INSTALL")])
6093 [delegate_ installPackage:package_];
6094 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6095 [delegate_ installPackage:package_];
6096 else if ([name isEqualToString:UCLocalize("REMOVE")])
6097 [delegate_ removePackage:package_];
6098 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6099 [delegate_ installPackage:package_];
6100 else _assert(false);
6103 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6104 NSString *context([sheet context]);
6106 if ([context isEqualToString:@"modify"]) {
6107 if (button != [sheet cancelButtonIndex]) {
6108 NSString *buttonName = [buttons_ objectAtIndex:button];
6109 [self _clickButtonWithName:buttonName];
6112 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6116 - (bool) _allowJavaScriptPanel {
6121 - (void) _customButtonClicked {
6122 int count([buttons_ count]);
6127 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6129 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6130 [buttons addObjectsFromArray:buttons_];
6132 UIActionSheet *sheet = [[[UIActionSheet alloc]
6135 cancelButtonTitle:nil
6136 destructiveButtonTitle:nil
6137 otherButtonTitles:nil
6140 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6142 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6143 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6145 [sheet setContext:@"modify"];
6147 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6151 - (void) reloadButtonClicked {
6152 if (commercial_ && function_ == nil && [package_ uninstalled])
6154 [self customButtonClicked];
6157 - (void) applyLoadingTitle {
6158 // Don't show "Loading" as the title. Ever.
6161 - (UIBarButtonItem *) rightButton {
6166 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6167 if ((self = [super init]) != nil) {
6168 database_ = database;
6169 buttons_ = [NSMutableArray arrayWithCapacity:4];
6170 name_ = name == nil ? @"" : [NSString stringWithString:name];
6171 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6175 - (void) reloadData {
6178 package_ = [database_ packageWithName:name_];
6180 [buttons_ removeAllObjects];
6182 if (package_ != nil) {
6183 [(Package *) package_ parse];
6185 commercial_ = [package_ isCommercial];
6187 if ([package_ mode] != nil)
6188 [buttons_ addObject:UCLocalize("CLEAR")];
6189 if ([package_ source] == nil);
6190 else if ([package_ upgradableAndEssential:NO])
6191 [buttons_ addObject:UCLocalize("UPGRADE")];
6192 else if ([package_ uninstalled])
6193 [buttons_ addObject:UCLocalize("INSTALL")];
6195 [buttons_ addObject:UCLocalize("REINSTALL")];
6196 if (![package_ uninstalled])
6197 [buttons_ addObject:UCLocalize("REMOVE")];
6201 switch ([buttons_ count]) {
6202 case 0: title = nil; break;
6203 case 1: title = [buttons_ objectAtIndex:0]; break;
6204 default: title = UCLocalize("MODIFY"); break;
6207 button_ = [[[UIBarButtonItem alloc]
6209 style:UIBarButtonItemStylePlain
6211 action:@selector(customButtonClicked)
6215 - (bool) isLoading {
6216 return commercial_ ? [super isLoading] : false;
6222 /* Package List Controller {{{ */
6223 @interface PackageListController : CyteViewController <
6224 UITableViewDataSource,
6227 _transient Database *database_;
6229 _H<NSArray> packages_;
6230 _H<NSMutableArray> sections_;
6231 _H<UITableView, 2> list_;
6232 _H<NSMutableArray> index_;
6233 _H<NSMutableDictionary> indices_;
6234 _H<NSString> title_;
6235 unsigned reloading_;
6238 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6239 - (void) setDelegate:(id)delegate;
6240 - (void) resetCursor;
6245 @implementation PackageListController
6247 - (NSURL *) referrerURL {
6248 return [self navigationURL];
6251 - (bool) isSummarized {
6255 - (bool) showsSections {
6259 - (void) deselectWithAnimation:(BOOL)animated {
6260 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6263 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6264 CGRect base = [[self view] bounds];
6265 base.size.height -= bounds.size.height;
6266 base.origin = [list_ frame].origin;
6268 [UIView beginAnimations:nil context:NULL];
6269 [UIView setAnimationBeginsFromCurrentState:YES];
6270 [UIView setAnimationCurve:curve];
6271 [UIView setAnimationDuration:duration];
6272 [list_ setFrame:base];
6273 [UIView commitAnimations];
6276 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6277 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6280 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6281 [self resizeForKeyboardBounds:bounds duration:0];
6284 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6285 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6286 *curve = UIViewAnimationCurveEaseInOut;
6288 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6290 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6293 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6296 - (void) keyboardWillShow:(NSNotification *)notification {
6299 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6300 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6302 NSTimeInterval duration;
6303 UIViewAnimationCurve curve;
6304 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6306 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);
6307 UIViewController *base = self;
6308 while ([base parentOrPresentingViewController] != nil)
6309 base = [base parentOrPresentingViewController];
6310 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6311 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6313 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6314 intersection.size.height += CYStatusBarHeight();
6316 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6319 - (void) keyboardWillHide:(NSNotification *)notification {
6320 NSTimeInterval duration;
6321 UIViewAnimationCurve curve;
6322 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6324 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6327 - (void) viewWillAppear:(BOOL)animated {
6328 [super viewWillAppear:animated];
6330 [self resizeForKeyboardBounds:CGRectZero];
6331 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6332 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6335 - (void) viewWillDisappear:(BOOL)animated {
6336 [super viewWillDisappear:animated];
6338 [self resizeForKeyboardBounds:CGRectZero];
6339 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6340 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6343 - (void) viewDidAppear:(BOOL)animated {
6344 [super viewDidAppear:animated];
6345 [self deselectWithAnimation:animated];
6348 - (void) didSelectPackage:(Package *)package {
6349 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6350 [view setDelegate:delegate_];
6351 [[self navigationController] pushViewController:view animated:YES];
6354 #if TryIndexedCollation
6355 + (BOOL) hasIndexedCollation {
6356 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6360 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6361 NSInteger count([sections_ count]);
6362 return count == 0 ? 1 : count;
6365 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6366 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6368 return [[sections_ objectAtIndex:section] name];
6371 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6372 if ([sections_ count] == 0)
6374 return [[sections_ objectAtIndex:section] count];
6377 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6378 @synchronized (database_) {
6379 if ([database_ era] != era_)
6382 Section *section([sections_ objectAtIndex:[path section]]);
6383 NSInteger row([path row]);
6384 Package *package([packages_ objectAtIndex:([section row] + row)]);
6385 return [[package retain] autorelease];
6388 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6389 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6391 cell = [[[PackageCell alloc] init] autorelease];
6393 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6394 [cell setPackage:package asSummary:[self isSummarized]];
6398 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6399 Package *package([self packageAtIndexPath:path]);
6400 package = [database_ packageWithName:[package id]];
6401 [self didSelectPackage:package];
6404 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6405 if (![self showsSections])
6411 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6412 #if TryIndexedCollation
6413 if ([[self class] hasIndexedCollation]) {
6414 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6421 - (void) updateHeight {
6422 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6425 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6426 if ((self = [super init]) != nil) {
6427 database_ = database;
6428 title_ = [title copy];
6429 [[self navigationItem] setTitle:title_];
6434 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6435 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6436 [self setView:view];
6438 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6439 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6440 [view addSubview:list_];
6442 // XXX: is 20 the most optimal number here?
6443 [list_ setSectionIndexMinimumDisplayRowCount:20];
6445 [(UITableView *) list_ setDataSource:self];
6446 [list_ setDelegate:self];
6448 [self updateHeight];
6451 - (void) releaseSubviews {
6459 [super releaseSubviews];
6462 - (void) setDelegate:(id)delegate {
6463 delegate_ = delegate;
6466 - (bool) shouldYield {
6470 - (bool) shouldBlock {
6474 - (NSMutableArray *) _reloadPackages {
6475 @synchronized (database_) {
6476 era_ = [database_ era];
6477 NSArray *packages([database_ packages]);
6479 return [NSMutableArray arrayWithArray:packages];
6482 - (void) _reloadData {
6483 if (reloading_ != 0) {
6491 if ([self shouldYield]) {
6495 if (![self shouldBlock])
6498 hud = [delegate_ addProgressHUD];
6499 [hud setText:UCLocalize("LOADING")];
6503 packages = [self yieldToSelector:@selector(_reloadPackages)];
6506 [delegate_ removeProgressHUD:hud];
6507 } while (reloading_ == 2);
6509 packages = [self _reloadPackages];
6512 @synchronized (database_) {
6513 if (era_ != [database_ era])
6517 packages_ = packages;
6519 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6520 sections_ = [NSMutableArray arrayWithCapacity:16];
6522 Section *section = nil;
6524 #if TryIndexedCollation
6525 if ([[self class] hasIndexedCollation]) {
6526 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6528 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6529 NSArray *titles = [collation sectionIndexTitles];
6532 _profile(PackageTable$reloadData$Section)
6533 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6537 _profile(PackageTable$reloadData$Section$Package)
6538 package = [packages_ objectAtIndex:offset];
6539 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6542 while (secidx < index) {
6545 _profile(PackageTable$reloadData$Section$Allocate)
6546 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6549 _profile(PackageTable$reloadData$Section$Add)
6550 [sections_ addObject:section];
6554 [section addToCount];
6560 index_ = [NSMutableArray arrayWithCapacity:32];
6562 bool sectioned([self showsSections]);
6564 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6565 [sections_ addObject:section];
6568 _profile(PackageTable$reloadData$Section)
6569 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6573 _profile(PackageTable$reloadData$Section$Package)
6574 package = [packages_ objectAtIndex:offset];
6575 index = [package index];
6578 if (sectioned && (section == nil || [section index] != index)) {
6579 _profile(PackageTable$reloadData$Section$Allocate)
6580 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6583 [index_ addObject:[section name]];
6584 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6586 _profile(PackageTable$reloadData$Section$Add)
6587 [sections_ addObject:section];
6591 [section addToCount];
6596 [self updateHeight];
6598 _profile(PackageTable$reloadData$List)
6599 [(UITableView *) list_ setDataSource:self];
6604 - (void) reloadData {
6607 if ([self shouldYield])
6608 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6613 - (void) resetCursor {
6614 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6617 - (void) clearData {
6618 [self updateHeight];
6620 [list_ setDataSource:nil];
6628 /* Filtered Package List Controller {{{ */
6629 @interface FilteredPackageListController : PackageListController {
6632 _H<NSObject> object_;
6633 _H<NSObject> stuff_;
6636 - (void) setObject:(id)object;
6637 - (void) setStuff:(id)object;
6638 - (void) setObject:(id)object andStuff:(id)stuff;
6640 - (void) setObject:(id)object forFilter:(SEL)filter;
6641 - (void) setObject:(id)object andStuff:(id)stuff forFilter:(SEL)filter;
6644 - (void) setFilter:(SEL)filter;
6646 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6650 @implementation FilteredPackageListController
6656 - (void) setFilter:(SEL)filter {
6657 @synchronized (self) {
6660 /* XXX: this is an unsafe optimization of doomy hell */
6661 Method method(class_getInstanceMethod([Package class], filter));
6662 _assert(method != NULL);
6663 imp_ = method_getImplementation(method);
6664 _assert(imp_ != NULL);
6667 - (void) setObject:(id)object {
6668 @synchronized (self) {
6672 - (void) setStuff:(id)stuff {
6673 @synchronized (self) {
6677 - (void) setObject:(id)object andStuff:(id)stuff {
6678 @synchronized (self) {
6683 - (void) setObject:(id)object forFilter:(SEL)filter {
6684 @synchronized (self) {
6685 [self setFilter:filter];
6689 - (void) setObject:(id)object andStuff:(id)stuff forFilter:(SEL)filter {
6690 @synchronized (self) {
6691 [self setFilter:filter];
6696 - (NSMutableArray *) _reloadPackages {
6697 @synchronized (database_) {
6698 era_ = [database_ era];
6699 NSArray *packages([database_ packages]);
6701 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6705 _H<NSObject> object;
6708 @synchronized (self) {
6715 _profile(PackageTable$reloadData$Filter)
6716 for (Package *package in packages)
6717 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id, id)>(imp))(package, filter, object, stuff))
6718 [filtered addObject:package];
6724 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6725 if ((self = [super initWithDatabase:database title:title]) != nil) {
6726 [self setFilter:filter];
6731 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object with:(id)stuff {
6732 if ((self = [super initWithDatabase:database title:title]) != nil) {
6733 [self setFilter:filter];
6742 /* Home Controller {{{ */
6743 @interface HomeController : CydiaWebViewController {
6744 CFRunLoopRef runloop_;
6745 SCNetworkReachabilityRef reachability_;
6750 @implementation HomeController
6752 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6753 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6757 if ((self = [super init]) != nil) {
6758 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6761 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6762 if (reachability_ != NULL) {
6763 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6764 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6766 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6767 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6774 if (reachability_ != NULL && runloop_ != NULL)
6775 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6779 - (NSURL *) navigationURL {
6780 return [NSURL URLWithString:@"cydia://home"];
6783 - (void) aboutButtonClicked {
6784 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6786 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6787 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6788 [alert setCancelButtonIndex:0];
6791 @"Copyright \u00a9 2008-2013\n"
6794 "Jay Freeman (saurik)\n"
6795 "saurik@saurik.com\n"
6796 "http://www.saurik.com/"
6802 - (UIBarButtonItem *) leftButton {
6803 return [[[UIBarButtonItem alloc]
6804 initWithTitle:UCLocalize("ABOUT")
6805 style:UIBarButtonItemStylePlain
6807 action:@selector(aboutButtonClicked)
6814 /* Cydia Navigation Controller Interface {{{ */
6815 @interface UINavigationController (Cydia)
6817 - (NSArray *) navigationURLCollection;
6818 - (void) unloadData;
6823 /* Cydia Tab Bar Controller {{{ */
6824 @interface CydiaTabBarController : CyteTabBarController <
6825 UITabBarControllerDelegate,
6828 _transient Database *database_;
6830 _H<UIActivityIndicatorView> indicator_;
6833 // XXX: ok, "updatedelegate_"?...
6834 _transient NSObject<CydiaDelegate> *updatedelegate_;
6837 - (NSArray *) navigationURLCollection;
6838 - (void) beginUpdate;
6843 @implementation CydiaTabBarController
6845 - (NSArray *) navigationURLCollection {
6846 NSMutableArray *items([NSMutableArray array]);
6848 // XXX: Should this deal with transient view controllers?
6849 for (id navigation in [self viewControllers]) {
6850 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6852 [items addObject:stack];
6858 - (id) initWithDatabase:(Database *)database {
6859 if ((self = [super init]) != nil) {
6860 database_ = database;
6861 [self setDelegate:self];
6863 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6864 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6866 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6870 - (void) setUpdate:(NSDate *)date {
6874 - (void) beginUpdate {
6875 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6876 UITabBarItem *item([controller tabBarItem]);
6878 [item setBadgeValue:@""];
6879 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6881 [indicator_ startAnimating];
6882 [badge addSubview:indicator_];
6884 [updatedelegate_ retainNetworkActivityIndicator];
6888 detachNewThreadSelector:@selector(performUpdate)
6894 - (void) performUpdate {
6895 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6897 SourceStatus status(self, database_);
6898 [database_ updateWithStatus:status];
6901 performSelectorOnMainThread:@selector(completeUpdate)
6909 - (void) stopUpdateWithSelector:(SEL)selector {
6911 [updatedelegate_ releaseNetworkActivityIndicator];
6913 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6914 [[controller tabBarItem] setBadgeValue:nil];
6916 [indicator_ removeFromSuperview];
6917 [indicator_ stopAnimating];
6919 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6922 - (void) completeUpdate {
6925 [self stopUpdateWithSelector:@selector(reloadData)];
6928 - (void) cancelUpdate {
6929 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
6932 - (void) cancelPressed {
6933 [self cancelUpdate];
6940 - (bool) isSourceCancelled {
6944 - (void) startSourceFetch:(NSString *)uri {
6947 - (void) stopSourceFetch:(NSString *)uri {
6950 - (void) setUpdateDelegate:(id)delegate {
6951 updatedelegate_ = delegate;
6954 - (UIView *) transitionView {
6955 if (![self respondsToSelector:@selector(_transitionView)])
6956 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6957 else if (kCFCoreFoundationVersionNumber < 800)
6958 return [self _transitionView];
6960 return [[[self _transitionView] superview] superview];
6966 /* Cydia Navigation Controller Implementation {{{ */
6967 @implementation UINavigationController (Cydia)
6969 - (NSArray *) navigationURLCollection {
6970 NSMutableArray *stack([NSMutableArray array]);
6972 for (CyteViewController *controller in [self viewControllers]) {
6973 NSString *url = [[controller navigationURL] absoluteString];
6975 [stack addObject:url];
6981 - (void) reloadData {
6984 UIViewController *visible([self visibleViewController]);
6986 [visible reloadData];
6988 // on the iPad, this view controller is ALSO visible. :(
6990 if (UIViewController *top = [self topViewController])
6995 - (void) unloadData {
6996 for (CyteViewController *page in [self viewControllers])
7005 /* Cydia:// Protocol {{{ */
7006 @interface CydiaURLProtocol : NSURLProtocol {
7011 @implementation CydiaURLProtocol
7013 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7014 NSURL *url([request URL]);
7018 NSString *scheme([[url scheme] lowercaseString]);
7019 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7021 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7027 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7031 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7032 id<NSURLProtocolClient> client([self client]);
7034 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7036 NSData *data(UIImagePNGRepresentation(icon));
7038 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7039 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7040 [client URLProtocol:self didLoadData:data];
7041 [client URLProtocolDidFinishLoading:self];
7045 - (void) startLoading {
7046 id<NSURLProtocolClient> client([self client]);
7047 NSURLRequest *request([self request]);
7049 NSURL *url([request URL]);
7050 NSString *href([url absoluteString]);
7051 NSString *scheme([[url scheme] lowercaseString]);
7055 if ([scheme isEqualToString:@"cydia"])
7056 path = [href substringFromIndex:8];
7057 else if ([scheme isEqualToString:@"about"])
7058 path = [href substringFromIndex:12];
7059 else _assert(false);
7061 NSRange slash([path rangeOfString:@"/"]);
7064 if (slash.location == NSNotFound) {
7068 command = [path substringToIndex:slash.location];
7069 path = [path substringFromIndex:(slash.location + 1)];
7072 Database *database([Database sharedInstance]);
7074 if ([command isEqualToString:@"package-icon"]) {
7077 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7078 Package *package([database packageWithName:path]);
7082 UIImage *icon([package icon]);
7083 [self _returnPNGWithImage:icon forRequest:request];
7084 } else if ([command isEqualToString:@"uikit-image"]) {
7087 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7088 UIImage *icon(_UIImageWithName(path));
7089 [self _returnPNGWithImage:icon forRequest:request];
7090 } else if ([command isEqualToString:@"section-icon"]) {
7093 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7094 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7096 icon = [UIImage applicationImageNamed:@"unknown.png"];
7097 [self _returnPNGWithImage:icon forRequest:request];
7099 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7103 - (void) stopLoading {
7109 /* Section Controller {{{ */
7110 @interface SectionController : FilteredPackageListController {
7112 _H<NSString> section_;
7115 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7119 @implementation SectionController
7121 - (NSURL *) referrerURL {
7122 NSString *name(section_);
7123 name = name ?: @"*";
7124 NSString *key(key_);
7126 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7129 - (NSURL *) navigationURL {
7130 NSString *name(section_);
7131 name = name ?: @"*";
7132 NSString *key(key_);
7134 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7137 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7140 title = UCLocalize("ALL_PACKAGES");
7141 else if (![section isEqual:@""])
7142 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7144 title = UCLocalize("NO_SECTION");
7146 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:source:) with:section with:source]) != nil) {
7147 key_ = [source key];
7152 - (void) reloadData {
7153 [super setStuff:[database_ sourceWithKey:key_]];
7159 /* Sections Controller {{{ */
7160 @interface SectionsController : CyteViewController <
7161 UITableViewDataSource,
7164 _transient Database *database_;
7166 _H<NSMutableArray> sections_;
7167 _H<NSMutableArray> filtered_;
7168 _H<UITableView, 2> list_;
7171 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7172 - (void) editButtonClicked;
7176 @implementation SectionsController
7178 - (NSURL *) navigationURL {
7179 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7182 - (Source *) source {
7185 return [database_ sourceWithKey:key_];
7188 - (void) updateNavigationItem {
7189 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7190 if ([sections_ count] == 0) {
7191 [[self navigationItem] setRightBarButtonItem:nil];
7193 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7194 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7196 action:@selector(editButtonClicked)
7197 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7201 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7202 [super setEditing:editing animated:animated];
7207 [delegate_ updateData];
7209 [self updateNavigationItem];
7212 - (void) viewDidAppear:(BOOL)animated {
7213 [super viewDidAppear:animated];
7214 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7217 - (void) viewWillDisappear:(BOOL)animated {
7218 [super viewWillDisappear:animated];
7219 [self setEditing:NO];
7222 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7223 Section *section = nil;
7224 int index = [indexPath row];
7225 if (![self isEditing]) {
7228 section = [filtered_ objectAtIndex:index];
7230 section = [sections_ objectAtIndex:index];
7235 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7236 if ([self isEditing])
7237 return [sections_ count];
7239 return [filtered_ count] + 1;
7242 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7246 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7247 static NSString *reuseIdentifier = @"SectionCell";
7249 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7251 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7253 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7258 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7259 if ([self isEditing])
7262 Section *section = [self sectionAtIndexPath:indexPath];
7264 SectionController *controller = [[[SectionController alloc]
7265 initWithDatabase:database_
7266 source:[self source]
7267 section:[section name]
7269 [controller setDelegate:delegate_];
7271 [[self navigationController] pushViewController:controller animated:YES];
7275 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7276 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7277 [list_ setRowHeight:46];
7278 [(UITableView *) list_ setDataSource:self];
7279 [list_ setDelegate:self];
7280 [self setView:list_];
7283 - (void) viewDidLoad {
7284 [super viewDidLoad];
7286 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7289 - (void) releaseSubviews {
7295 [super releaseSubviews];
7298 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7299 if ((self = [super init]) != nil) {
7300 database_ = database;
7301 key_ = [source key];
7305 - (void) reloadData {
7308 NSArray *packages = [database_ packages];
7310 sections_ = [NSMutableArray arrayWithCapacity:16];
7311 filtered_ = [NSMutableArray arrayWithCapacity:16];
7313 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7315 Source *source([self source]);
7318 for (Package *package in packages) {
7319 if (source != nil && [package source] != source)
7322 NSString *name([package section]);
7323 NSString *key(name == nil ? @"" : name);
7327 _profile(SectionsView$reloadData$Section)
7328 section = [sections objectForKey:key];
7329 if (section == nil) {
7330 _profile(SectionsView$reloadData$Section$Allocate)
7331 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7332 [sections setObject:section forKey:key];
7337 [section addToCount];
7339 _profile(SectionsView$reloadData$Filter)
7340 if (![package valid] || ![package visible])
7348 [sections_ addObjectsFromArray:[sections allValues]];
7350 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7352 for (Section *section in (id) sections_) {
7353 size_t count([section row]);
7357 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7358 [section setCount:count];
7359 [filtered_ addObject:section];
7362 [self updateNavigationItem];
7367 - (void) editButtonClicked {
7368 [self setEditing:![self isEditing] animated:YES];
7374 /* Changes Controller {{{ */
7375 @interface ChangesController : CyteViewController <
7376 UITableViewDataSource,
7379 _transient Database *database_;
7381 _H<NSMutableArray> packages_;
7382 _H<NSMutableArray> sections_;
7383 _H<UITableView, 2> list_;
7387 - (id) initWithDatabase:(Database *)database;
7391 @implementation ChangesController
7393 - (NSURL *) navigationURL {
7394 return [NSURL URLWithString:@"cydia://changes"];
7397 - (void) viewDidAppear:(BOOL)animated {
7398 [super viewDidAppear:animated];
7399 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7402 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7403 NSInteger count([sections_ count]);
7404 return count == 0 ? 1 : count;
7407 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7408 if ([sections_ count] == 0)
7410 return [[sections_ objectAtIndex:section] name];
7413 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7414 if ([sections_ count] == 0)
7416 return [[sections_ objectAtIndex:section] count];
7419 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7420 @synchronized (database_) {
7421 if ([database_ era] != era_)
7424 NSUInteger sectionIndex([path section]);
7425 if (sectionIndex >= [sections_ count])
7427 Section *section([sections_ objectAtIndex:sectionIndex]);
7428 NSInteger row([path row]);
7429 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7432 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7433 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7435 cell = [[[PackageCell alloc] init] autorelease];
7437 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7438 [cell setPackage:package asSummary:false];
7442 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7443 Package *package([self packageAtIndexPath:path]);
7444 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[NSString stringWithFormat:@"%@/#!/changes/", UI_]] autorelease]);
7445 [view setDelegate:delegate_];
7446 [[self navigationController] pushViewController:view animated:YES];
7450 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7451 NSString *context([alert context]);
7453 if ([context isEqualToString:@"norefresh"])
7454 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7457 - (void) setLeftBarButtonItem {
7458 if ([delegate_ updating])
7459 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7460 initWithTitle:UCLocalize("CANCEL")
7461 style:UIBarButtonItemStyleDone
7463 action:@selector(cancelButtonClicked)
7464 ] autorelease] animated:YES];
7466 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7467 initWithTitle:UCLocalize("REFRESH")
7468 style:UIBarButtonItemStylePlain
7470 action:@selector(refreshButtonClicked)
7471 ] autorelease] animated:YES];
7474 - (void) refreshButtonClicked {
7475 if ([delegate_ requestUpdate])
7476 [self setLeftBarButtonItem];
7479 - (void) cancelButtonClicked {
7480 [delegate_ cancelUpdate];
7483 - (void) upgradeButtonClicked {
7484 [delegate_ distUpgrade];
7485 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7489 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7490 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7491 [self setView:view];
7493 list_ = [[[UITableView alloc] initWithFrame:[view bounds] style:UITableViewStylePlain] autorelease];
7494 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7495 [list_ setRowHeight:73];
7496 [(UITableView *) list_ setDataSource:self];
7497 [list_ setDelegate:self];
7498 [view addSubview:list_];
7501 - (void) viewDidLoad {
7502 [super viewDidLoad];
7504 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7507 - (void) releaseSubviews {
7513 [super releaseSubviews];
7516 - (id) initWithDatabase:(Database *)database {
7517 if ((self = [super init]) != nil) {
7518 database_ = database;
7522 - (NSMutableArray *) _reloadPackages {
7523 @synchronized (database_) {
7524 era_ = [database_ era];
7525 NSArray *packages([database_ packages]);
7527 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7530 _profile(ChangesController$_reloadPackages$Filter)
7531 for (Package *package in packages)
7532 if ([package upgradableAndEssential:YES] || [package visible])
7533 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7536 _profile(ChangesController$_reloadPackages$radixSort)
7537 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7544 - (void) _reloadData {
7545 [self setLeftBarButtonItem];
7547 NSMutableArray *packages;
7551 UIProgressHUD *hud([delegate_ addProgressHUD]);
7552 [hud setText:UCLocalize("LOADING")];
7553 //NSLog(@"HUD:%@::%@", delegate_, hud);
7554 packages = [self yieldToSelector:@selector(_reloadPackages)];
7555 [delegate_ removeProgressHUD:hud];
7557 packages = [self _reloadPackages];
7560 @synchronized (database_) {
7561 if (era_ != [database_ era])
7564 packages_ = packages;
7565 sections_ = [NSMutableArray arrayWithCapacity:16];
7567 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7568 Section *ignored = nil;
7569 Section *section = nil;
7573 bool unseens = false;
7575 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7577 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7578 Package *package = [packages_ objectAtIndex:offset];
7580 BOOL uae = [package upgradableAndEssential:YES];
7584 time_t seen([package seen]);
7586 if (section == nil || last != seen) {
7590 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7593 _profile(ChangesController$reloadData$Allocate)
7594 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7595 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7596 [sections_ addObject:section];
7600 [section addToCount];
7601 } else if ([package ignored]) {
7602 if (ignored == nil) {
7603 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7605 [ignored addToCount];
7608 [upgradable addToCount];
7613 CFRelease(formatter);
7616 Section *last = [sections_ lastObject];
7617 size_t count = [last count];
7618 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7619 [sections_ removeLastObject];
7622 if ([ignored count] != 0)
7623 [sections_ insertObject:ignored atIndex:0];
7625 [sections_ insertObject:upgradable atIndex:0];
7629 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7630 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7631 style:UIBarButtonItemStylePlain
7633 action:@selector(upgradeButtonClicked)
7634 ] autorelease]) animated:YES];
7639 - (void) reloadData {
7641 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7646 /* Search Controller {{{ */
7647 @interface SearchController : FilteredPackageListController <
7650 _H<UISearchBar, 1> search_;
7654 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7655 - (void) reloadData;
7659 @implementation SearchController
7661 - (NSURL *) referrerURL {
7662 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7665 - (NSURL *) navigationURL {
7666 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7667 return [NSURL URLWithString:@"cydia://search"];
7669 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7672 - (NSArray *) termsForQuery:(NSString *)query {
7673 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7674 for (NSString *component in [query componentsSeparatedByString:@" "])
7675 if ([component length] != 0)
7676 [terms addObject:component];
7681 - (void) useSearch {
7682 [self setObject:[self termsForQuery:[search_ text]] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7687 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7688 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7693 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7694 [search_ resignFirstResponder];
7698 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7699 [search_ setText:@""];
7700 [self searchBarButtonClicked:searchBar];
7703 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7704 [self searchBarButtonClicked:searchBar];
7707 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7708 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7712 - (bool) shouldYield {
7716 - (bool) shouldBlock {
7717 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7720 - (bool) isSummarized {
7721 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7724 - (bool) showsSections {
7728 - (NSMutableArray *) _reloadPackages {
7729 NSMutableArray *packages([super _reloadPackages]);
7730 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7731 [packages radixSortUsingSelector:@selector(rank)];
7735 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7736 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[self termsForQuery:query]])) {
7737 search_ = [[[UISearchBar alloc] init] autorelease];
7738 [search_ setDelegate:self];
7741 [search_ setText:query];
7745 - (void) viewDidAppear:(BOOL)animated {
7746 [super viewDidAppear:animated];
7748 if (!searchloaded_) {
7749 searchloaded_ = YES;
7750 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7751 [search_ layoutSubviews];
7752 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7754 UITextField *textField;
7755 if ([search_ respondsToSelector:@selector(searchField)])
7756 textField = [search_ searchField];
7758 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7760 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7761 [textField setEnablesReturnKeyAutomatically:NO];
7762 [[self navigationItem] setTitleView:textField];
7765 if ([self isSummarized])
7766 [search_ becomeFirstResponder];
7769 - (void) reloadData {
7770 id object([search_ text]);
7771 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7772 object = [self termsForQuery:object];
7774 [self setObject:object];
7780 - (void) didSelectPackage:(Package *)package {
7781 [search_ resignFirstResponder];
7782 [super didSelectPackage:package];
7787 /* Package Settings Controller {{{ */
7788 @interface PackageSettingsController : CyteViewController <
7789 UITableViewDataSource,
7792 _transient Database *database_;
7794 _H<Package> package_;
7795 _H<UITableView, 2> table_;
7796 _H<UISwitch> subscribedSwitch_;
7797 _H<UISwitch> ignoredSwitch_;
7798 _H<UITableViewCell> subscribedCell_;
7799 _H<UITableViewCell> ignoredCell_;
7802 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7806 @implementation PackageSettingsController
7808 - (NSURL *) navigationURL {
7809 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7812 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7813 if (package_ == nil)
7816 if ([package_ installed] == nil)
7822 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7823 if (package_ == nil)
7826 // both sections contain just one item right now.
7830 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7834 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7836 return UCLocalize("SHOW_ALL_CHANGES_EX");
7838 return UCLocalize("IGNORE_UPGRADES_EX");
7841 - (void) onSubscribed:(id)control {
7842 bool value([control isOn]);
7843 if (package_ == nil)
7845 if ([package_ setSubscribed:value])
7846 [delegate_ updateData];
7849 - (void) _updateIgnored {
7850 const char *package([name_ UTF8String]);
7851 bool on([ignoredSwitch_ isOn]);
7853 pid_t pid(ExecFork());
7855 FILE *dpkg(popen("dpkg --set-selections", "w"));
7856 fwrite(package, strlen(package), 1, dpkg);
7859 fwrite(" hold\n", 6, 1, dpkg);
7861 fwrite(" install\n", 9, 1, dpkg);
7869 - (void) onIgnored:(id)control {
7870 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7871 [invocation setTarget:self];
7872 [invocation setSelector:@selector(_updateIgnored)];
7874 [delegate_ reloadDataWithInvocation:invocation];
7877 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7878 if (package_ == nil)
7881 switch ([indexPath section]) {
7882 case 0: return subscribedCell_;
7883 case 1: return ignoredCell_;
7892 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7893 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7894 [self setView:view];
7896 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7897 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7898 [(UITableView *) table_ setDataSource:self];
7899 [table_ setDelegate:self];
7900 [view addSubview:table_];
7902 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7903 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7904 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7906 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7907 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7908 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7910 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7911 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7912 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7913 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7915 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7916 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7917 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7918 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7921 - (void) viewDidLoad {
7922 [super viewDidLoad];
7924 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7927 - (void) releaseSubviews {
7929 subscribedCell_ = nil;
7931 ignoredSwitch_ = nil;
7932 subscribedSwitch_ = nil;
7934 [super releaseSubviews];
7937 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7938 if ((self = [super init]) != nil) {
7939 database_ = database;
7944 - (void) reloadData {
7947 package_ = [database_ packageWithName:name_];
7949 if (package_ != nil) {
7950 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7951 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7952 } // XXX: what now, G?
7954 [table_ reloadData];
7960 /* Installed Controller {{{ */
7961 @interface InstalledController : FilteredPackageListController {
7964 - (id) initWithDatabase:(Database *)database;
7965 - (void) queueStatusDidChange;
7969 @implementation InstalledController
7971 - (NSURL *) referrerURL {
7972 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
7975 - (NSURL *) navigationURL {
7976 return [NSURL URLWithString:@"cydia://installed"];
7979 - (id) initWithDatabase:(Database *)database {
7980 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7981 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("SIMPLE"), UCLocalize("EXPERT"), nil]] autorelease]);
7982 [segmented setSelectedSegmentIndex:0];
7983 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
7984 [[self navigationItem] setTitleView:segmented];
7986 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
7988 [self queueStatusDidChange];
7993 - (void) queueButtonClicked {
7998 - (void) queueStatusDidChange {
8001 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8002 initWithTitle:UCLocalize("QUEUE")
8003 style:UIBarButtonItemStyleDone
8005 action:@selector(queueButtonClicked)
8008 [[self navigationItem] setLeftBarButtonItem:nil];
8013 - (void) modeChanged:(UISegmentedControl *)segmented {
8014 bool simple([segmented selectedSegmentIndex] == 0);
8015 [self setObject:[NSNumber numberWithBool:simple]];
8022 /* Source Cell {{{ */
8023 @interface SourceCell : CyteTableViewCell <
8024 CyteTableViewCellDelegate,
8027 _H<Source, 1> source_;
8030 _H<NSString> origin_;
8031 _H<NSString> label_;
8032 _H<UIActivityIndicatorView> indicator_;
8035 - (void) setSource:(Source *)source;
8036 - (void) setFetch:(NSNumber *)fetch;
8040 @implementation SourceCell
8042 - (void) _setImage:(NSArray *)data {
8043 if ([url_ isEqual:[data objectAtIndex:0]]) {
8044 icon_ = [data objectAtIndex:1];
8045 [content_ setNeedsDisplay];
8049 - (void) _setSource:(NSURL *) url {
8050 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8052 if (NSData *data = [NSURLConnection
8053 sendSynchronousRequest:[NSURLRequest
8055 cachePolicy:NSURLRequestUseProtocolCachePolicy
8059 returningResponse:NULL
8062 if (UIImage *image = [UIImage imageWithData:data])
8063 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8068 - (void) setSource:(Source *)source {
8070 [source_ setDelegate:self];
8072 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8074 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8076 origin_ = [source name];
8077 label_ = [source rooturi];
8079 [content_ setNeedsDisplay];
8081 url_ = [source iconURL];
8082 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8085 - (void) setAllSource {
8087 [indicator_ stopAnimating];
8089 icon_ = [UIImage applicationImageNamed:@"folder.png"];
8090 origin_ = UCLocalize("ALL_SOURCES");
8091 label_ = UCLocalize("ALL_SOURCES_EX");
8092 [content_ setNeedsDisplay];
8095 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8096 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8097 UIView *content([self contentView]);
8098 CGRect bounds([content bounds]);
8100 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8101 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8102 [content_ setBackgroundColor:[UIColor whiteColor]];
8103 [content addSubview:content_];
8105 [content_ setDelegate:self];
8106 [content_ setOpaque:YES];
8108 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8109 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8110 [content addSubview:indicator_];
8112 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8116 - (void) layoutSubviews {
8117 [super layoutSubviews];
8119 UIView *content([self contentView]);
8120 CGRect bounds([content bounds]);
8122 CGRect frame([indicator_ frame]);
8123 frame.origin.x = bounds.size.width - frame.size.width;
8124 frame.origin.y = (bounds.size.height - frame.size.height) / 2;
8126 if (kCFCoreFoundationVersionNumber < 800)
8127 frame.origin.x -= 8;
8128 [indicator_ setFrame:frame];
8131 - (NSString *) accessibilityLabel {
8135 - (void) drawContentRect:(CGRect)rect {
8136 bool highlighted(highlighted_);
8137 float width(rect.size.width);
8141 rect.size = [(UIImage *) icon_ size];
8143 while (rect.size.width > 32 || rect.size.height > 32) {
8144 rect.size.width /= 2;
8145 rect.size.height /= 2;
8148 rect.origin.x = 26 - rect.size.width / 2;
8149 rect.origin.y = 26 - rect.size.height / 2;
8151 [icon_ drawInRect:rect];
8154 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8159 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 61) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8163 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 61) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8166 - (void) setFetch:(NSNumber *)fetch {
8167 if ([fetch boolValue])
8168 [indicator_ startAnimating];
8170 [indicator_ stopAnimating];
8175 /* Sources Controller {{{ */
8176 @interface SourcesController : CyteViewController <
8177 UITableViewDataSource,
8180 _transient Database *database_;
8183 _H<UITableView, 2> list_;
8184 _H<NSMutableArray> sources_;
8188 _H<UIProgressHUD> hud_;
8191 NSURLConnection *trivial_bz2_;
8192 NSURLConnection *trivial_gz_;
8197 - (id) initWithDatabase:(Database *)database;
8198 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8202 @implementation SourcesController
8204 - (void) _releaseConnection:(NSURLConnection *)connection {
8205 if (connection != nil) {
8206 [connection cancel];
8207 //[connection setDelegate:nil];
8208 [connection release];
8213 [self _releaseConnection:trivial_gz_];
8214 [self _releaseConnection:trivial_bz2_];
8219 - (NSURL *) navigationURL {
8220 return [NSURL URLWithString:@"cydia://sources"];
8223 - (void) viewDidAppear:(BOOL)animated {
8224 [super viewDidAppear:animated];
8225 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8228 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8232 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8234 return UCLocalize("INDIVIDUAL_SOURCES");
8238 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8241 case 1: return [sources_ count];
8246 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8247 @synchronized (database_) {
8248 if ([database_ era] != era_)
8250 if ([indexPath section] != 1)
8252 NSUInteger index([indexPath row]);
8253 if (index >= [sources_ count])
8255 return [sources_ objectAtIndex:index];
8258 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8259 static NSString *cellIdentifier = @"SourceCell";
8261 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8262 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8263 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8265 Source *source([self sourceAtIndexPath:indexPath]);
8267 [cell setAllSource];
8269 [cell setSource:source];
8274 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8275 SectionsController *controller([[[SectionsController alloc]
8276 initWithDatabase:database_
8277 source:[self sourceAtIndexPath:indexPath]
8280 [controller setDelegate:delegate_];
8281 [[self navigationController] pushViewController:controller animated:YES];
8284 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8285 if ([indexPath section] != 1)
8287 Source *source = [self sourceAtIndexPath:indexPath];
8288 return [source record] != nil;
8291 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8292 _assert([indexPath section] == 1);
8293 if (editingStyle == UITableViewCellEditingStyleDelete) {
8294 Source *source = [self sourceAtIndexPath:indexPath];
8295 if (source == nil) return;
8297 [Sources_ removeObjectForKey:[source key]];
8300 [delegate_ _saveConfig];
8301 [delegate_ reloadDataWithInvocation:nil];
8306 [delegate_ addTrivialSource:href_];
8309 [delegate_ syncData];
8312 - (NSString *) getWarning {
8313 NSString *href(href_);
8314 NSRange colon([href rangeOfString:@"://"]);
8315 if (colon.location != NSNotFound)
8316 href = [href substringFromIndex:(colon.location + 3)];
8317 href = [href stringByAddingPercentEscapes];
8318 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8320 NSURL *url([NSURL URLWithString:href]);
8322 NSStringEncoding encoding;
8323 NSError *error(nil);
8325 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8326 return [warning length] == 0 ? nil : warning;
8330 - (void) _endConnection:(NSURLConnection *)connection {
8331 // XXX: the memory management in this method is horribly awkward
8333 NSURLConnection **field = NULL;
8334 if (connection == trivial_bz2_)
8335 field = &trivial_bz2_;
8336 else if (connection == trivial_gz_)
8337 field = &trivial_gz_;
8338 _assert(field != NULL);
8339 [connection release];
8343 trivial_bz2_ == nil &&
8346 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8348 [delegate_ releaseNetworkActivityIndicator];
8350 [delegate_ removeProgressHUD:hud_];
8354 if (warning != nil) {
8355 UIAlertView *alert = [[[UIAlertView alloc]
8356 initWithTitle:UCLocalize("SOURCE_WARNING")
8359 cancelButtonTitle:UCLocalize("CANCEL")
8361 UCLocalize("ADD_ANYWAY"),
8365 [alert setContext:@"warning"];
8366 [alert setNumberOfRows:1];
8369 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8375 } else if (error_ != nil) {
8376 UIAlertView *alert = [[[UIAlertView alloc]
8377 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8378 message:[error_ localizedDescription]
8380 cancelButtonTitle:UCLocalize("OK")
8381 otherButtonTitles:nil
8384 [alert setContext:@"urlerror"];
8389 UIAlertView *alert = [[[UIAlertView alloc]
8390 initWithTitle:UCLocalize("NOT_REPOSITORY")
8391 message:UCLocalize("NOT_REPOSITORY_EX")
8393 cancelButtonTitle:UCLocalize("OK")
8394 otherButtonTitles:nil
8397 [alert setContext:@"trivial"];
8407 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8408 switch ([response statusCode]) {
8414 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8415 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8417 [self _endConnection:connection];
8420 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8421 [self _endConnection:connection];
8424 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8425 NSURL *url([NSURL URLWithString:href]);
8427 NSMutableURLRequest *request = [NSMutableURLRequest
8429 cachePolicy:NSURLRequestUseProtocolCachePolicy
8433 [request setHTTPMethod:method];
8435 if (Machine_ != NULL)
8436 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8438 if (UniqueID_ != nil)
8439 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8441 if ([url isCydiaSecure]) {
8442 if (UniqueID_ != nil)
8443 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8446 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8449 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8450 NSString *context([alert context]);
8452 if ([context isEqualToString:@"source"]) {
8455 NSString *href = [[alert textField] text];
8457 static Pcre href_r("^http(s?)://[^# ]*$");
8458 if (!href_r(href)) {
8459 UIAlertView *alert = [[[UIAlertView alloc]
8460 initWithTitle:Error_
8461 message:UCLocalize("INVALID_URL")
8463 cancelButtonTitle:UCLocalize("OK")
8464 otherButtonTitles:nil
8467 [alert setContext:@"badurl"];
8473 if (![href hasSuffix:@"/"])
8474 href_ = [href stringByAppendingString:@"/"];
8478 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8479 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8483 // XXX: this is stupid
8484 hud_ = [delegate_ addProgressHUD];
8485 [hud_ setText:UCLocalize("VERIFYING_URL")];
8486 [delegate_ retainNetworkActivityIndicator];
8495 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8496 } else if ([context isEqualToString:@"trivial"])
8497 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8498 else if ([context isEqualToString:@"urlerror"])
8499 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8500 else if ([context isEqualToString:@"warning"]) {
8503 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8512 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8516 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8517 BOOL editing([list_ isEditing]);
8520 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8521 initWithTitle:UCLocalize("ADD")
8522 style:UIBarButtonItemStylePlain
8524 action:@selector(addButtonClicked)
8525 ] autorelease] animated:animated];
8526 else if ([delegate_ updating])
8527 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8528 initWithTitle:UCLocalize("CANCEL")
8529 style:UIBarButtonItemStyleDone
8531 action:@selector(cancelButtonClicked)
8532 ] autorelease] animated:animated];
8534 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8535 initWithTitle:UCLocalize("REFRESH")
8536 style:UIBarButtonItemStylePlain
8538 action:@selector(refreshButtonClicked)
8539 ] autorelease] animated:animated];
8541 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8542 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8543 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8545 action:@selector(editButtonClicked)
8546 ] autorelease] animated:animated];
8550 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8551 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8552 [list_ setRowHeight:53];
8553 [(UITableView *) list_ setDataSource:self];
8554 [list_ setDelegate:self];
8555 [self setView:list_];
8558 - (void) viewDidLoad {
8559 [super viewDidLoad];
8561 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8562 [self updateButtonsForEditingStatusAnimated:NO];
8565 - (void) viewWillAppear:(BOOL)animated {
8566 [super viewWillAppear:animated];
8568 [list_ setEditing:NO];
8569 [self updateButtonsForEditingStatusAnimated:NO];
8572 - (void) releaseSubviews {
8577 [super releaseSubviews];
8580 - (id) initWithDatabase:(Database *)database {
8581 if ((self = [super init]) != nil) {
8582 database_ = database;
8586 - (void) reloadData {
8588 [self updateButtonsForEditingStatusAnimated:YES];
8590 @synchronized (database_) {
8591 era_ = [database_ era];
8593 sources_ = [NSMutableArray arrayWithCapacity:16];
8594 [sources_ addObjectsFromArray:[database_ sources]];
8596 [sources_ sortUsingSelector:@selector(compareByName:)];
8599 int count([sources_ count]);
8601 for (int i = 0; i != count; i++) {
8602 if ([[sources_ objectAtIndex:i] record] == nil)
8610 - (void) showAddSourcePrompt {
8611 UIAlertView *alert = [[[UIAlertView alloc]
8612 initWithTitle:UCLocalize("ENTER_APT_URL")
8615 cancelButtonTitle:UCLocalize("CANCEL")
8617 UCLocalize("ADD_SOURCE"),
8621 [alert setContext:@"source"];
8623 [alert setNumberOfRows:1];
8624 [alert addTextFieldWithValue:@"http://" label:@""];
8626 UITextInputTraits *traits = [[alert textField] textInputTraits];
8627 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8628 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8629 [traits setKeyboardType:UIKeyboardTypeURL];
8630 // XXX: UIReturnKeyDone
8631 [traits setReturnKeyType:UIReturnKeyNext];
8636 - (void) addButtonClicked {
8637 [self showAddSourcePrompt];
8640 - (void) refreshButtonClicked {
8641 if ([delegate_ requestUpdate])
8642 [self updateButtonsForEditingStatusAnimated:YES];
8645 - (void) cancelButtonClicked {
8646 [delegate_ cancelUpdate];
8649 - (void) editButtonClicked {
8650 [list_ setEditing:![list_ isEditing] animated:YES];
8651 [self updateButtonsForEditingStatusAnimated:YES];
8657 /* Stash Controller {{{ */
8658 @interface StashController : CyteViewController {
8659 _H<UIActivityIndicatorView> spinner_;
8660 _H<UILabel> status_;
8661 _H<UILabel> caption_;
8666 @implementation StashController
8669 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8670 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8671 [self setView:view];
8673 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8675 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8676 CGRect spinrect = [spinner_ frame];
8677 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8678 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8679 [spinner_ setFrame:spinrect];
8680 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8681 [view addSubview:spinner_];
8682 [spinner_ startAnimating];
8685 captrect.size.width = [[self view] frame].size.width;
8686 captrect.size.height = 40.0f;
8687 captrect.origin.x = 0;
8688 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8689 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8690 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8691 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8692 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8693 [caption_ setTextColor:[UIColor whiteColor]];
8694 [caption_ setBackgroundColor:[UIColor clearColor]];
8695 [caption_ setShadowColor:[UIColor blackColor]];
8696 [caption_ setTextAlignment:UITextAlignmentCenter];
8697 [view addSubview:caption_];
8700 statusrect.size.width = [[self view] frame].size.width;
8701 statusrect.size.height = 30.0f;
8702 statusrect.origin.x = 0;
8703 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8704 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8705 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8706 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8707 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8708 [status_ setTextColor:[UIColor whiteColor]];
8709 [status_ setBackgroundColor:[UIColor clearColor]];
8710 [status_ setShadowColor:[UIColor blackColor]];
8711 [status_ setTextAlignment:UITextAlignmentCenter];
8712 [view addSubview:status_];
8715 - (void) releaseSubviews {
8720 [super releaseSubviews];
8726 @interface CYURLCache : SDURLCache {
8731 @implementation CYURLCache
8733 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8736 else if ([event isEqualToString:@"no-cache"])
8738 else if ([event isEqualToString:@"store"])
8740 else if ([event isEqualToString:@"invalid"])
8742 else if ([event isEqualToString:@"memory"])
8744 else if ([event isEqualToString:@"disk"])
8746 else if ([event isEqualToString:@"miss"])
8749 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8753 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8754 if (NSURLResponse *response = [cached response])
8755 if (NSString *mime = [response MIMEType])
8756 if ([mime isEqualToString:@"text/cache-manifest"]) {
8757 NSURL *url([response URL]);
8760 NSLog(@"###: %@", [url absoluteString]);
8763 @synchronized (HostConfig_) {
8764 [CachedURLs_ addObject:url];
8768 [super storeCachedResponse:cached forRequest:request];
8773 @interface Cydia : UIApplication <
8774 ConfirmationControllerDelegate,
8777 UINavigationControllerDelegate,
8778 UITabBarControllerDelegate
8780 _H<UIWindow> window_;
8781 _H<CydiaTabBarController> tabbar_;
8782 _H<CydiaLoadingViewController> emulated_;
8784 _H<NSMutableArray> essential_;
8785 _H<NSMutableArray> broken_;
8787 Database *database_;
8789 _H<NSURL> starturl_;
8794 _H<StashController> stash_;
8803 @implementation Cydia
8805 - (void) lockSuspend {
8806 if (locked_++ == 0) {
8807 if ($SBSSetInterceptsMenuButtonForever != NULL)
8808 (*$SBSSetInterceptsMenuButtonForever)(true);
8810 [self setIdleTimerDisabled:YES];
8814 - (void) unlockSuspend {
8815 if (--locked_ == 0) {
8816 [self setIdleTimerDisabled:NO];
8818 if ($SBSSetInterceptsMenuButtonForever != NULL)
8819 (*$SBSSetInterceptsMenuButtonForever)(false);
8823 - (void) beginUpdate {
8824 [tabbar_ beginUpdate];
8827 - (void) cancelUpdate {
8828 [tabbar_ cancelUpdate];
8831 - (bool) requestUpdate {
8832 if (IsReachable("cydia.saurik.com")) {
8836 UIAlertView *alert = [[[UIAlertView alloc]
8837 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8838 message:@"Host Unreachable" // XXX: Localize
8840 cancelButtonTitle:UCLocalize("OK")
8841 otherButtonTitles:nil
8844 [alert setContext:@"norefresh"];
8852 return [tabbar_ updating];
8856 if ([broken_ count] != 0) {
8857 int count = [broken_ count];
8859 UIAlertView *alert = [[[UIAlertView alloc]
8860 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8861 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8863 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8865 UCLocalize("TEMPORARY_IGNORE"),
8869 [alert setContext:@"fixhalf"];
8870 [alert setNumberOfRows:2];
8872 } else if (!Ignored_ && [essential_ count] != 0) {
8873 int count = [essential_ count];
8875 UIAlertView *alert = [[[UIAlertView alloc]
8876 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8877 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8879 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8881 UCLocalize("UPGRADE_ESSENTIAL"),
8882 UCLocalize("COMPLETE_UPGRADE"),
8886 [alert setContext:@"upgrade"];
8891 - (void) returnToCydia {
8895 - (void) _saveConfig {
8896 @synchronized (database_) {
8903 NSString *error(nil);
8905 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8907 NSError *error(nil);
8908 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8909 NSLog(@"failure to save metadata data: %@", error);
8914 NSLog(@"failure to serialize metadata: %@", error);
8918 CydiaWriteSources();
8921 // Navigation controller for the queuing badge.
8922 - (UINavigationController *) queueNavigationController {
8923 NSArray *controllers = [tabbar_ viewControllers];
8924 return [controllers objectAtIndex:3];
8927 - (void) unloadData {
8928 [tabbar_ unloadData];
8931 - (void) _updateData {
8935 UINavigationController *navigation = [self queueNavigationController];
8937 id queuedelegate = nil;
8938 if ([[navigation viewControllers] count] > 0)
8939 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8941 [queuedelegate queueStatusDidChange];
8942 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8945 - (void) _refreshIfPossible:(NSDate *)update {
8946 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8948 bool recently = false;
8949 if (update != nil) {
8950 NSTimeInterval interval([update timeIntervalSinceNow]);
8951 if (interval <= 0 && interval > -(15*60))
8955 // Don't automatic refresh if:
8956 // - We already refreshed recently.
8957 // - We already auto-refreshed this launch.
8958 // - Auto-refresh is disabled.
8959 // - Cydia's server is not reachable
8960 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
8961 // If we are cancelling, we need to make sure it knows it's already loaded.
8964 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8966 // We are going to load, so remember that.
8969 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8975 - (void) refreshIfPossible {
8976 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8979 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8980 @synchronized (self) {
8981 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8983 [hud setText:UCLocalize("RELOADING_DATA")];
8985 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8989 [essential_ removeAllObjects];
8990 [broken_ removeAllObjects];
8992 NSArray *packages([database_ packages]);
8993 for (Package *package in packages) {
8995 [broken_ addObject:package];
8996 if ([package upgradableAndEssential:YES] && ![package ignored]) {
8997 if ([package essential] && [package installed] != nil)
8998 [essential_ addObject:package];
9003 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9006 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9007 [changesItem setBadgeValue:badge];
9008 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9009 [self setApplicationIconBadgeNumber:changes];
9012 [changesItem setBadgeValue:nil];
9013 [changesItem setAnimatedBadge:NO];
9014 [self setApplicationIconBadgeNumber:0];
9020 [self removeProgressHUD:hud];
9023 - (void) updateData {
9027 - (void) updateDataAndLoad {
9029 if ([database_ progressDelegate] == nil)
9035 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9038 - (void) disemulate {
9039 if (emulated_ == nil)
9042 [window_ addSubview:[tabbar_ view]];
9043 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9044 [window_ setRootViewController:tabbar_];
9045 [[emulated_ view] removeFromSuperview];
9047 [window_ setUserInteractionEnabled:YES];
9050 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9051 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9053 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9055 UIViewController *parent;
9056 if (emulated_ == nil)
9065 [parent presentModalViewController:navigation animated:YES];
9068 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9069 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9071 if (navigation != nil)
9072 [navigation pushViewController:progress animated:YES];
9074 [self presentModalViewController:progress force:YES];
9076 [progress invoke:invocation withTitle:title];
9080 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9081 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9084 - (void) repairWithInvocation:(NSInvocation *)invocation {
9086 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9090 - (void) repairWithSelector:(SEL)selector {
9091 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9094 - (void) reloadData {
9095 [self reloadDataWithInvocation:nil];
9096 if ([database_ progressDelegate] == nil)
9102 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9105 - (void) addSource:(NSDictionary *) source {
9106 CydiaAddSource(source);
9109 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9110 CydiaAddSource(href, distribution, sections);
9113 - (void) addTrivialSource:(NSString *)href {
9114 CydiaAddSource(href, @"./");
9117 - (void) updateValues {
9122 pkgProblemResolver *resolver = [database_ resolver];
9124 resolver->InstallProtect();
9125 if (!resolver->Resolve(true))
9130 // XXX: this is a really crappy way of doing this.
9131 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9132 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9133 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9134 if ([tabbar_ updating])
9135 [tabbar_ cancelUpdate];
9137 if (![database_ prepare])
9140 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9141 [page setDelegate:self];
9142 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9145 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9146 [tabbar_ presentModalViewController:confirm_ animated:YES];
9152 @synchronized (self) {
9157 - (void) clearPackage:(Package *)package {
9158 @synchronized (self) {
9165 - (void) installPackages:(NSArray *)packages {
9166 @synchronized (self) {
9167 for (Package *package in packages)
9174 - (void) installPackage:(Package *)package {
9175 @synchronized (self) {
9182 - (void) removePackage:(Package *)package {
9183 @synchronized (self) {
9190 - (void) distUpgrade {
9191 @synchronized (self) {
9192 if (![database_ upgrade])
9200 system("su -c /usr/bin/uicache mobile");
9205 UIProgressHUD *hud([self addProgressHUD]);
9206 [hud setText:UCLocalize("LOADING")];
9207 [self yieldToSelector:@selector(_uicache)];
9208 [self removeProgressHUD:hud];
9212 [database_ perform];
9213 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9214 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9217 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9220 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9221 [self unlockSuspend];
9224 - (void) retainNetworkActivityIndicator {
9225 if (activity_++ == 0)
9226 [self setNetworkActivityIndicatorVisible:YES];
9229 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9233 - (void) releaseNetworkActivityIndicator {
9234 if (--activity_ == 0)
9235 [self setNetworkActivityIndicatorVisible:NO];
9238 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9243 - (void) cancelAndClear:(bool)clear {
9244 @synchronized (self) {
9256 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9257 NSString *context([alert context]);
9259 if ([context isEqualToString:@"conffile"]) {
9260 FILE *input = [database_ input];
9261 if (button == [alert cancelButtonIndex])
9262 fprintf(input, "N\n");
9263 else if (button == [alert firstOtherButtonIndex])
9264 fprintf(input, "Y\n");
9267 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9268 } else if ([context isEqualToString:@"fixhalf"]) {
9269 if (button == [alert cancelButtonIndex]) {
9270 @synchronized (self) {
9271 for (Package *broken in (id) broken_) {
9274 NSString *id = [broken id];
9275 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9276 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9277 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9278 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9284 } else if (button == [alert firstOtherButtonIndex]) {
9285 [broken_ removeAllObjects];
9289 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9290 } else if ([context isEqualToString:@"upgrade"]) {
9291 if (button == [alert firstOtherButtonIndex]) {
9292 @synchronized (self) {
9293 for (Package *essential in (id) essential_)
9294 [essential install];
9299 } else if (button == [alert firstOtherButtonIndex] + 1) {
9301 } else if (button == [alert cancelButtonIndex]) {
9305 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9309 - (void) system:(NSString *)command {
9310 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9313 system([command UTF8String]);
9319 - (void) applicationWillSuspend {
9321 [super applicationWillSuspend];
9324 - (BOOL) isSafeToSuspend {
9327 NSLog(@"isSafeToSuspend: locked_ != 0");
9332 // Use external process status API internally.
9333 // This is probably a really bad idea.
9334 // XXX: what is the point of this? does this solve anything at all?
9335 uint64_t status = 0;
9337 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9338 notify_get_state(notify_token, &status);
9339 notify_cancel(notify_token);
9344 NSLog(@"isSafeToSuspend: status != 0");
9350 NSLog(@"isSafeToSuspend: -> true");
9355 - (void) applicationSuspend:(__GSEvent *)event {
9356 if ([self isSafeToSuspend])
9357 [super applicationSuspend:event];
9360 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9361 if ([self isSafeToSuspend])
9362 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9365 - (void) _setSuspended:(BOOL)value {
9366 if ([self isSafeToSuspend])
9367 [super _setSuspended:value];
9370 - (UIProgressHUD *) addProgressHUD {
9371 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9372 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9374 [window_ setUserInteractionEnabled:NO];
9376 UIViewController *target(tabbar_);
9377 if (UIViewController *modal = [target modalViewController])
9380 [hud showInView:[target view]];
9386 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9387 [self unlockSuspend];
9389 [hud removeFromSuperview];
9390 [window_ setUserInteractionEnabled:YES];
9393 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9394 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9397 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9398 NSString *scheme([[url scheme] lowercaseString]);
9399 if ([[url absoluteString] length] <= [scheme length] + 3)
9401 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9402 NSArray *components([path componentsSeparatedByString:@"/"]);
9404 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9405 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9406 if (controller != nil)
9407 [controller setDelegate:self];
9411 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9414 NSString *base([components objectAtIndex:0]);
9416 CyteViewController *controller = nil;
9418 if ([base isEqualToString:@"url"]) {
9419 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9420 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9421 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9422 } else if (!external && [components count] == 1) {
9423 if ([base isEqualToString:@"sources"]) {
9424 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9427 if ([base isEqualToString:@"home"]) {
9428 controller = [[[HomeController alloc] init] autorelease];
9431 if ([base isEqualToString:@"sections"]) {
9432 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9435 if ([base isEqualToString:@"search"]) {
9436 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9439 if ([base isEqualToString:@"changes"]) {
9440 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9443 if ([base isEqualToString:@"installed"]) {
9444 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9446 } else if ([components count] == 2) {
9447 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9449 if ([base isEqualToString:@"package"]) {
9450 controller = [self pageForPackage:argument withReferrer:referrer];
9453 if (!external && [base isEqualToString:@"search"]) {
9454 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9457 if (!external && [base isEqualToString:@"sections"]) {
9458 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9460 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9463 if (!external && [base isEqualToString:@"sources"]) {
9464 if ([argument isEqualToString:@"add"]) {
9465 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9466 [(SourcesController *)controller showAddSourcePrompt];
9468 Source *source([database_ sourceWithKey:argument]);
9469 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9473 if (!external && [base isEqualToString:@"launch"]) {
9474 [self launchApplicationWithIdentifier:argument suspended:NO];
9477 } else if (!external && [components count] == 3) {
9478 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9479 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9481 if ([base isEqualToString:@"package"]) {
9482 if ([arg2 isEqualToString:@"settings"]) {
9483 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9484 } else if ([arg2 isEqualToString:@"files"]) {
9485 if (Package *package = [database_ packageWithName:arg1]) {
9486 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9487 [(FileTable *)controller setPackage:package];
9492 if ([base isEqualToString:@"sections"]) {
9493 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9494 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9495 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9499 [controller setDelegate:self];
9503 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9504 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9507 [tabbar_ setUnselectedViewController:page];
9512 - (void) applicationOpenURL:(NSURL *)url {
9513 [super applicationOpenURL:url];
9518 [self openCydiaURL:url forExternal:YES];
9521 - (void) applicationWillResignActive:(UIApplication *)application {
9522 // Stop refreshing if you get a phone call or lock the device.
9523 if ([tabbar_ updating])
9524 [tabbar_ cancelUpdate];
9526 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9527 [super applicationWillResignActive:application];
9530 - (void) saveState {
9531 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9532 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9533 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9539 - (void) applicationWillTerminate:(UIApplication *)application {
9543 - (void) setConfigurationData:(NSString *)data {
9544 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9546 if (!conffile_r(data)) {
9547 lprintf("E:invalid conffile\n");
9551 NSString *ofile = conffile_r[1];
9552 //NSString *nfile = conffile_r[2];
9554 UIAlertView *alert = [[[UIAlertView alloc]
9555 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9556 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9558 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9560 UCLocalize("ACCEPT_NEW_COPY"),
9561 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9565 [alert setContext:@"conffile"];
9566 [alert setNumberOfRows:2];
9570 - (void) addStashController {
9572 stash_ = [[[StashController alloc] init] autorelease];
9573 [window_ addSubview:[stash_ view]];
9576 - (void) removeStashController {
9577 [[stash_ view] removeFromSuperview];
9579 [self unlockSuspend];
9583 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9584 UpdateExternalStatus(1);
9585 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9586 UpdateExternalStatus(0);
9588 [self removeStashController];
9590 pid_t pid(ExecFork());
9592 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9593 perror("launchctl stop");
9599 - (void) setupViewControllers {
9600 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9602 NSMutableArray *items;
9603 if (kCFCoreFoundationVersionNumber < 800) {
9604 items = [NSMutableArray arrayWithObjects:
9605 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9606 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9607 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9608 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease],
9609 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9612 items = [NSMutableArray arrayWithObjects:
9613 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home7.png"] selectedImage:[UIImage applicationImageNamed:@"home7s.png"]] autorelease],
9614 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install7.png"] selectedImage:[UIImage applicationImageNamed:@"install7s.png"]] autorelease],
9615 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes7.png"] selectedImage:[UIImage applicationImageNamed:@"changes7s.png"]] autorelease],
9616 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage7.png"] selectedImage:[UIImage applicationImageNamed:@"manage7s.png"]] autorelease],
9617 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search7.png"] selectedImage:[UIImage applicationImageNamed:@"search7s.png"]] autorelease],
9621 NSMutableArray *controllers([NSMutableArray array]);
9622 for (UITabBarItem *item in items) {
9623 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9624 [controller setTabBarItem:item];
9625 [controllers addObject:controller];
9627 [tabbar_ setViewControllers:controllers];
9629 [tabbar_ setUpdateDelegate:self];
9632 - (void) _sendMemoryWarningNotification {
9633 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9634 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9636 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9639 - (void) _sendMemoryWarningNotifications {
9641 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9647 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9649 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9652 - (void) applicationDidFinishLaunching:(id)unused {
9653 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9656 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9657 [self setApplicationSupportsShakeToEdit:NO];
9659 @synchronized (HostConfig_) {
9660 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9663 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9664 initWithMemoryCapacity:524288
9665 diskCapacity:10485760
9666 diskPath:[NSString stringWithFormat:@"%@/SDURLCache", Cache_]
9669 [CydiaWebViewController _initialize];
9671 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9673 // this would disallow http{,s} URLs from accessing this data
9674 //[WebView registerURLSchemeAsLocal:@"cydia"];
9676 Font12_ = [UIFont systemFontOfSize:12];
9677 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9678 Font14_ = [UIFont systemFontOfSize:14];
9679 Font18_ = [UIFont systemFontOfSize:18];
9680 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9681 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9683 essential_ = [NSMutableArray arrayWithCapacity:4];
9684 broken_ = [NSMutableArray arrayWithCapacity:4];
9686 // XXX: I really need this thing... like, seriously... I'm sorry
9687 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9689 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9690 [window_ orderFront:self];
9691 [window_ makeKey:self];
9692 [window_ setHidden:NO];
9695 [self addStashController];
9696 // XXX: this would be much cleaner as a yieldToSelector:
9697 // that way the removeStashController could happen right here inline
9698 // we also could no longer require the useless stash_ field anymore
9699 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9704 int error(stat("/", &root));
9705 _assert(error != -1);
9707 #define Stash_(path) do { \
9708 struct stat folder; \
9709 int error(lstat((path), &folder)); \
9710 if (error != -1 && ( \
9711 folder.st_dev == root.st_dev && \
9712 S_ISDIR(folder.st_mode) \
9713 ) || error == -1 && ( \
9714 errno == ENOENT || \
9719 Stash_("/Applications");
9720 Stash_("/Library/Ringtones");
9721 Stash_("/Library/Wallpaper");
9722 //Stash_("/usr/bin");
9723 Stash_("/usr/include");
9724 Stash_("/usr/lib/pam");
9725 Stash_("/usr/share");
9726 //Stash_("/var/lib");
9728 database_ = [Database sharedInstance];
9729 [database_ setDelegate:self];
9731 [window_ setUserInteractionEnabled:NO];
9732 [self setupViewControllers];
9734 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9735 [window_ addSubview:[emulated_ view]];
9736 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9737 [window_ setRootViewController:emulated_];
9739 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9743 - (NSArray *) defaultStartPages {
9744 NSMutableArray *standard = [NSMutableArray array];
9745 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9746 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9747 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9748 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9749 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9755 if ([emulated_ modalViewController] != nil)
9756 [emulated_ dismissModalViewControllerAnimated:YES];
9757 [window_ setUserInteractionEnabled:NO];
9759 [self reloadDataWithInvocation:nil];
9760 [self refreshIfPossible];
9765 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9766 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9767 int standardIndex = 0;
9768 NSArray *standard = [self defaultStartPages];
9775 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9776 if (valid && closed != nil) {
9777 NSTimeInterval interval([closed timeIntervalSinceNow]);
9778 // XXX: Is 30 minutes the optimal time here?
9779 if (interval <= -(30*60))
9783 if (valid && [saved count] != [standard count])
9787 for (unsigned int i = 0; i < [standard count]; i++) {
9788 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9789 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9790 // but it's good enough for now.
9791 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9798 NSArray *items = nil;
9800 [tabbar_ setSelectedIndex:savedIndex];
9803 [tabbar_ setSelectedIndex:standardIndex];
9807 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9808 NSArray *stack = [items objectAtIndex:tab];
9809 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9810 NSMutableArray *current = [NSMutableArray array];
9812 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9813 NSString *addr = [stack objectAtIndex:nav];
9814 NSURL *url = [NSURL URLWithString:addr];
9815 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9817 [current addObject:page];
9820 [navigation setViewControllers:current];
9823 // (Try to) show the startup URL.
9824 if (starturl_ != nil) {
9825 [self openCydiaURL:starturl_ forExternal:NO];
9830 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9831 if (item != nil && IsWildcat_) {
9832 [sheet showFromBarButtonItem:item animated:YES];
9834 [sheet showInView:window_];
9838 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9839 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9840 [progress setTitle:task];
9841 [progress addProgressEvent:event];
9844 - (void) addProgressEventForTask:(NSArray *)data {
9845 CydiaProgressEvent *event([data objectAtIndex:0]);
9846 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9847 [self addProgressEvent:event forTask:task];
9850 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9851 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9857 id Alloc_(id self, SEL selector) {
9858 id object = alloc_(self, selector);
9859 lprintf("[%s]A-%p\n", self->isa->name, object);
9864 id Dealloc_(id self, SEL selector) {
9865 id object = dealloc_(self, selector);
9866 lprintf("[%s]D-%p\n", self->isa->name, object);
9870 static NSSet *MobilizedFiles_;
9872 static NSURL *MobilizeURL(NSURL *url) {
9873 NSString *path([url path]);
9874 if ([path hasPrefix:@"/var/root/"]) {
9875 NSString *file([path substringFromIndex:10]);
9876 if ([MobilizedFiles_ containsObject:file])
9877 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9883 Class $CFXPreferencesPropertyListSource;
9884 @class CFXPreferencesPropertyListSource;
9886 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9887 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9888 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9889 url = MobilizeURL(url);
9890 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9891 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9897 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9898 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9899 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9900 url = MobilizeURL(url);
9901 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9902 //NSLog(@"%@ %@", [url absoluteString], value);
9908 Class $NSURLConnection;
9910 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9911 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
9913 NSURL *url([copy URL]);
9915 NSString *host([url host]);
9916 NSString *scheme([[url scheme] lowercaseString]);
9918 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9920 @synchronized (HostConfig_) {
9921 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9922 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9923 [copy setHTTPShouldUsePipelining:YES];
9925 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9926 if ([control isEqualToString:@"max-age=0"])
9927 if ([CachedURLs_ containsObject:url]) {
9929 NSLog(@"~~~: %@", url);
9932 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9934 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9935 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9936 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9940 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9946 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
9947 CGSize size([[UIScreen mainScreen] bounds].size);
9948 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
9949 if ([$WAKWindow hasLandscapeOrientation])
9950 std::swap(size.width, size.height);*/
9954 Class $NSUserDefaults;
9956 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
9957 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
9958 return [NSString stringWithFormat:@"%@/LocalStorage", Cache_];
9959 return _NSUserDefaults$objectForKey$(self, _cmd, key);
9962 int main(int argc, char *argv[]) {
9963 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9967 UpdateExternalStatus(0);
9969 UIScreen *screen([UIScreen mainScreen]);
9970 if ([screen respondsToSelector:@selector(scale)])
9971 ScreenScale_ = [screen scale];
9975 UIDevice *device([UIDevice currentDevice]);
9976 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
9977 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9978 if (idiom == UIUserInterfaceIdiomPad)
9982 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
9984 Pcre pattern("^([0-9]+\\.[0-9]+)");
9986 if (pattern([device systemVersion]))
9987 Firmware_ = pattern[1];
9988 if (pattern(Cydia_))
9989 Major_ = pattern[1];
9991 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9993 HostConfig_ = [[[NSObject alloc] init] autorelease];
9994 @synchronized (HostConfig_) {
9995 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9996 TokenHosts_ = [NSMutableSet setWithCapacity:4];
9997 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9998 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9999 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10002 NSString *ui(@"ui/ios");
10004 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10005 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10006 UI_ = CydiaURL(ui);
10008 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10010 MobilizedFiles_ = [NSMutableSet setWithObjects:
10011 @"Library/Preferences/com.apple.Accessibility.plist",
10012 @"Library/Preferences/com.apple.preferences.sounds.plist",
10015 /* Library Hacks {{{ */
10016 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10018 $WAKWindow = objc_getClass("WAKWindow");
10019 if ($WAKWindow != NULL)
10020 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10021 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10023 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10025 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10026 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10027 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10028 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10031 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10032 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10033 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10034 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10037 $NSURLConnection = objc_getClass("NSURLConnection");
10038 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10039 if (NSURLConnection$init$ != NULL) {
10040 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10041 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10044 $NSUserDefaults = objc_getClass("NSUserDefaults");
10045 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10046 if (NSUserDefaults$objectForKey$ != NULL) {
10047 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10048 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10051 /* Set Locale {{{ */
10052 Locale_ = CFLocaleCopyCurrent();
10053 Languages_ = [NSLocale preferredLanguages];
10055 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10056 //NSLog(@"%@", [Languages_ description]);
10059 if (Locale_ != NULL)
10060 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10061 else if (Languages_ != nil && [Languages_ count] != 0)
10062 lang = [[Languages_ objectAtIndex:0] UTF8String];
10064 // XXX: consider just setting to C and then falling through?
10067 if (lang != NULL) {
10068 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10069 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10072 NSLog(@"Setting Language: %s", lang);
10074 if (lang != NULL) {
10075 setenv("LANG", lang, true);
10076 std::setlocale(LC_ALL, lang);
10080 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10082 /* Parse Arguments {{{ */
10083 bool substrate(false);
10089 for (int argi(1); argi != argc; ++argi)
10090 if (strcmp(argv[argi], "--") == 0) {
10092 argv[argi] = argv[0];
10098 for (int argi(1); argi != arge; ++argi)
10099 if (strcmp(args[argi], "--substrate") == 0)
10102 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10106 App_ = [[NSBundle mainBundle] bundlePath];
10112 if (access("/var/mobile/Library/Keyboard/UserDictionary.sqlite", F_OK) == 0)
10113 system("mkdir -p /var/root/Library/Keyboard; cp -af /var/mobile/Library/Keyboard/UserDictionary.sqlite /var/root/Library/Keyboard/");
10115 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/root"] retain];
10117 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10118 alloc_ = alloc->method_imp;
10119 alloc->method_imp = (IMP) &Alloc_;*/
10121 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10122 dealloc_ = dealloc->method_imp;
10123 dealloc->method_imp = (IMP) &Dealloc_;*/
10125 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10126 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10128 /* System Information {{{ */
10132 size = sizeof(maxproc);
10133 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10134 perror("sysctlbyname(\"kern.maxproc\", ?)");
10135 else if (maxproc < 64) {
10137 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10138 perror("sysctlbyname(\"kern.maxproc\", #)");
10141 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10142 char *osversion = new char[size];
10143 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10144 perror("sysctlbyname(\"kern.osversion\", ?)");
10146 System_ = [NSString stringWithUTF8String:osversion];
10148 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10149 char *machine = new char[size];
10150 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10151 perror("sysctlbyname(\"hw.machine\", ?)");
10153 Machine_ = machine;
10155 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10156 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10157 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10159 UniqueID_ = UniqueIdentifier(device);
10161 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10162 Product_ = [info objectForKey:@"SafariProductVersion"];
10163 Safari_ = [info objectForKey:@"CFBundleVersion"];
10166 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10168 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10169 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10170 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10171 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10172 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10173 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10175 UserAgent_ = agent;
10177 /* Load Database {{{ */
10179 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10181 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10183 if (Metadata_ == NULL)
10184 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10186 Settings_ = [Metadata_ objectForKey:@"Settings"];
10188 Packages_ = [Metadata_ objectForKey:@"Packages"];
10190 Values_ = [Metadata_ objectForKey:@"Values"];
10191 Sections_ = [Metadata_ objectForKey:@"Sections"];
10192 Sources_ = [Metadata_ objectForKey:@"Sources"];
10194 Token_ = [Metadata_ objectForKey:@"Token"];
10196 Version_ = [Metadata_ objectForKey:@"Version"];
10199 if (Values_ == nil) {
10200 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10201 [Metadata_ setObject:Values_ forKey:@"Values"];
10204 if (Sections_ == nil) {
10205 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10206 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10209 if (Sources_ == nil) {
10210 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10211 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10214 if (Version_ == nil) {
10215 Version_ = [NSNumber numberWithUnsignedInt:0];
10216 [Metadata_ setObject:Version_ forKey:@"Version"];
10219 if ([Version_ unsignedIntValue] == 0) {
10220 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10221 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10222 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10223 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10225 Version_ = [NSNumber numberWithUnsignedInt:1];
10226 [Metadata_ setObject:Version_ forKey:@"Version"];
10228 [Metadata_ removeObjectForKey:@"LastUpdate"];
10233 _H<NSMutableArray> broken([NSMutableArray array]);
10234 for (NSString *key in (id) Sources_)
10235 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound)
10236 [broken addObject:key];
10237 if ([broken count] != 0) {
10238 for (NSString *key in (id) broken)
10239 [Sources_ removeObjectForKey:key];
10244 CydiaWriteSources();
10247 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10250 if (Packages_ != nil) {
10252 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10256 [Metadata_ removeObjectForKey:@"Packages"];
10262 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10264 #define MobileSubstrate_(name) \
10265 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10266 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10267 if (handle == NULL) \
10268 NSLog(@"%s", dlerror()); \
10271 MobileSubstrate_(Activator)
10272 MobileSubstrate_(libstatusbar)
10273 MobileSubstrate_(SimulatedKeyEvents)
10274 MobileSubstrate_(WinterBoard)
10276 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10277 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10279 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10281 if (access("/User", F_OK) != 0 || version != 6) {
10283 system("/usr/libexec/cydia/firmware.sh");
10287 _assert([[NSFileManager defaultManager]
10288 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10289 withIntermediateDirectories:YES
10294 if (access("/tmp/cydia.chk", F_OK) == 0) {
10295 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10296 _assert(errno == ENOENT);
10297 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10298 _assert(errno == ENOENT);
10301 /* APT Initialization {{{ */
10302 _assert(pkgInitConfig(*_config));
10303 _assert(pkgInitSystem(*_config, _system));
10306 _config->Set("APT::Acquire::Translation", lang);
10308 // XXX: this timeout might be important :(
10309 //_config->Set("Acquire::http::Timeout", 15);
10311 _config->Set("Acquire::http::MaxParallel", 3);
10313 /* Color Choices {{{ */
10314 space_ = CGColorSpaceCreateDeviceRGB();
10316 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10317 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10318 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10319 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10320 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10321 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10322 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10323 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10324 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10325 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10327 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10328 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10330 /* UIKit Configuration {{{ */
10331 // XXX: I have a feeling this was important
10332 //UIKeyboardDisableAutomaticAppearance();
10335 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10337 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10338 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10339 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10341 PulseInterval_ = fast ? 50000 : 500000;
10343 Colon_ = UCLocalize("COLON_DELIMITED");
10344 Elision_ = UCLocalize("ELISION");
10345 Error_ = UCLocalize("ERROR");
10346 Warning_ = UCLocalize("WARNING");
10349 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10351 CGColorSpaceRelease(space_);
10352 CFRelease(Locale_);