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/CFUniChar.h>
43 #include <SystemConfiguration/SystemConfiguration.h>
45 #include <UIKit/UIKit.h>
46 #include "iPhonePrivate.h"
48 #include <IOKit/IOKitLib.h>
50 #include <QuartzCore/CALayer.h>
52 #include <WebCore/WebCoreThread.h>
53 #include <WebKit/DOMHTMLIFrameElement.h>
61 #include <ext/stdio_filebuf.h>
65 #include <apt-pkg/acquire.h>
66 #include <apt-pkg/acquire-item.h>
67 #include <apt-pkg/algorithms.h>
68 #include <apt-pkg/cachefile.h>
69 #include <apt-pkg/clean.h>
70 #include <apt-pkg/configuration.h>
71 #include <apt-pkg/debindexfile.h>
72 #include <apt-pkg/debmetaindex.h>
73 #include <apt-pkg/error.h>
74 #include <apt-pkg/init.h>
75 #include <apt-pkg/mmap.h>
76 #include <apt-pkg/pkgrecords.h>
77 #include <apt-pkg/sha1.h>
78 #include <apt-pkg/sourcelist.h>
79 #include <apt-pkg/sptr.h>
80 #include <apt-pkg/strutl.h>
81 #include <apt-pkg/tagfile.h>
83 #include <apr-1/apr_pools.h>
85 #include <sys/types.h>
87 #include <sys/sysctl.h>
88 #include <sys/param.h>
89 #include <sys/mount.h>
90 #include <sys/reboot.h>
97 #include <mach-o/nlist.h>
106 #include <Cytore.hpp>
109 #include <CydiaSubstrate/CydiaSubstrate.h>
110 #include "Menes/Menes.h"
112 #include "CyteKit/IndirectDelegate.h"
113 #include "CyteKit/PerlCompatibleRegEx.hpp"
114 #include "CyteKit/TableViewCell.h"
115 #include "CyteKit/TabBarController.h"
116 #include "CyteKit/WebScriptObject-Cyte.h"
117 #include "CyteKit/WebViewController.h"
118 #include "CyteKit/WebViewTableViewCell.h"
119 #include "CyteKit/stringWithUTF8Bytes.h"
121 #include "Cydia/MIMEAddress.h"
122 #include "Cydia/LoadingViewController.h"
123 #include "Cydia/ProgressEvent.h"
125 #include "SDURLCache/SDURLCache.h"
132 #define _timestamp ({ \
134 gettimeofday(&tv, NULL); \
135 tv.tv_sec * 1000000 + tv.tv_usec; \
138 typedef std::vector<class ProfileTime *> TimeList;
148 ProfileTime(const char *name) :
152 times_.push_back(this);
155 void AddTime(uint64_t time) {
162 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
174 ProfileTimer(ProfileTime &time) :
181 time_.AddTime(_timestamp - start_);
186 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
188 std::cerr << "========" << std::endl;
191 #define _profile(name) { \
192 static ProfileTime name(#name); \
193 ProfileTimer _ ## name(name);
198 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
199 #define synchronized(lock) \
200 synchronized(static_cast<NSObject *>(lock))
202 extern NSString *Cydia_;
204 #define lprintf(args...) fprintf(stderr, args)
207 #define TraceLogging (1 && !ForRelease)
208 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
209 #define ProfileTimes (0 && !ForRelease)
210 #define ForSaurik (0 && !ForRelease)
211 #define LogBrowser (0 && !ForRelease)
212 #define TrackResize (0 && !ForRelease)
213 #define ManualRefresh (1 && !ForRelease)
214 #define ShowInternals (0 && !ForRelease)
215 #define AlwaysReload (0 && !ForRelease)
216 #define TryIndexedCollation (0 && !ForRelease)
220 #define _trace(args...)
225 #define _profile(name) {
228 #define PrintTimes() do {} while (false)
231 // Hash Functions/Structures {{{
232 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
240 static NSString *Colon_;
242 static NSString *Error_;
243 static NSString *Warning_;
245 static NSString *Cache_;
247 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
249 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
251 static NSString *UniqueIdentifier(UIDevice *device = nil) {
252 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
253 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
255 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
258 static bool IsReachable(const char *name) {
259 SCNetworkReachabilityFlags flags; {
260 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
261 SCNetworkReachabilityGetFlags(reachability, &flags);
262 CFRelease(reachability);
265 // XXX: this elaborate mess is what Apple is using to determine this? :(
266 // XXX: do we care if the user has to intervene? maybe that's ok?
268 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
269 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
270 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
271 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
272 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
273 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
278 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
280 static _finline NSString *CydiaURL(NSString *path) {
282 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
283 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
284 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
285 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
286 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
288 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
291 static void ReapZombie(pid_t pid) {
294 if (waitpid(pid, &status, 0) == -1)
300 static _finline void UpdateExternalStatus(uint64_t newStatus) {
302 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
303 notify_set_state(notify_token, newStatus);
304 notify_cancel(notify_token);
306 notify_post("com.saurik.Cydia.status");
309 static CGFloat CYStatusBarHeight() {
310 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
311 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
314 /* NSForcedOrderingSearch doesn't work on the iPhone */
315 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
316 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
317 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
319 /* Insertion Sort {{{ */
321 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
322 const char *ptr = (const char *)list;
324 CFIndex half = count / 2;
325 const char *probe = ptr + elementSize * half;
326 CFComparisonResult cr = comparator(element, probe, context);
327 if (0 == cr) return (probe - (const char *)list) / elementSize;
328 ptr = (cr < 0) ? ptr : probe + elementSize;
329 count = (cr < 0) ? half : (half + (count & 1) - 1);
331 return (ptr - (const char *)list) / elementSize;
334 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
335 const char *ptr = (const char *)list;
337 CFIndex half = count / 2;
338 const char *probe = ptr + elementSize * half;
339 CFComparisonResult cr = comparator(element, probe, context);
340 if (0 == cr) return (probe - (const char *)list) / elementSize;
341 ptr = (cr < 0) ? ptr : probe + elementSize;
342 count = (cr < 0) ? half : (half + (count & 1) - 1);
344 return (ptr - (const char *)list) / elementSize;
347 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
348 if (range.length == 0)
350 const void **values(new const void *[range.length]);
351 CFArrayGetValues(array, range, values);
353 #if HistogramInsertionSort > 0
354 uint32_t total(0), *offsets(new uint32_t[range.length]);
357 for (CFIndex index(1); index != range.length; ++index) {
358 const void *value(values[index]);
359 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
360 CFIndex correct(index);
361 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
362 #if HistogramInsertionSort > 1
363 NSLog(@"%@ < %@", value, values[correct - 1]);
368 if (correct != index) {
369 size_t offset(index - correct);
370 #if HistogramInsertionSort
374 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
376 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
377 values[correct] = value;
381 CFArrayReplaceValues(array, range, values, range.length);
384 #if HistogramInsertionSort > 0
385 for (CFIndex index(0); index != range.length; ++index)
386 if (offsets[index] != 0)
387 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
388 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
395 /* Apple Bug Fixes {{{ */
396 @implementation UIWebDocumentView (Cydia)
398 - (void) _setScrollerOffset:(CGPoint)offset {
399 UIScroller *scroller([self _scroller]);
401 CGSize size([scroller contentSize]);
402 CGSize bounds([scroller bounds].size);
405 max.x = size.width - bounds.width;
406 max.y = size.height - bounds.height;
414 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
415 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
417 [scroller setOffset:offset];
423 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
424 size_t length([self length] - state->state);
427 else if (length > count)
429 for (size_t i(0); i != length; ++i)
430 objects[i] = [self item:state->state++];
431 state->itemsPtr = objects;
432 state->mutationsPtr = (unsigned long *) self;
436 /* Cydia NSString Additions {{{ */
437 @interface NSString (Cydia)
438 - (NSComparisonResult) compareByPath:(NSString *)other;
439 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
442 @implementation NSString (Cydia)
444 - (NSComparisonResult) compareByPath:(NSString *)other {
445 NSString *prefix = [self commonPrefixWithString:other options:0];
446 size_t length = [prefix length];
448 NSRange lrange = NSMakeRange(length, [self length] - length);
449 NSRange rrange = NSMakeRange(length, [other length] - length);
451 lrange = [self rangeOfString:@"/" options:0 range:lrange];
452 rrange = [other rangeOfString:@"/" options:0 range:rrange];
454 NSComparisonResult value;
456 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
457 value = NSOrderedSame;
458 else if (lrange.location == NSNotFound)
459 value = NSOrderedAscending;
460 else if (rrange.location == NSNotFound)
461 value = NSOrderedDescending;
463 value = NSOrderedSame;
465 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
466 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
467 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
468 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
470 NSComparisonResult result = [lpath compare:rpath];
471 return result == NSOrderedSame ? value : result;
474 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
475 return [(id)CFURLCreateStringByAddingPercentEscapes(
480 kCFStringEncodingUTF8
487 /* C++ NSString Wrapper Cache {{{ */
488 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
489 return size == 0 ? NULL :
490 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
491 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
494 static _finline CFStringRef CYStringCreate(const char *data) {
495 return CYStringCreate(data, strlen(data));
504 _finline void clear_() {
505 if (cache_ != NULL) {
512 _finline bool empty() const {
516 _finline size_t size() const {
520 _finline char *data() const {
524 _finline void clear() {
529 _finline CYString() :
536 _finline ~CYString() {
540 void operator =(const CYString &rhs) {
544 if (rhs.cache_ == nil)
547 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
550 void copy(apr_pool_t *pool) {
551 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
552 memcpy(temp, data_, size_);
557 void set(apr_pool_t *pool, const char *data, size_t size) {
563 data_ = const_cast<char *>(data);
571 _finline void set(apr_pool_t *pool, const char *data) {
572 set(pool, data, data == NULL ? 0 : strlen(data));
575 _finline void set(apr_pool_t *pool, const std::string &rhs) {
576 set(pool, rhs.data(), rhs.size());
579 bool operator ==(const CYString &rhs) const {
580 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
583 _finline operator CFStringRef() {
585 cache_ = CYStringCreate(data_, size_);
589 _finline operator id() {
590 return (NSString *) static_cast<CFStringRef>(*this);
593 _finline operator const char *() {
594 return reinterpret_cast<const char *>(data_);
598 /* C++ NSString Algorithm Adapters {{{ */
600 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
603 struct NSStringMapHash :
604 std::unary_function<NSString *, size_t>
606 _finline size_t operator ()(NSString *value) const {
607 return CFStringHashNSString((CFStringRef) value);
611 struct NSStringMapLess :
612 std::binary_function<NSString *, NSString *, bool>
614 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
615 return [lhs compare:rhs] == NSOrderedAscending;
619 struct NSStringMapEqual :
620 std::binary_function<NSString *, NSString *, bool>
622 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
623 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
624 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
625 //[lhs isEqualToString:rhs];
630 /* CoreGraphics Primitives {{{ */
635 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
636 CGFloat color[] = {red, green, blue, alpha};
637 return CGColorCreate(space, color);
646 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
647 color_(Create_(space, red, green, blue, alpha))
649 Set(space, red, green, blue, alpha);
654 CGColorRelease(color_);
661 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
663 color_ = Create_(space, red, green, blue, alpha);
666 operator CGColorRef() {
672 /* Random Global Variables {{{ */
673 static int PulseInterval_ = 500000;
675 static const NSString *UI_;
678 static bool RestartSubstrate_;
679 static NSArray *Finishes_;
681 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
682 #define NotifyConfig_ "/etc/notify.conf"
684 static bool Queuing_;
686 static CYColor Blue_;
687 static CYColor Blueish_;
688 static CYColor Black_;
689 static CYColor Folder_;
691 static CYColor White_;
692 static CYColor Gray_;
693 static CYColor Green_;
694 static CYColor Purple_;
695 static CYColor Purplish_;
697 static UIColor *InstallingColor_;
698 static UIColor *RemovingColor_;
700 static NSString *App_;
702 static BOOL Advanced_;
703 static BOOL Ignored_;
705 static _H<UIFont> Font12_;
706 static _H<UIFont> Font12Bold_;
707 static _H<UIFont> Font14_;
708 static _H<UIFont> Font18_;
709 static _H<UIFont> Font18Bold_;
710 static _H<UIFont> Font22Bold_;
712 static const char *Machine_ = NULL;
713 static _H<NSString> System_;
714 static NSString *SerialNumber_ = nil;
715 static NSString *ChipID_ = nil;
716 static NSString *BBSNum_ = nil;
717 static _H<NSString> Token_;
718 static _H<NSString> UniqueID_;
719 static _H<NSString> UserAgent_;
720 static _H<NSString> Product_;
721 static _H<NSString> Safari_;
723 static CFLocaleRef Locale_;
724 static NSArray *Languages_;
725 static CGColorSpaceRef space_;
727 static NSDictionary *SectionMap_;
728 static NSMutableDictionary *Metadata_;
729 static _transient NSMutableDictionary *Settings_;
730 static _transient NSMutableDictionary *Packages_;
731 static _transient NSMutableDictionary *Values_;
732 static _transient NSMutableDictionary *Sections_;
733 _H<NSMutableDictionary> Sources_;
734 static _transient NSNumber *Version_;
739 static CGFloat ScreenScale_;
740 static NSString *Idiom_;
741 static _H<NSString> Firmware_;
742 static NSString *Major_;
744 static _H<NSMutableDictionary> SessionData_;
745 static _H<NSObject> HostConfig_;
746 static _H<NSMutableSet> BridgedHosts_;
747 static _H<NSMutableSet> TokenHosts_;
748 static _H<NSMutableSet> InsecureHosts_;
749 static _H<NSMutableSet> PipelinedHosts_;
750 static _H<NSMutableSet> CachedURLs_;
752 static NSString *kCydiaProgressEventTypeError = @"Error";
753 static NSString *kCydiaProgressEventTypeInformation = @"Information";
754 static NSString *kCydiaProgressEventTypeStatus = @"Status";
755 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
758 /* Display Helpers {{{ */
759 inline float Interpolate(float begin, float end, float fraction) {
760 return (end - begin) * fraction + begin;
763 static _finline const char *StripVersion_(const char *version) {
764 const char *colon(strchr(version, ':'));
765 return colon == NULL ? version : colon + 1;
768 NSString *LocalizeSection(NSString *section) {
769 static Pcre title_r("^(.*?) \\((.*)\\)$");
770 if (title_r(section)) {
771 NSString *parent(title_r[1]);
772 NSString *child(title_r[2]);
774 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
775 LocalizeSection(parent),
776 LocalizeSection(child)
780 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
783 NSString *Simplify(NSString *title) {
784 const char *data = [title UTF8String];
785 size_t size = [title length];
787 static Pcre square_r("^\\[(.*)\\]$");
788 if (square_r(data, size))
789 return Simplify(square_r[1]);
791 static Pcre paren_r("^\\((.*)\\)$");
792 if (paren_r(data, size))
793 return Simplify(paren_r[1]);
795 static Pcre title_r("^(.*?) \\((.*)\\)$");
796 if (title_r(data, size))
797 return Simplify(title_r[1]);
803 NSString *GetLastUpdate() {
804 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
807 return UCLocalize("NEVER_OR_UNKNOWN");
809 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
810 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
812 CFRelease(formatter);
814 return [(NSString *) formatted autorelease];
817 bool isSectionVisible(NSString *section) {
818 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
819 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
820 return hidden == nil || ![hidden boolValue];
823 static NSObject *CYIOGetValue(const char *path, NSString *property) {
824 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
825 if (entry == MACH_PORT_NULL)
828 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
829 IOObjectRelease(entry);
833 return [(id) value autorelease];
836 static NSString *CYHex(NSData *data, bool reverse = false) {
840 size_t length([data length]);
841 uint8_t bytes[length];
842 [data getBytes:bytes];
844 char string[length * 2 + 1];
845 for (size_t i(0); i != length; ++i)
846 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
848 return [NSString stringWithUTF8String:string];
853 /* Delegate Prototypes {{{ */
856 @class CydiaProgressEvent;
858 @protocol DatabaseDelegate
859 - (void) repairWithSelector:(SEL)selector;
860 - (void) setConfigurationData:(NSString *)data;
861 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
864 @class CYPackageController;
866 @protocol SourceDelegate
867 - (void) setFetch:(NSNumber *)fetch;
870 @protocol FetchDelegate
871 - (bool) isSourceCancelled;
872 - (void) startSourceFetch:(NSString *)uri;
873 - (void) stopSourceFetch:(NSString *)uri;
876 @protocol CydiaDelegate
877 - (void) returnToCydia;
879 - (void) retainNetworkActivityIndicator;
880 - (void) releaseNetworkActivityIndicator;
881 - (void) clearPackage:(Package *)package;
882 - (void) installPackage:(Package *)package;
883 - (void) installPackages:(NSArray *)packages;
884 - (void) removePackage:(Package *)package;
885 - (void) beginUpdate;
887 - (bool) requestUpdate;
888 - (void) distUpgrade;
891 - (void) _saveConfig;
893 - (void) addSource:(NSDictionary *)source;
894 - (void) addTrivialSource:(NSString *)href;
895 - (UIProgressHUD *) addProgressHUD;
896 - (void) removeProgressHUD:(UIProgressHUD *)hud;
897 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
898 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
902 /* CancelStatus {{{ */
904 public pkgAcquireStatus
915 virtual bool MediaChange(std::string media, std::string drive) {
919 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
923 virtual bool Pulse_(pkgAcquire *Owner) = 0;
925 virtual bool Pulse(pkgAcquire *Owner) {
926 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
934 _finline bool WasCancelled() const {
939 /* DelegateStatus {{{ */
944 _transient NSObject<ProgressDelegate> *delegate_;
952 void setDelegate(NSObject<ProgressDelegate> *delegate) {
953 delegate_ = delegate;
956 virtual void Fetch(pkgAcquire::ItemDesc &item) {
957 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
958 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
959 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
962 virtual void Done(pkgAcquire::ItemDesc &item) {
963 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
964 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
965 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
968 virtual void Fail(pkgAcquire::ItemDesc &item) {
970 item.Owner->Status == pkgAcquire::Item::StatIdle ||
971 item.Owner->Status == pkgAcquire::Item::StatDone
975 std::string &error(item.Owner->ErrorText);
979 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
980 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
983 virtual bool Pulse_(pkgAcquire *Owner) {
985 double(CurrentBytes + CurrentItems) /
986 double(TotalBytes + TotalItems)
989 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
990 [NSNumber numberWithDouble:percent], @"Percent",
992 [NSNumber numberWithDouble:CurrentBytes], @"Current",
993 [NSNumber numberWithDouble:TotalBytes], @"Total",
994 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
995 nil] waitUntilDone:YES];
997 return ![delegate_ isProgressCancelled];
1000 virtual void Start() {
1001 pkgAcquireStatus::Start();
1002 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1005 virtual void Stop() {
1006 pkgAcquireStatus::Stop();
1007 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1008 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1012 /* Database Interface {{{ */
1013 typedef std::map< unsigned long, _H<Source> > SourceMap;
1015 @interface Database : NSObject {
1021 pkgCacheFile cache_;
1022 pkgDepCache::Policy *policy_;
1023 pkgRecords *records_;
1024 pkgProblemResolver *resolver_;
1025 pkgAcquire *fetcher_;
1027 SPtr<pkgPackageManager> manager_;
1028 pkgSourceList *list_;
1030 SourceMap sourceMap_;
1031 _H<NSMutableArray> sourceList_;
1033 CFMutableArrayRef packages_;
1035 _transient NSObject<DatabaseDelegate> *delegate_;
1036 _transient NSObject<ProgressDelegate> *progress_;
1038 CydiaStatus status_;
1044 std::map<const char *, _H<NSString> > sections_;
1047 + (Database *) sharedInstance;
1050 - (void) _readCydia:(NSNumber *)fd;
1051 - (void) _readStatus:(NSNumber *)fd;
1052 - (void) _readOutput:(NSNumber *)fd;
1056 - (Package *) packageWithName:(NSString *)name;
1058 - (pkgCacheFile &) cache;
1059 - (pkgDepCache::Policy *) policy;
1060 - (pkgRecords *) records;
1061 - (pkgProblemResolver *) resolver;
1062 - (pkgAcquire &) fetcher;
1063 - (pkgSourceList &) list;
1064 - (NSArray *) packages;
1065 - (NSArray *) sources;
1066 - (Source *) sourceWithKey:(NSString *)key;
1067 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1075 - (void) updateWithStatus:(CancelStatus &)status;
1077 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1079 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1080 - (NSObject<ProgressDelegate> *) progressDelegate;
1082 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1083 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1084 - (void) resetFetch;
1086 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1090 /* SourceStatus {{{ */
1091 class SourceStatus :
1095 _transient NSObject<FetchDelegate> *delegate_;
1096 _transient Database *database_;
1099 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1100 delegate_(delegate),
1105 void Set(bool fetch, pkgAcquire::ItemDesc &desc) {
1107 [database_ setFetch:fetch forURI:desc.Owner->DescURI().c_str()];
1110 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1114 virtual void Done(pkgAcquire::ItemDesc &desc) {
1118 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1122 virtual bool Pulse_(pkgAcquire *Owner) {
1123 for (pkgAcquire::ItemCIterator item = Owner->ItemsBegin(); item != Owner->ItemsEnd(); ++item)
1124 if ((*item)->ID != 0);
1125 else if ((*item)->Status == pkgAcquire::Item::StatIdle) {
1127 [database_ setFetch:true forURI:(*item)->DescURI().c_str()];
1128 } else (*item)->ID = 0;
1129 return ![delegate_ isSourceCancelled];
1132 virtual void Stop() {
1133 pkgAcquireStatus::Stop();
1134 [database_ resetFetch];
1138 /* ProgressEvent Implementation {{{ */
1139 @implementation CydiaProgressEvent
1141 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1142 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1145 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1146 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1147 [event setPackage:package];
1151 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1152 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1154 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1155 NSArray *fields([description componentsSeparatedByString:@" "]);
1156 [event setItem:fields];
1158 if ([fields count] > 3) {
1159 [event setPackage:[fields objectAtIndex:2]];
1160 [event setVersion:[fields objectAtIndex:3]];
1163 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1168 + (NSArray *) _attributeKeys {
1169 return [NSArray arrayWithObjects:
1179 - (NSArray *) attributeKeys {
1180 return [[self class] _attributeKeys];
1183 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1184 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1187 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1188 if ((self = [super init]) != nil) {
1194 - (NSString *) message {
1198 - (NSString *) type {
1202 - (NSArray *) item {
1203 return (id) item_ ?: [NSNull null];
1206 - (void) setItem:(NSArray *)item {
1210 - (NSString *) package {
1211 return (id) package_ ?: [NSNull null];
1214 - (void) setPackage:(NSString *)package {
1218 - (NSString *) url {
1219 return (id) url_ ?: [NSNull null];
1222 - (void) setURL:(NSString *)url {
1226 - (void) setVersion:(NSString *)version {
1230 - (NSString *) version {
1231 return (id) version_ ?: [NSNull null];
1234 - (NSString *) compound:(NSString *)value {
1236 NSString *mode(nil); {
1237 NSString *type([self type]);
1238 if ([type isEqualToString:kCydiaProgressEventTypeError])
1239 mode = UCLocalize("ERROR");
1240 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1241 mode = UCLocalize("WARNING");
1245 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1251 - (NSString *) compoundMessage {
1252 return [self compound:[self message]];
1255 - (NSString *) compoundTitle {
1258 if (package_ == nil)
1260 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1261 title = [package name];
1265 return [self compound:title];
1271 // Cytore Definitions {{{
1272 struct PackageValue :
1275 Cytore::Offset<PackageValue> next_;
1277 uint32_t index_ : 23;
1278 uint32_t subscribed_ : 1;
1295 Cytore::Offset<PackageValue> packages_[1 << 16];
1298 static Cytore::File<MetaValue> MetaFile_;
1300 // Cytore Helper Functions {{{
1301 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1302 SplitHash nhash = { hashlittle(name, length) };
1304 PackageValue *metadata;
1306 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1307 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1308 *offset = MetaFile_.New<PackageValue>(length + 1);
1309 metadata = &MetaFile_.Get(*offset);
1311 if (metadata == NULL) {
1315 metadata = new PackageValue();
1316 memset(metadata, 0, sizeof(*metadata));
1319 memcpy(metadata->name_, name, length);
1320 metadata->name_[length] = '\0';
1321 metadata->nhash_ = nhash.u16[1];
1323 metadata = &MetaFile_.Get(*offset);
1324 if (metadata->nhash_ != nhash.u16[1])
1326 if (strncmp(metadata->name_, name, length) != 0)
1328 if (metadata->name_[length] != '\0')
1335 static void PackageImport(const void *key, const void *value, void *context) {
1336 bool &fail(*reinterpret_cast<bool *>(context));
1339 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1340 NSLog(@"failed to import package %@", key);
1344 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1345 NSDictionary *package((NSDictionary *) value);
1347 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1348 if ([subscribed boolValue] && !metadata->subscribed_)
1349 metadata->subscribed_ = true;
1351 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1352 time_t time([date timeIntervalSince1970]);
1353 if (metadata->first_ > time || metadata->first_ == 0)
1354 metadata->first_ = time;
1357 NSDate *date([package objectForKey:@"LastSeen"]);
1358 NSString *version([package objectForKey:@"LastVersion"]);
1360 if (date != nil && version != nil) {
1361 time_t time([date timeIntervalSince1970]);
1362 if (metadata->last_ < time || metadata->last_ == 0)
1363 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1364 size_t length(strlen(buffer));
1365 uint16_t vhash(hashlittle(buffer, length));
1367 size_t capped(std::min<size_t>(8, length));
1368 char *latest(buffer + length - capped);
1370 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1371 metadata->vhash_ = vhash;
1373 metadata->last_ = time;
1379 /* Source Class {{{ */
1380 @interface Source : NSObject {
1382 Database *database_;
1385 CYString depiction_;
1386 CYString description_;
1392 CYString distribution_;
1398 _H<NSString> authority_;
1400 CYString defaultIcon_;
1402 _H<NSMutableDictionary> record_;
1405 std::set<std::string> fetches_;
1406 std::set<std::string> files_;
1407 _transient NSObject<SourceDelegate> *delegate_;
1410 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1412 - (NSComparisonResult) compareByName:(Source *)source;
1414 - (NSString *) depictionForPackage:(NSString *)package;
1415 - (NSString *) supportForPackage:(NSString *)package;
1417 - (metaIndex *) metaIndex;
1418 - (NSDictionary *) record;
1421 - (NSString *) rooturi;
1422 - (NSString *) distribution;
1423 - (NSString *) type;
1426 - (NSString *) host;
1428 - (NSString *) name;
1429 - (NSString *) shortDescription;
1430 - (NSString *) label;
1431 - (NSString *) origin;
1432 - (NSString *) version;
1434 - (NSString *) defaultIcon;
1435 - (NSURL *) iconURL;
1437 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1438 - (void) resetFetch;
1442 @implementation Source
1444 + (NSString *) webScriptNameForSelector:(SEL)selector {
1446 else if (selector == @selector(addSection:))
1447 return @"addSection";
1448 else if (selector == @selector(getField:))
1450 else if (selector == @selector(removeSection:))
1451 return @"removeSection";
1452 else if (selector == @selector(remove))
1458 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1459 return [self webScriptNameForSelector:selector] == nil;
1462 + (NSArray *) _attributeKeys {
1463 return [NSArray arrayWithObjects:
1474 @"shortDescription",
1481 - (NSArray *) attributeKeys {
1482 return [[self class] _attributeKeys];
1485 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1486 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1489 - (metaIndex *) metaIndex {
1493 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1494 trusted_ = index->IsTrusted();
1496 uri_.set(pool, index->GetURI());
1497 distribution_.set(pool, index->GetDist());
1498 type_.set(pool, index->GetType());
1500 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1501 if (dindex != NULL) {
1502 std::string file(dindex->MetaIndexURI(""));
1503 base_.set(pool, file);
1506 dindex->GetIndexes(&acquire, true);
1507 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1508 std::string file((*item)->DescURI());
1509 files_.insert(file);
1510 if (file.length() < sizeof("Packages.bz2") || file.substr(file.length() - sizeof("Packages.bz2")) != "/Packages.bz2")
1512 file = file.substr(0, file.length() - 4);
1513 files_.insert(file);
1514 files_.insert(file + ".gz");
1515 files_.insert(file + "Index");
1519 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1522 pkgTagFile tags(&fd);
1524 pkgTagSection section;
1531 {"default-icon", &defaultIcon_},
1532 {"depiction", &depiction_},
1533 {"description", &description_},
1535 {"origin", &origin_},
1536 {"support", &support_},
1537 {"version", &version_},
1540 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1541 const char *start, *end;
1543 if (section.Find(names[i].name_, start, end)) {
1544 CYString &value(*names[i].value_);
1545 value.set(pool, start, end - start);
1551 record_ = [Sources_ objectForKey:[self key]];
1553 NSURL *url([NSURL URLWithString:uri_]);
1557 host_ = [host_ lowercaseString];
1562 authority_ = [url path];
1565 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1566 if ((self = [super init]) != nil) {
1567 era_ = [database era];
1568 database_ = database;
1571 [self setMetaIndex:index inPool:pool];
1575 - (NSString *) getField:(NSString *)name {
1576 @synchronized (database_) {
1577 if ([database_ era] != era_ || index_ == NULL)
1580 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1585 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1590 pkgTagFile tags(&fd);
1592 pkgTagSection section;
1595 const char *start, *end;
1596 if (!section.Find([name UTF8String], start, end))
1597 return (NSString *) [NSNull null];
1599 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1602 - (NSComparisonResult) compareByName:(Source *)source {
1603 NSString *lhs = [self name];
1604 NSString *rhs = [source name];
1606 if ([lhs length] != 0 && [rhs length] != 0) {
1607 unichar lhc = [lhs characterAtIndex:0];
1608 unichar rhc = [rhs characterAtIndex:0];
1610 if (isalpha(lhc) && !isalpha(rhc))
1611 return NSOrderedAscending;
1612 else if (!isalpha(lhc) && isalpha(rhc))
1613 return NSOrderedDescending;
1616 return [lhs compare:rhs options:LaxCompareOptions_];
1619 - (NSString *) depictionForPackage:(NSString *)package {
1620 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1623 - (NSString *) supportForPackage:(NSString *)package {
1624 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1627 - (NSArray *) sections {
1628 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1631 - (void) _addSection:(NSString *)section {
1634 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1635 if (![sections containsObject:section]) {
1636 [sections addObject:section];
1640 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1645 - (bool) addSection:(NSString *)section {
1649 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1653 - (void) _removeSection:(NSString *)section {
1657 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1658 if ([sections containsObject:section]) {
1659 [sections removeObject:section];
1664 - (bool) removeSection:(NSString *)section {
1668 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1673 [Sources_ removeObjectForKey:[self key]];
1678 bool value(record_ != nil);
1679 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1683 - (NSDictionary *) record {
1691 - (NSString *) rooturi {
1695 - (NSString *) distribution {
1696 return distribution_;
1699 - (NSString *) type {
1703 - (NSString *) baseuri {
1704 return base_.empty() ? nil : (id) base_;
1707 - (NSString *) iconuri {
1708 if (NSString *base = [self baseuri])
1709 return [base stringByAppendingString:@"CydiaIcon.png"];
1714 - (NSURL *) iconURL {
1715 if (NSString *uri = [self iconuri])
1716 return [NSURL URLWithString:uri];
1720 - (NSString *) key {
1721 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1724 - (NSString *) host {
1728 - (NSString *) name {
1729 return origin_.empty() ? (id) authority_ : origin_;
1732 - (NSString *) shortDescription {
1733 return description_;
1736 - (NSString *) label {
1737 return label_.empty() ? (id) authority_ : label_;
1740 - (NSString *) origin {
1744 - (NSString *) version {
1748 - (NSString *) defaultIcon {
1749 return defaultIcon_;
1752 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1753 delegate_ = delegate;
1757 return !fetches_.empty();
1760 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1762 if (fetches_.erase(uri) == 0)
1764 } else if (files_.find(uri) == files_.end())
1766 else if (!fetches_.insert(uri).second)
1769 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1772 - (void) resetFetch {
1774 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1779 /* CydiaOperation Class {{{ */
1780 @interface CydiaOperation : NSObject {
1781 _H<NSString> operator_;
1782 _H<NSString> value_;
1785 - (NSString *) operator;
1786 - (NSString *) value;
1790 @implementation CydiaOperation
1792 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1793 if ((self = [super init]) != nil) {
1794 operator_ = [NSString stringWithUTF8String:_operator];
1795 value_ = [NSString stringWithUTF8String:value];
1799 + (NSArray *) _attributeKeys {
1800 return [NSArray arrayWithObjects:
1806 - (NSArray *) attributeKeys {
1807 return [[self class] _attributeKeys];
1810 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1811 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1814 - (NSString *) operator {
1818 - (NSString *) value {
1824 /* CydiaClause Class {{{ */
1825 @interface CydiaClause : NSObject {
1826 _H<NSString> package_;
1827 _H<CydiaOperation> version_;
1830 - (NSString *) package;
1831 - (CydiaOperation *) version;
1835 @implementation CydiaClause
1837 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1838 if ((self = [super init]) != nil) {
1839 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1841 if (const char *version = dep.TargetVer())
1842 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1844 version_ = (id) [NSNull null];
1848 + (NSArray *) _attributeKeys {
1849 return [NSArray arrayWithObjects:
1855 - (NSArray *) attributeKeys {
1856 return [[self class] _attributeKeys];
1859 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1860 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1863 - (NSString *) package {
1867 - (CydiaOperation *) version {
1873 /* CydiaRelation Class {{{ */
1874 @interface CydiaRelation : NSObject {
1875 _H<NSString> relationship_;
1876 _H<NSMutableArray> clauses_;
1879 - (NSString *) relationship;
1880 - (NSArray *) clauses;
1884 @implementation CydiaRelation
1886 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1887 if ((self = [super init]) != nil) {
1888 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1889 clauses_ = [NSMutableArray arrayWithCapacity:8];
1891 pkgCache::DepIterator start;
1892 pkgCache::DepIterator end;
1893 dep.GlobOr(start, end); // ++dep
1896 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1898 // yes, seriously. (wtf?)
1906 + (NSArray *) _attributeKeys {
1907 return [NSArray arrayWithObjects:
1913 - (NSArray *) attributeKeys {
1914 return [[self class] _attributeKeys];
1917 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1918 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1921 - (NSString *) relationship {
1922 return relationship_;
1925 - (NSArray *) clauses {
1929 - (void) addClause:(CydiaClause *)clause {
1930 [clauses_ addObject:clause];
1935 /* Package Class {{{ */
1936 struct ParsedPackage {
1940 CYString architecture_;
1943 CYString depiction_;
1950 @interface Package : NSObject {
1952 @public uint32_t role_ : 3;
1953 uint32_t essential_ : 1;
1954 uint32_t obsolete_ : 1;
1955 uint32_t ignored_ : 1;
1956 uint32_t pooled_ : 1;
1962 _transient Database *database_;
1964 pkgCache::VerIterator version_;
1965 pkgCache::PkgIterator iterator_;
1966 pkgCache::VerFileIterator file_;
1972 CYString installed_;
1975 const char *section_;
1976 _transient NSString *section$_;
1980 PackageValue *metadata_;
1981 ParsedPackage *parsed_;
1983 _H<NSMutableArray> tags_;
1986 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1987 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1989 - (pkgCache::PkgIterator) iterator;
1992 - (NSString *) section;
1993 - (NSString *) simpleSection;
1995 - (NSString *) longSection;
1996 - (NSString *) shortSection;
2000 - (MIMEAddress *) maintainer;
2002 - (NSString *) longDescription;
2003 - (NSString *) shortDescription;
2006 - (PackageValue *) metadata;
2009 - (bool) subscribed;
2010 - (bool) setSubscribed:(bool)subscribed;
2014 - (NSString *) latest;
2015 - (NSString *) installed;
2016 - (BOOL) uninstalled;
2019 - (BOOL) upgradableAndEssential:(BOOL)essential;
2022 - (BOOL) unfiltered;
2026 - (BOOL) halfConfigured;
2027 - (BOOL) halfInstalled;
2029 - (NSString *) mode;
2032 - (NSString *) name;
2034 - (NSString *) homepage;
2035 - (NSString *) depiction;
2036 - (MIMEAddress *) author;
2038 - (NSString *) support;
2040 - (NSArray *) files;
2041 - (NSArray *) warnings;
2042 - (NSArray *) applications;
2044 - (Source *) source;
2047 - (BOOL) matches:(NSArray *)query;
2049 - (BOOL) hasTag:(NSString *)tag;
2050 - (NSString *) primaryPurpose;
2051 - (NSArray *) purposes;
2052 - (bool) isCommercial;
2054 - (void) setIndex:(size_t)index;
2056 - (CYString &) cyname;
2058 - (uint32_t) compareBySection:(NSArray *)sections;
2065 uint32_t PackageChangesRadix(Package *self, void *) {
2070 uint32_t timestamp : 30;
2071 uint32_t ignored : 1;
2072 uint32_t upgradable : 1;
2076 bool upgradable([self upgradableAndEssential:YES]);
2077 value.bits.upgradable = upgradable ? 1 : 0;
2080 value.bits.timestamp = 0;
2081 value.bits.ignored = [self ignored] ? 0 : 1;
2082 value.bits.upgradable = 1;
2084 value.bits.timestamp = [self seen] >> 2;
2085 value.bits.ignored = 0;
2086 value.bits.upgradable = 0;
2089 return _not(uint32_t) - value.key;
2092 uint32_t PackagePrefixRadix(Package *self, void *context) {
2093 size_t offset(reinterpret_cast<size_t>(context));
2094 CYString &name([self cyname]);
2096 size_t size(name.size());
2099 char *text(name.data());
2102 if (!isdigit(text[0]))
2106 while (size != digits && isdigit(text[digits]))
2114 if (offset == 0 && zeros != 0) {
2115 memset(data, '0', zeros);
2116 memcpy(data + zeros, text, 4 - zeros);
2118 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2119 if (size <= offset - zeros)
2122 text += offset - zeros;
2123 size -= offset - zeros;
2126 memcpy(data, text, 4);
2128 memcpy(data, text, size);
2129 memset(data + size, 0, 4 - size);
2132 for (size_t i(0); i != 4; ++i)
2133 if (isalpha(data[i]))
2141 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2143 /* XXX: ntohl may be more honest */
2144 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2147 CYString &(*PackageName)(Package *self, SEL sel);
2149 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2150 _profile(PackageNameCompare)
2151 CYString &lhi(PackageName(lhs, @selector(cyname)));
2152 CYString &rhi(PackageName(rhs, @selector(cyname)));
2153 CFStringRef lhn(lhi), rhn(rhi);
2156 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2157 else if (rhn == NULL)
2158 return kCFCompareGreaterThan;
2160 _profile(PackageNameCompare$NumbersLast)
2161 if (!lhi.empty() && !rhi.empty()) {
2162 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2163 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2164 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2165 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2166 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2170 CFIndex length = CFStringGetLength(lhn);
2172 _profile(PackageNameCompare$Compare)
2173 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2178 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2179 return PackageNameCompare(*lhs, *rhs, context);
2182 struct PackageNameOrdering :
2183 std::binary_function<Package *, Package *, bool>
2185 _finline bool operator ()(Package *lhs, Package *rhs) const {
2186 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2190 @implementation Package
2192 - (NSString *) description {
2193 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2198 apr_pool_destroy(pool_);
2199 if (parsed_ != NULL)
2204 + (NSString *) webScriptNameForSelector:(SEL)selector {
2206 else if (selector == @selector(clear))
2208 else if (selector == @selector(getField:))
2210 else if (selector == @selector(getRecord))
2211 return @"getRecord";
2212 else if (selector == @selector(hasTag:))
2214 else if (selector == @selector(install))
2216 else if (selector == @selector(remove))
2222 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2223 return [self webScriptNameForSelector:selector] == nil;
2226 + (NSArray *) _attributeKeys {
2227 return [NSArray arrayWithObjects:
2248 @"shortDescription",
2260 - (NSArray *) attributeKeys {
2261 return [[self class] _attributeKeys];
2264 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2265 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2268 - (NSArray *) relations {
2269 @synchronized (database_) {
2270 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2271 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2272 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2276 - (NSString *) architecture {
2278 @synchronized (database_) {
2279 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2282 - (NSString *) getField:(NSString *)name {
2283 @synchronized (database_) {
2284 if ([database_ era] != era_ || file_.end())
2287 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2289 const char *start, *end;
2290 if (!parser.Find([name UTF8String], start, end))
2291 return (NSString *) [NSNull null];
2293 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2296 - (NSString *) getRecord {
2297 @synchronized (database_) {
2298 if ([database_ era] != era_ || file_.end())
2301 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2303 const char *start, *end;
2304 parser.GetRec(start, end);
2306 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2310 if (parsed_ != NULL)
2312 @synchronized (database_) {
2313 if ([database_ era] != era_ || file_.end())
2316 ParsedPackage *parsed(new ParsedPackage);
2319 _profile(Package$parse)
2320 pkgRecords::Parser *parser;
2322 _profile(Package$parse$Lookup)
2323 parser = &[database_ records]->Lookup(file_);
2329 _profile(Package$parse$Find)
2334 {"architecture", &parsed->architecture_},
2335 {"icon", &parsed->icon_},
2336 {"depiction", &parsed->depiction_},
2337 {"homepage", &parsed->homepage_},
2338 {"website", &website},
2340 {"support", &parsed->support_},
2341 {"author", &parsed->author_},
2342 {"md5sum", &parsed->md5sum_},
2345 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2346 const char *start, *end;
2348 if (parser->Find(names[i].name_, start, end)) {
2349 CYString &value(*names[i].value_);
2350 _profile(Package$parse$Value)
2351 value.set(pool_, start, end - start);
2357 _profile(Package$parse$Tagline)
2358 const char *start, *end;
2359 if (parser->ShortDesc(start, end)) {
2360 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2363 while (stop != start && stop[-1] == '\r')
2365 parsed->tagline_.set(pool_, start, stop - start);
2369 _profile(Package$parse$Retain)
2370 if (parsed->homepage_.empty())
2371 parsed->homepage_ = website;
2372 if (parsed->homepage_ == parsed->depiction_)
2373 parsed->homepage_.clear();
2374 if (parsed->support_.empty())
2375 parsed->support_ = bugs;
2380 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2381 if ((self = [super init]) != nil) {
2382 _profile(Package$initWithVersion)
2384 apr_pool_create(&pool_, NULL);
2390 database_ = database;
2391 era_ = [database era];
2395 pkgCache::PkgIterator iterator(version.ParentPkg());
2396 iterator_ = iterator;
2398 _profile(Package$initWithVersion$Version)
2399 if (!version_.end())
2400 file_ = version_.FileList();
2402 pkgCache &cache([database_ cache]);
2403 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2407 _profile(Package$initWithVersion$Cache)
2408 name_.set(NULL, iterator.Display());
2410 latest_.set(NULL, StripVersion_(version_.VerStr()));
2412 pkgCache::VerIterator current(iterator.CurrentVer());
2414 installed_.set(NULL, StripVersion_(current.VerStr()));
2417 _profile(Package$initWithVersion$Tags)
2418 pkgCache::TagIterator tag(iterator.TagList());
2420 tags_ = [NSMutableArray arrayWithCapacity:8];
2422 goto tag; for (; !tag.end(); ++tag) tag: {
2423 const char *name(tag.Name());
2424 NSString *string((NSString *) CYStringCreate(name));
2428 [tags_ addObject:[string autorelease]];
2430 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2431 if (strcmp(name + 6, "enduser") == 0)
2433 else if (strcmp(name + 6, "hacker") == 0)
2435 else if (strcmp(name + 6, "developer") == 0)
2437 else if (strcmp(name + 6, "cydia") == 0)
2443 if (strncmp(name, "cydia::", 7) == 0) {
2444 if (strcmp(name + 7, "essential") == 0)
2446 else if (strcmp(name + 7, "obsolete") == 0)
2453 _profile(Package$initWithVersion$Metadata)
2454 const char *mixed(iterator.Name());
2455 size_t size(strlen(mixed));
2456 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2457 char lower[prefix + size + 5 + 1];
2459 for (size_t i(0); i != size; ++i)
2460 lower[prefix + i] = mixed[i] | 0x20;
2462 if (!installed_.empty()) {
2463 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2464 memcpy(lower + prefix + size, ".list", 6);
2466 if (stat(lower, &info) != -1)
2467 updated_ = info.st_birthtime;
2470 PackageValue *metadata(PackageFind(lower + prefix, size));
2471 metadata_ = metadata;
2473 id_.set(NULL, metadata->name_, size);
2475 const char *latest(version_.VerStr());
2476 size_t length(strlen(latest));
2478 uint16_t vhash(hashlittle(latest, length));
2480 size_t capped(std::min<size_t>(8, length));
2481 latest = latest + length - capped;
2483 if (metadata->first_ == 0)
2484 metadata->first_ = now_;
2486 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2487 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2488 metadata->vhash_ = vhash;
2489 metadata->last_ = now_;
2490 } else if (metadata->last_ == 0)
2491 metadata->last_ = metadata->first_;
2494 _profile(Package$initWithVersion$Section)
2495 section_ = version_.Section();
2498 _profile(Package$initWithVersion$Flags)
2499 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2500 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2505 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2506 pkgCache::VerIterator version;
2508 _profile(Package$packageWithIterator$GetCandidateVer)
2509 version = [database policy]->GetCandidateVer(iterator);
2517 _profile(Package$packageWithIterator$Allocate)
2518 package = [Package allocWithZone:zone];
2521 _profile(Package$packageWithIterator$Initialize)
2523 initWithVersion:version
2530 _profile(Package$packageWithIterator$Autorelease)
2531 package = [package autorelease];
2537 - (pkgCache::PkgIterator) iterator {
2541 - (NSString *) section {
2542 if (section$_ == nil) {
2543 if (section_ == NULL)
2546 _profile(Package$section$mappedSectionForPointer)
2547 section$_ = [database_ mappedSectionForPointer:section_];
2552 - (NSString *) simpleSection {
2553 if (NSString *section = [self section])
2554 return Simplify(section);
2559 - (NSString *) longSection {
2560 return LocalizeSection([self section]);
2563 - (NSString *) shortSection {
2564 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2567 - (NSString *) uri {
2570 pkgIndexFile *index;
2571 pkgCache::PkgFileIterator file(file_.File());
2572 if (![database_ list].FindIndex(file, index))
2574 return [NSString stringWithUTF8String:iterator_->Path];
2575 //return [NSString stringWithUTF8String:file.Site()];
2576 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2580 - (MIMEAddress *) maintainer {
2581 @synchronized (database_) {
2582 if ([database_ era] != era_ || file_.end())
2585 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2586 const std::string &maintainer(parser->Maintainer());
2587 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2590 - (NSString *) md5sum {
2591 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2595 @synchronized (database_) {
2596 if ([database_ era] != era_ || version_.end())
2599 return version_->InstalledSize;
2602 - (NSString *) longDescription {
2603 @synchronized (database_) {
2604 if ([database_ era] != era_ || file_.end())
2607 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2608 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2610 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2611 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2612 if ([lines count] < 2)
2615 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2616 for (size_t i(1), e([lines count]); i != e; ++i) {
2617 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2618 [trimmed addObject:trim];
2621 return [trimmed componentsJoinedByString:@"\n"];
2624 - (NSString *) shortDescription {
2625 if (parsed_ != NULL)
2626 return static_cast<NSString *>(parsed_->tagline_);
2628 @synchronized (database_) {
2629 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2631 const char *start, *end;
2632 if (!parser.ShortDesc(start, end))
2635 if (end - start > 200)
2639 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2642 while (end != start && end[-1] == '\r')
2646 return [(id) CYStringCreate(start, end - start) autorelease];
2650 _profile(Package$index)
2651 CFStringRef name((CFStringRef) [self name]);
2652 if (CFStringGetLength(name) == 0)
2654 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2655 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2657 return toupper(character);
2661 - (PackageValue *) metadata {
2666 PackageValue *metadata([self metadata]);
2667 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2670 - (bool) subscribed {
2671 return [self metadata]->subscribed_;
2674 - (bool) setSubscribed:(bool)subscribed {
2675 PackageValue *metadata([self metadata]);
2676 if (metadata->subscribed_ == subscribed)
2678 metadata->subscribed_ = subscribed;
2686 - (NSString *) latest {
2690 - (NSString *) installed {
2694 - (BOOL) uninstalled {
2695 return installed_.empty();
2699 return !version_.end();
2702 - (BOOL) upgradableAndEssential:(BOOL)essential {
2703 _profile(Package$upgradableAndEssential)
2704 pkgCache::VerIterator current(iterator_.CurrentVer());
2706 return essential && essential_;
2708 return !version_.end() && version_ != current;
2712 - (BOOL) essential {
2717 return [database_ cache][iterator_].InstBroken();
2720 - (BOOL) unfiltered {
2721 _profile(Package$unfiltered$obsolete)
2722 if (_unlikely(obsolete_))
2726 _profile(Package$unfiltered$role)
2727 if (_unlikely(role_ > 3))
2735 if (![self unfiltered])
2740 _profile(Package$visible$section)
2741 section = [self section];
2744 _profile(Package$visible$isSectionVisible)
2745 if (!isSectionVisible(section))
2753 unsigned char current(iterator_->CurrentState);
2754 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2757 - (BOOL) halfConfigured {
2758 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2761 - (BOOL) halfInstalled {
2762 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2766 @synchronized (database_) {
2767 if ([database_ era] != era_ || iterator_.end())
2770 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2771 return state.Mode != pkgDepCache::ModeKeep;
2774 - (NSString *) mode {
2775 @synchronized (database_) {
2776 if ([database_ era] != era_ || iterator_.end())
2779 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2781 switch (state.Mode) {
2782 case pkgDepCache::ModeDelete:
2783 if ((state.iFlags & pkgDepCache::Purge) != 0)
2787 case pkgDepCache::ModeKeep:
2788 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2789 return @"REINSTALL";
2790 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2794 case pkgDepCache::ModeInstall:
2795 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2796 return @"REINSTALL";
2797 else*/ switch (state.Status) {
2799 return @"DOWNGRADE";
2805 return @"NEW_INSTALL";
2816 - (NSString *) name {
2817 return name_.empty() ? id_ : name_;
2820 - (UIImage *) icon {
2821 NSString *section = [self simpleSection];
2824 if (parsed_ != NULL)
2825 if (NSString *href = parsed_->icon_)
2826 if ([href hasPrefix:@"file:///"])
2827 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2828 if (icon == nil) if (section != nil)
2829 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2830 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2831 if ([dicon hasPrefix:@"file:///"])
2832 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2834 icon = [UIImage applicationImageNamed:@"unknown.png"];
2838 - (NSString *) homepage {
2839 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2842 - (NSString *) depiction {
2843 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2846 - (MIMEAddress *) author {
2847 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2850 - (NSString *) support {
2851 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
2854 - (NSArray *) files {
2855 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2856 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2859 fin.open([path UTF8String]);
2864 while (std::getline(fin, line))
2865 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2870 - (NSString *) state {
2871 @synchronized (database_) {
2872 if ([database_ era] != era_ || file_.end())
2875 switch (iterator_->CurrentState) {
2876 case pkgCache::State::NotInstalled:
2877 return @"NotInstalled";
2878 case pkgCache::State::UnPacked:
2880 case pkgCache::State::HalfConfigured:
2881 return @"HalfConfigured";
2882 case pkgCache::State::HalfInstalled:
2883 return @"HalfInstalled";
2884 case pkgCache::State::ConfigFiles:
2885 return @"ConfigFiles";
2886 case pkgCache::State::Installed:
2887 return @"Installed";
2888 case pkgCache::State::TriggersAwaited:
2889 return @"TriggersAwaited";
2890 case pkgCache::State::TriggersPending:
2891 return @"TriggersPending";
2894 return (NSString *) [NSNull null];
2897 - (NSString *) selection {
2898 @synchronized (database_) {
2899 if ([database_ era] != era_ || file_.end())
2902 switch (iterator_->SelectedState) {
2903 case pkgCache::State::Unknown:
2905 case pkgCache::State::Install:
2907 case pkgCache::State::Hold:
2909 case pkgCache::State::DeInstall:
2910 return @"DeInstall";
2911 case pkgCache::State::Purge:
2915 return (NSString *) [NSNull null];
2918 - (NSArray *) warnings {
2919 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2920 const char *name(iterator_.Name());
2922 size_t length(strlen(name));
2923 if (length < 2) invalid:
2924 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2925 else for (size_t i(0); i != length; ++i)
2927 /* XXX: technically this is not allowed */
2928 (name[i] < 'A' || name[i] > 'Z') &&
2929 (name[i] < 'a' || name[i] > 'z') &&
2930 (name[i] < '0' || name[i] > '9') &&
2931 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2934 if (strcmp(name, "cydia") != 0) {
2937 bool _private = false;
2940 bool repository = [[self section] isEqualToString:@"Repositories"];
2942 if (NSArray *files = [self files])
2943 for (NSString *file in files)
2944 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2946 else if (!user && [file isEqualToString:@"/User"])
2948 else if (!_private && [file isEqualToString:@"/private"])
2950 else if (!stash && [file isEqualToString:@"/var/stash"])
2953 /* XXX: this is not sensitive enough. only some folders are valid. */
2954 if (cydia && !repository)
2955 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2957 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2959 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2961 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2964 return [warnings count] == 0 ? nil : warnings;
2967 - (NSArray *) applications {
2968 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2970 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2972 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2973 if (NSArray *files = [self files])
2974 for (NSString *file in files)
2975 if (application_r(file)) {
2976 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2977 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2978 if ([id isEqualToString:me])
2981 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2983 display = application_r[1];
2985 NSString *bundle([file stringByDeletingLastPathComponent]);
2986 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2987 // XXX: maybe this should check if this is really a string, not just for length
2988 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
2990 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2992 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2993 [applications addObject:application];
2995 [application addObject:id];
2996 [application addObject:display];
2997 [application addObject:url];
3000 return [applications count] == 0 ? nil : applications;
3003 - (Source *) source {
3004 if (source_ == nil) {
3005 @synchronized (database_) {
3006 if ([database_ era] != era_ || file_.end())
3007 source_ = (Source *) [NSNull null];
3009 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3013 return source_ == (Source *) [NSNull null] ? nil : source_;
3016 - (uint32_t) updated {
3017 return std::numeric_limits<uint32_t>::max() - updated_;
3024 - (BOOL) matches:(NSArray *)query {
3025 if (query == nil || [query count] == 0)
3034 string = [self name];
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;
3045 length = [string length];
3047 for (NSString *term in query) {
3048 range = [string rangeOfString:term options:MatchCompareOptions_];
3049 if (range.location != NSNotFound)
3050 rank_ -= 6 * 1000000 / length;
3054 string = [self shortDescription];
3055 length = [string length];
3056 NSUInteger stop(std::min<NSUInteger>(length, 200));
3058 for (NSString *term in query) {
3059 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3060 if (range.location != NSNotFound)
3061 rank_ -= 2 * 100000;
3067 - (NSArray *) tags {
3071 - (BOOL) hasTag:(NSString *)tag {
3072 return tags_ == nil ? NO : [tags_ containsObject:tag];
3075 - (NSString *) primaryPurpose {
3076 for (NSString *tag in (NSArray *) tags_)
3077 if ([tag hasPrefix:@"purpose::"])
3078 return [tag substringFromIndex:9];
3082 - (NSArray *) purposes {
3083 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3084 for (NSString *tag in (NSArray *) tags_)
3085 if ([tag hasPrefix:@"purpose::"])
3086 [purposes addObject:[tag substringFromIndex:9]];
3087 return [purposes count] == 0 ? nil : purposes;
3090 - (bool) isCommercial {
3091 return [self hasTag:@"cydia::commercial"];
3094 - (void) setIndex:(size_t)index {
3095 if (metadata_->index_ != index)
3096 metadata_->index_ = index;
3099 - (CYString &) cyname {
3100 return name_.empty() ? id_ : name_;
3103 - (uint32_t) compareBySection:(NSArray *)sections {
3104 NSString *section([self section]);
3105 for (size_t i(0), e([sections count]); i != e; ++i) {
3106 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3110 return _not(uint32_t);
3114 @synchronized (database_) {
3115 pkgProblemResolver *resolver = [database_ resolver];
3116 resolver->Clear(iterator_);
3118 pkgCacheFile &cache([database_ cache]);
3119 cache->SetReInstall(iterator_, false);
3120 cache->MarkKeep(iterator_, false);
3124 @synchronized (database_) {
3125 pkgProblemResolver *resolver = [database_ resolver];
3126 resolver->Clear(iterator_);
3127 resolver->Protect(iterator_);
3129 pkgCacheFile &cache([database_ cache]);
3130 cache->SetReInstall(iterator_, false);
3131 cache->MarkInstall(iterator_, false);
3133 pkgDepCache::StateCache &state((*cache)[iterator_]);
3134 if (!state.Install())
3135 cache->SetReInstall(iterator_, true);
3139 @synchronized (database_) {
3140 pkgProblemResolver *resolver = [database_ resolver];
3141 resolver->Clear(iterator_);
3142 resolver->Remove(iterator_);
3143 resolver->Protect(iterator_);
3145 pkgCacheFile &cache([database_ cache]);
3146 cache->SetReInstall(iterator_, false);
3147 cache->MarkDelete(iterator_, true);
3152 /* Section Class {{{ */
3153 @interface Section : NSObject {
3158 _H<NSString> localized_;
3161 - (NSComparisonResult) compareByLocalized:(Section *)section;
3162 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3163 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3164 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3165 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3166 - (NSString *) name;
3173 - (void) addToCount;
3175 - (void) setCount:(size_t)count;
3176 - (NSString *) localized;
3180 @implementation Section
3182 - (NSComparisonResult) compareByLocalized:(Section *)section {
3183 NSString *lhs(localized_);
3184 NSString *rhs([section localized]);
3186 /*if ([lhs length] != 0 && [rhs length] != 0) {
3187 unichar lhc = [lhs characterAtIndex:0];
3188 unichar rhc = [rhs characterAtIndex:0];
3190 if (isalpha(lhc) && !isalpha(rhc))
3191 return NSOrderedAscending;
3192 else if (!isalpha(lhc) && isalpha(rhc))
3193 return NSOrderedDescending;
3196 return [lhs compare:rhs options:LaxCompareOptions_];
3199 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3200 if ((self = [self initWithName:name localize:NO]) != nil) {
3201 if (localized != nil)
3202 localized_ = localized;
3206 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3207 return [self initWithName:name row:0 localize:localize];
3210 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3211 if ((self = [super init]) != nil) {
3216 localized_ = LocalizeSection(name_);
3220 /* XXX: localize the index thingees */
3221 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3222 if ((self = [super init]) != nil) {
3223 name_ = [NSString stringWithCharacters:&index length:1];
3229 - (NSString *) name {
3249 - (void) addToCount {
3253 - (void) setCount:(size_t)count {
3257 - (NSString *) localized {
3264 class CydiaLogCleaner :
3265 public pkgArchiveCleaner
3268 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3273 /* Database Implementation {{{ */
3274 @implementation Database
3276 + (Database *) sharedInstance {
3277 static _H<Database> instance;
3278 if (instance == nil)
3279 instance = [[[Database alloc] init] autorelease];
3287 - (void) releasePackages {
3288 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3289 CFArrayRemoveAllValues(packages_);
3293 // XXX: actually implement this thing
3295 [self releasePackages];
3296 apr_pool_destroy(pool_);
3297 NSRecycleZone(zone_);
3301 - (void) _readCydia:(NSNumber *)fd {
3302 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3303 std::istream is(&ib);
3306 static Pcre finish_r("^finish:([^:]*)$");
3308 while (std::getline(is, line)) {
3309 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3311 const char *data(line.c_str());
3312 size_t size = line.size();
3313 lprintf("C:%s\n", data);
3315 if (finish_r(data, size)) {
3316 NSString *finish = finish_r[1];
3317 int index = [Finishes_ indexOfObject:finish];
3318 if (index != INT_MAX && index > Finish_)
3328 - (void) _readStatus:(NSNumber *)fd {
3329 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3330 std::istream is(&ib);
3333 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3334 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3336 while (std::getline(is, line)) {
3337 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3339 const char *data(line.c_str());
3340 size_t size(line.size());
3341 lprintf("S:%s\n", data);
3343 if (conffile_r(data, size)) {
3344 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3345 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3346 } else if (strncmp(data, "status: ", 8) == 0) {
3347 // status: <package>: {unpacked,half-configured,installed}
3348 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3349 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3350 } else if (strncmp(data, "processing: ", 12) == 0) {
3351 // processing: configure: config-test
3352 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3353 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3354 } else if (pmstatus_r(data, size)) {
3355 std::string type([pmstatus_r[1] UTF8String]);
3357 NSString *package = pmstatus_r[2];
3358 if ([package isEqualToString:@"dpkg-exec"])
3361 float percent([pmstatus_r[3] floatValue]);
3362 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3364 NSString *string = pmstatus_r[4];
3366 if (type == "pmerror") {
3367 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3368 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3369 } else if (type == "pmstatus") {
3370 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3371 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3372 } else if (type == "pmconffile")
3373 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3375 lprintf("E:unknown pmstatus\n");
3377 lprintf("E:unknown status\n");
3385 - (void) _readOutput:(NSNumber *)fd {
3386 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3387 std::istream is(&ib);
3390 while (std::getline(is, line)) {
3391 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3393 lprintf("O:%s\n", line.c_str());
3395 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3396 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3408 - (Package *) packageWithName:(NSString *)name {
3411 @synchronized (self) {
3412 if (static_cast<pkgDepCache *>(cache_) == NULL)
3414 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3415 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3419 if ((self = [super init]) != nil) {
3426 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3427 apr_pool_create(&pool_, NULL);
3429 size_t capacity(MetaFile_->active_);
3435 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3436 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3440 _assert(pipe(fds) != -1);
3443 _config->Set("APT::Keep-Fds::", cydiafd_);
3444 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3447 detachNewThreadSelector:@selector(_readCydia:)
3449 withObject:[NSNumber numberWithInt:fds[0]]
3452 _assert(pipe(fds) != -1);
3456 detachNewThreadSelector:@selector(_readStatus:)
3458 withObject:[NSNumber numberWithInt:fds[0]]
3461 _assert(pipe(fds) != -1);
3462 _assert(dup2(fds[0], 0) != -1);
3463 _assert(close(fds[0]) != -1);
3465 input_ = fdopen(fds[1], "a");
3467 _assert(pipe(fds) != -1);
3468 _assert(dup2(fds[1], 1) != -1);
3469 _assert(close(fds[1]) != -1);
3472 detachNewThreadSelector:@selector(_readOutput:)
3474 withObject:[NSNumber numberWithInt:fds[0]]
3479 - (pkgCacheFile &) cache {
3483 - (pkgDepCache::Policy *) policy {
3487 - (pkgRecords *) records {
3491 - (pkgProblemResolver *) resolver {
3495 - (pkgAcquire &) fetcher {
3499 - (pkgSourceList &) list {
3503 - (NSArray *) packages {
3504 return (NSArray *) packages_;
3507 - (NSArray *) sources {
3511 - (Source *) sourceWithKey:(NSString *)key {
3512 for (Source *source in [self sources]) {
3513 if ([[source key] isEqualToString:key])
3518 - (bool) popErrorWithTitle:(NSString *)title {
3521 while (!_error->empty()) {
3523 bool warning(!_error->PopMessage(error));
3528 size_t size(error.size());
3529 if (size == 0 || error[size - 1] != '\n')
3531 error.resize(size - 1);
3534 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3536 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3537 if (warning && no_pubkey(error.c_str()))
3540 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3546 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3547 return [self popErrorWithTitle:title] || !success;
3550 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3551 @synchronized (self) {
3554 [self releasePackages];
3557 [sourceList_ removeAllObjects];
3577 apr_pool_clear(pool_);
3579 NSRecycleZone(zone_);
3580 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3582 int chk(creat("/tmp/cydia.chk", 0644));
3586 if (invocation != nil)
3587 [invocation invoke];
3589 NSString *title(UCLocalize("DATABASE"));
3591 list_ = new pkgSourceList();
3592 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3595 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3596 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3597 [sourceList_ addObject:object];
3601 OpProgress progress;
3603 if (!cache_.Open(progress, true)) {
3604 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3605 while (!_error->empty()) {
3607 bool warning(!_error->PopMessage(error));
3609 lprintf("cache_.Open():[%s]\n", error.c_str());
3611 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3615 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3616 repair = @selector(configure);
3617 //else if (error == "The package lists or status file could not be parsed or opened.")
3618 // repair = @selector(update);
3619 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3620 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3621 // else if (error == "Malformed Status line")
3622 // else if (error == "The list of sources could not be read.")
3624 if (repair != NULL) {
3626 [delegate_ repairWithSelector:repair];
3635 unlink("/tmp/cydia.chk");
3637 now_ = [[NSDate date] timeIntervalSince1970];
3639 policy_ = new pkgDepCache::Policy();
3640 records_ = new pkgRecords(cache_);
3641 resolver_ = new pkgProblemResolver(cache_);
3642 fetcher_ = new pkgAcquire(&status_);
3645 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3646 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3650 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3653 if (cache_->BrokenCount() != 0) {
3654 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3657 if (cache_->BrokenCount() != 0) {
3658 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3662 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3666 for (Source *object in (id) sourceList_) {
3667 metaIndex *source([object metaIndex]);
3668 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3669 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3670 // XXX: this could be more intelligent
3671 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3672 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3674 sourceMap_[cached->ID] = object;
3679 /*std::vector<Package *> packages;
3680 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3685 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3686 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3687 //packages.push_back(package);
3688 CFArrayAppendValue(packages_, CFRetain(package));
3692 /*if (packages.empty())
3693 packages_ = [[NSArray alloc] init];
3695 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3698 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3699 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3700 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3708 /*if (!packages.empty())
3709 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3710 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3712 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3714 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3716 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3720 size_t count(CFArrayGetCount(packages_));
3721 MetaFile_->active_ = count;
3723 for (size_t index(0); index != count; ++index)
3724 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3731 @synchronized (self) {
3733 resolver_ = new pkgProblemResolver(cache_);
3735 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3736 if (!cache_[iterator].Keep())
3737 cache_->MarkKeep(iterator, false);
3738 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3739 cache_->SetReInstall(iterator, false);
3742 - (void) configure {
3743 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3745 system([dpkg UTF8String]);
3750 @synchronized (self) {
3751 // XXX: I don't remember this condition
3756 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3758 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3760 if ([self popErrorWithTitle:title])
3764 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3766 CydiaLogCleaner cleaner;
3767 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3774 fetcher_->Shutdown();
3776 pkgRecords records(cache_);
3778 lock_ = new FileFd();
3779 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3781 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3783 if ([self popErrorWithTitle:title])
3787 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3790 manager_ = (_system->CreatePM(cache_));
3791 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3798 bool substrate(RestartSubstrate_);
3799 RestartSubstrate_ = false;
3801 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3803 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3805 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3807 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3808 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3811 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3813 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3815 [self popErrorWithTitle:title];
3819 bool failed = false;
3820 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3821 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3823 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3826 std::string uri = (*item)->DescURI();
3827 std::string error = (*item)->ErrorText;
3829 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3832 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3833 [delegate_ addProgressEventOnMainThread:event forTask:title];
3836 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3844 RestartSubstrate_ = true;
3847 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3848 if ([self popErrorWithTitle:title])
3851 if (result == pkgPackageManager::Failed) {
3856 if (result != pkgPackageManager::Completed) {
3861 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3863 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3865 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3866 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3869 if (![before isEqualToArray:after])
3874 NSString *title(UCLocalize("UPGRADE"));
3875 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3881 [self updateWithStatus:status_];
3884 - (void) updateWithStatus:(CancelStatus &)status {
3885 NSString *title(UCLocalize("REFRESHING_DATA"));
3888 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3892 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3893 if ([self popErrorWithTitle:title])
3896 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3898 bool success(ListUpdate(status, list, PulseInterval_));
3899 if (status.WasCancelled())
3902 [self popErrorWithTitle:title forOperation:success];
3903 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3907 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3910 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3911 delegate_ = delegate;
3914 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3915 progress_ = delegate;
3916 status_.setDelegate(delegate);
3919 - (NSObject<ProgressDelegate> *) progressDelegate {
3923 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3924 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3925 return i == sourceMap_.end() ? nil : i->second;
3928 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
3929 for (Source *source in (id) sourceList_)
3930 [source setFetch:fetch forURI:uri];
3933 - (void) resetFetch {
3934 for (Source *source in (id) sourceList_)
3935 [source resetFetch];
3938 - (NSString *) mappedSectionForPointer:(const char *)section {
3939 _H<NSString> *mapped;
3941 _profile(Database$mappedSectionForPointer$Cache)
3942 mapped = §ions_[section];
3945 if (*mapped == NULL) {
3946 size_t length(strlen(section));
3947 char spaced[length + 1];
3949 _profile(Database$mappedSectionForPointer$Replace)
3950 for (size_t index(0); index != length; ++index)
3951 spaced[index] = section[index] == '_' ? ' ' : section[index];
3952 spaced[length] = '\0';
3957 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3958 string = [NSString stringWithUTF8String:spaced];
3961 _profile(Database$mappedSectionForPointer$Map)
3962 string = [SectionMap_ objectForKey:string] ?: string;
3972 static _H<NSMutableSet> Diversions_;
3974 @interface Diversion : NSObject {
3977 _H<NSString> format_;
3982 @implementation Diversion
3984 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3985 if ((self = [super init]) != nil) {
3986 pattern_ = [from UTF8String];
3992 - (NSString *) divert:(NSString *)url {
3993 return !pattern_(url) ? nil : pattern_->*format_;
3996 + (NSURL *) divertURL:(NSURL *)url {
3998 NSString *href([url absoluteString]);
4000 for (Diversion *diversion in (id) Diversions_)
4001 if (NSString *diverted = [diversion divert:href]) {
4003 NSLog(@"div: %@", diverted);
4005 url = [NSURL URLWithString:diverted];
4012 - (NSString *) key {
4016 - (NSUInteger) hash {
4020 - (BOOL) isEqual:(Diversion *)object {
4021 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4026 @interface CydiaObject : NSObject {
4027 _H<CyteWebViewController> indirect_;
4028 _transient id delegate_;
4031 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4037 @interface CydiaWebViewController : CyteWebViewController {
4038 _H<CydiaObject> cydia_;
4041 + (void) addDiversion:(Diversion *)diversion;
4042 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4043 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4044 - (void) setDelegate:(id)delegate;
4048 /* Web Scripting {{{ */
4049 @implementation CydiaObject
4051 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4052 if ((self = [super init]) != nil) {
4053 indirect_ = (CyteWebViewController *) indirect;
4057 - (void) setDelegate:(id)delegate {
4058 delegate_ = delegate;
4061 + (NSArray *) _attributeKeys {
4062 return [NSArray arrayWithObjects:
4065 @"coreFoundationVersionNumber",
4082 - (NSArray *) attributeKeys {
4083 return [[self class] _attributeKeys];
4086 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4087 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4090 - (NSString *) version {
4094 - (NSString *) build {
4098 - (NSString *) coreFoundationVersionNumber {
4099 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4102 - (NSString *) device {
4103 return UniqueIdentifier();
4106 - (NSString *) firmware {
4107 return [[UIDevice currentDevice] systemVersion];
4110 - (NSString *) hostname {
4111 return [[UIDevice currentDevice] name];
4114 - (NSString *) idiom {
4115 return (id) Idiom_ ?: [NSNull null];
4118 - (NSString *) mcc {
4119 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4120 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4124 - (NSString *) mnc {
4125 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4126 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4130 - (NSString *) operator {
4131 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4132 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4136 - (NSString *) bbsnum {
4137 return (id) BBSNum_ ?: [NSNull null];
4140 - (NSString *) ecid {
4141 return (id) ChipID_ ?: [NSNull null];
4144 - (NSString *) serial {
4145 return SerialNumber_;
4148 - (NSString *) role {
4149 return (id) [NSNull null];
4152 - (NSString *) model {
4153 return [NSString stringWithUTF8String:Machine_];
4156 - (NSString *) token {
4157 return (id) Token_ ?: [NSNull null];
4160 + (NSString *) webScriptNameForSelector:(SEL)selector {
4162 else if (selector == @selector(addBridgedHost:))
4163 return @"addBridgedHost";
4164 else if (selector == @selector(addInsecureHost:))
4165 return @"addInsecureHost";
4166 else if (selector == @selector(addInternalRedirect::))
4167 return @"addInternalRedirect";
4168 else if (selector == @selector(addPipelinedHost:scheme:))
4169 return @"addPipelinedHost";
4170 else if (selector == @selector(addSource:::))
4171 return @"addSource";
4172 else if (selector == @selector(addTokenHost:))
4173 return @"addTokenHost";
4174 else if (selector == @selector(addTrivialSource:))
4175 return @"addTrivialSource";
4176 else if (selector == @selector(close))
4178 else if (selector == @selector(du:))
4180 else if (selector == @selector(stringWithFormat:arguments:))
4182 else if (selector == @selector(getAllSources))
4183 return @"getAllSources";
4184 else if (selector == @selector(getApplicationInfo:value:))
4185 return @"getApplicationInfoValue";
4186 else if (selector == @selector(getKernelNumber:))
4187 return @"getKernelNumber";
4188 else if (selector == @selector(getKernelString:))
4189 return @"getKernelString";
4190 else if (selector == @selector(getInstalledPackages))
4191 return @"getInstalledPackages";
4192 else if (selector == @selector(getIORegistryEntry::))
4193 return @"getIORegistryEntry";
4194 else if (selector == @selector(getLocaleIdentifier))
4195 return @"getLocaleIdentifier";
4196 else if (selector == @selector(getPreferredLanguages))
4197 return @"getPreferredLanguages";
4198 else if (selector == @selector(getPackageById:))
4199 return @"getPackageById";
4200 else if (selector == @selector(getMetadataKeys))
4201 return @"getMetadataKeys";
4202 else if (selector == @selector(getMetadataValue:))
4203 return @"getMetadataValue";
4204 else if (selector == @selector(getSessionValue:))
4205 return @"getSessionValue";
4206 else if (selector == @selector(installPackages:))
4207 return @"installPackages";
4208 else if (selector == @selector(isReachable:))
4209 return @"isReachable";
4210 else if (selector == @selector(localizedStringForKey:value:table:))
4212 else if (selector == @selector(popViewController:))
4213 return @"popViewController";
4214 else if (selector == @selector(refreshSources))
4215 return @"refreshSources";
4216 else if (selector == @selector(registerFrame:))
4217 return @"registerFrame";
4218 else if (selector == @selector(removeButton))
4219 return @"removeButton";
4220 else if (selector == @selector(saveConfig))
4221 return @"saveConfig";
4222 else if (selector == @selector(setMetadataValue::))
4223 return @"setMetadataValue";
4224 else if (selector == @selector(setSessionValue::))
4225 return @"setSessionValue";
4226 else if (selector == @selector(substitutePackageNames:))
4227 return @"substitutePackageNames";
4228 else if (selector == @selector(scrollToBottom:))
4229 return @"scrollToBottom";
4230 else if (selector == @selector(setAllowsNavigationAction:))
4231 return @"setAllowsNavigationAction";
4232 else if (selector == @selector(setBadgeValue:))
4233 return @"setBadgeValue";
4234 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4235 return @"setButtonImage";
4236 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4237 return @"setButtonTitle";
4238 else if (selector == @selector(setHidesBackButton:))
4239 return @"setHidesBackButton";
4240 else if (selector == @selector(setHidesNavigationBar:))
4241 return @"setHidesNavigationBar";
4242 else if (selector == @selector(setNavigationBarStyle:))
4243 return @"setNavigationBarStyle";
4244 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4245 return @"setNavigationBarTintColor";
4246 else if (selector == @selector(setPasteboardString:))
4247 return @"setPasteboardString";
4248 else if (selector == @selector(setPasteboardURL:))
4249 return @"setPasteboardURL";
4250 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4251 return @"setScrollAlwaysBounceVertical";
4252 else if (selector == @selector(setScrollIndicatorStyle:))
4253 return @"setScrollIndicatorStyle";
4254 else if (selector == @selector(setToken:))
4256 else if (selector == @selector(setViewportWidth:))
4257 return @"setViewportWidth";
4258 else if (selector == @selector(statfs:))
4260 else if (selector == @selector(supports:))
4262 else if (selector == @selector(unload))
4268 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4269 return [self webScriptNameForSelector:selector] == nil;
4272 - (BOOL) supports:(NSString *)feature {
4273 return [feature isEqualToString:@"window.open"];
4277 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4280 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4281 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4284 - (void) setScrollIndicatorStyle:(NSString *)style {
4285 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4288 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4289 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4292 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4294 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4295 return (id) [NSNull null];
4296 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4298 return (id) [NSNull null];
4299 return [info objectForKey:key];
4302 - (NSNumber *) getKernelNumber:(NSString *)name {
4303 const char *string([name UTF8String]);
4306 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4307 return (id) [NSNull null];
4309 if (size != sizeof(int))
4310 return (id) [NSNull null];
4313 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4314 return (id) [NSNull null];
4316 return [NSNumber numberWithInt:value];
4319 - (NSString *) getKernelString:(NSString *)name {
4320 const char *string([name UTF8String]);
4323 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4324 return (id) [NSNull null];
4326 char value[size + 1];
4327 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4328 return (id) [NSNull null];
4330 // XXX: just in case you request something ludicrous
4333 return [NSString stringWithCString:value];
4336 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4337 NSObject *value(CYIOGetValue([path UTF8String], entry));
4340 if ([value isKindOfClass:[NSData class]])
4341 value = CYHex((NSData *) value);
4346 - (NSArray *) getMetadataKeys {
4347 @synchronized (Values_) {
4348 return [Values_ allKeys];
4351 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4352 WebFrame *frame([iframe contentFrame]);
4353 [indirect_ registerFrame:frame];
4356 - (id) getMetadataValue:(NSString *)key {
4357 @synchronized (Values_) {
4358 return [Values_ objectForKey:key];
4361 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4362 @synchronized (Values_) {
4363 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4364 [Values_ removeObjectForKey:key];
4366 [Values_ setObject:value forKey:key];
4368 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4371 - (id) getSessionValue:(NSString *)key {
4372 @synchronized (SessionData_) {
4373 return [SessionData_ objectForKey:key];
4376 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4377 @synchronized (SessionData_) {
4378 if (value == (id) [WebUndefined undefined])
4379 [SessionData_ removeObjectForKey:key];
4381 [SessionData_ setObject:value forKey:key];
4384 - (void) addBridgedHost:(NSString *)host {
4385 @synchronized (HostConfig_) {
4386 [BridgedHosts_ addObject:host];
4389 - (void) addInsecureHost:(NSString *)host {
4390 @synchronized (HostConfig_) {
4391 [InsecureHosts_ addObject:host];
4394 - (void) addTokenHost:(NSString *)host {
4395 @synchronized (HostConfig_) {
4396 [TokenHosts_ addObject:host];
4399 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4400 @synchronized (HostConfig_) {
4401 if (scheme != (id) [WebUndefined undefined])
4402 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4404 [PipelinedHosts_ addObject:host];
4407 - (void) popViewController:(NSNumber *)value {
4408 if (value == (id) [WebUndefined undefined])
4409 value = [NSNumber numberWithBool:YES];
4410 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4413 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4414 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4416 for (NSString *section in sections)
4417 [array addObject:section];
4419 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4422 distribution, @"Distribution",
4424 nil] waitUntilDone:NO];
4427 - (void) addTrivialSource:(NSString *)href {
4428 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4431 - (void) refreshSources {
4432 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4435 - (void) saveConfig {
4436 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4439 - (NSArray *) getAllSources {
4440 return [[Database sharedInstance] sources];
4443 - (NSArray *) getInstalledPackages {
4444 Database *database([Database sharedInstance]);
4445 @synchronized (database) {
4446 NSArray *packages([database packages]);
4447 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4448 for (Package *package in packages)
4449 if (![package uninstalled])
4450 [installed addObject:package];
4454 - (Package *) getPackageById:(NSString *)id {
4455 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4459 return (Package *) [NSNull null];
4462 - (NSString *) getLocaleIdentifier {
4463 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4466 - (NSArray *) getPreferredLanguages {
4470 - (NSArray *) statfs:(NSString *)path {
4473 if (path == nil || statfs([path UTF8String], &stat) == -1)
4476 return [NSArray arrayWithObjects:
4477 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4478 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4479 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4483 - (NSNumber *) du:(NSString *)path {
4484 NSNumber *value(nil);
4487 _assert(pipe(fds) != -1);
4489 pid_t pid(ExecFork());
4491 _assert(dup2(fds[1], 1) != -1);
4492 _assert(close(fds[0]) != -1);
4493 _assert(close(fds[1]) != -1);
4494 /* XXX: this should probably not use du */
4495 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4498 _assert(close(fds[1]) != -1);
4500 if (FILE *du = fdopen(fds[0], "r")) {
4502 while (fgets(line, sizeof(line), du) != NULL) {
4503 size_t length(strlen(line));
4504 while (length != 0 && line[length - 1] == '\n')
4505 line[--length] = '\0';
4506 if (char *tab = strchr(line, '\t')) {
4508 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4514 _assert(close(fds[0]) != -1);
4521 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4524 - (NSNumber *) isReachable:(NSString *)name {
4525 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4528 - (void) installPackages:(NSArray *)packages {
4529 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4532 - (NSString *) substitutePackageNames:(NSString *)message {
4533 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4534 for (size_t i(0), e([words count]); i != e; ++i) {
4535 NSString *word([words objectAtIndex:i]);
4536 if (Package *package = [[Database sharedInstance] packageWithName:word])
4537 [words replaceObjectAtIndex:i withObject:[package name]];
4540 return [words componentsJoinedByString:@" "];
4543 - (void) removeButton {
4544 [indirect_ removeButton];
4547 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4548 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4551 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4552 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4555 - (void) setBadgeValue:(id)value {
4556 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4559 - (void) setAllowsNavigationAction:(NSString *)value {
4560 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4563 - (void) setHidesBackButton:(NSString *)value {
4564 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4567 - (void) setHidesNavigationBar:(NSString *)value {
4568 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4571 - (void) setNavigationBarStyle:(NSString *)value {
4572 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4575 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4576 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4577 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4578 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4581 - (void) setPasteboardString:(NSString *)value {
4582 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4585 - (void) setPasteboardURL:(NSString *)value {
4586 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4589 - (void) _setToken:(NSString *)token {
4593 [Metadata_ removeObjectForKey:@"Token"];
4595 [Metadata_ setObject:Token_ forKey:@"Token"];
4600 - (void) setToken:(NSString *)token {
4601 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4604 - (void) scrollToBottom:(NSNumber *)animated {
4605 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4608 - (void) setViewportWidth:(float)width {
4609 [indirect_ setViewportWidthOnMainThread:width];
4612 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4613 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4614 unsigned count([arguments count]);
4616 for (unsigned i(0); i != count; ++i)
4617 values[i] = [arguments objectAtIndex:i];
4618 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4621 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4622 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4624 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4626 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4632 @interface NSURL (CydiaSecure)
4635 @implementation NSURL (CydiaSecure)
4637 - (bool) isCydiaSecure {
4638 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4641 @synchronized (HostConfig_) {
4642 if ([InsecureHosts_ containsObject:[self host]])
4651 /* Cydia Browser Controller {{{ */
4652 @implementation CydiaWebViewController
4654 - (NSURL *) navigationURL {
4655 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4658 + (void) _initialize {
4659 [super _initialize];
4661 Diversions_ = [NSMutableSet setWithCapacity:0];
4664 + (void) addDiversion:(Diversion *)diversion {
4665 [Diversions_ addObject:diversion];
4668 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4669 [super webView:view didClearWindowObject:window forFrame:frame];
4670 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4673 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4674 WebDataSource *source([frame dataSource]);
4675 NSURLResponse *response([source response]);
4676 NSURL *url([response URL]);
4677 NSString *scheme([[url scheme] lowercaseString]);
4679 bool bridged(false);
4681 @synchronized (HostConfig_) {
4682 if ([scheme isEqualToString:@"file"])
4684 else if ([scheme isEqualToString:@"https"])
4685 if ([BridgedHosts_ containsObject:[url host]])
4690 [window setValue:cydia forKey:@"cydia"];
4693 - (void) _setupMail:(MFMailComposeViewController *)controller {
4694 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4696 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4697 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4700 - (NSURL *) URLWithURL:(NSURL *)url {
4701 return [Diversion divertURL:url];
4704 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4705 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4708 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4709 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4711 NSURL *url([copy URL]);
4712 NSString *href([url absoluteString]);
4713 NSString *host([url host]);
4715 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4716 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4717 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4718 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4721 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4722 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4724 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4728 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4729 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4730 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4731 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4736 @synchronized (HostConfig_) {
4737 bridged = [BridgedHosts_ containsObject:host];
4738 token = [TokenHosts_ containsObject:host];
4741 if ([url isCydiaSecure]) {
4743 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4744 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4746 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4747 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4754 - (void) setDelegate:(id)delegate {
4755 [super setDelegate:delegate];
4756 [cydia_ setDelegate:delegate];
4759 - (NSString *) applicationNameForUserAgent {
4764 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4765 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4771 @interface AppCacheController : CydiaWebViewController {
4776 @implementation AppCacheController
4778 - (void) didReceiveMemoryWarning {
4779 // XXX: this doesn't work
4782 - (bool) retainsNetworkActivityIndicator {
4790 @interface NSObject (CydiaScript)
4791 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4794 @implementation NSObject (CydiaScript)
4796 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4802 @implementation NSArray (CydiaScript)
4804 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4805 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4806 for (size_t i(0), e([self count]); i != e; ++i)
4807 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4813 @implementation NSDictionary (CydiaScript)
4815 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4816 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4818 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4825 /* Confirmation Controller {{{ */
4826 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4827 if (!iterator.end())
4828 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4829 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4831 pkgCache::PkgIterator package(dep.TargetPkg());
4834 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4841 @protocol ConfirmationControllerDelegate
4842 - (void) cancelAndClear:(bool)clear;
4843 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4847 @interface ConfirmationController : CydiaWebViewController {
4848 _transient Database *database_;
4850 _H<UIAlertView> essential_;
4852 _H<NSDictionary> changes_;
4853 _H<NSMutableArray> issues_;
4854 _H<NSDictionary> sizes_;
4859 - (id) initWithDatabase:(Database *)database;
4863 @implementation ConfirmationController
4867 RestartSubstrate_ = true;
4868 [delegate_ confirmWithNavigationController:[self navigationController]];
4871 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4872 NSString *context([alert context]);
4874 if ([context isEqualToString:@"remove"]) {
4875 if (button == [alert cancelButtonIndex])
4876 [self dismissModalViewControllerAnimated:YES];
4877 else if (button == [alert firstOtherButtonIndex]) {
4878 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
4881 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4882 } else if ([context isEqualToString:@"unable"]) {
4883 [self dismissModalViewControllerAnimated:YES];
4884 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4886 [super alertView:alert clickedButtonAtIndex:button];
4890 - (void) _doContinue {
4891 [delegate_ cancelAndClear:NO];
4892 [self dismissModalViewControllerAnimated:YES];
4895 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4896 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4900 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4901 [super webView:view didClearWindowObject:window forFrame:frame];
4903 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4904 (id) changes_, @"changes",
4905 (id) issues_, @"issues",
4906 (id) sizes_, @"sizes",
4908 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4911 - (id) initWithDatabase:(Database *)database {
4912 if ((self = [super init]) != nil) {
4913 database_ = database;
4915 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4916 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4917 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4918 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4919 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4923 pkgCacheFile &cache([database_ cache]);
4924 NSArray *packages([database_ packages]);
4925 pkgDepCache::Policy *policy([database_ policy]);
4927 issues_ = [NSMutableArray arrayWithCapacity:4];
4929 for (Package *package in packages) {
4930 pkgCache::PkgIterator iterator([package iterator]);
4931 NSString *name([package id]);
4933 if ([package broken]) {
4934 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4936 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4938 reasons, @"reasons",
4941 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4945 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4946 pkgCache::DepIterator start;
4947 pkgCache::DepIterator end;
4948 dep.GlobOr(start, end); // ++dep
4950 if (!cache->IsImportantDep(end))
4952 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4955 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4957 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4958 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4959 clauses, @"clauses",
4963 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4965 pkgCache::PkgIterator target(start.TargetPkg());
4966 if (target->ProvidesList != 0)
4967 reason = @"missing";
4969 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4971 reason = @"installed";
4972 installed = [NSString stringWithUTF8String:ver.VerStr()];
4973 } else if (!cache[target].CandidateVerIter(cache).end())
4974 reason = @"uninstalled";
4975 else if (target->ProvidesList == 0)
4976 reason = @"uninstallable";
4978 reason = @"virtual";
4981 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4982 [NSString stringWithUTF8String:start.CompType()], @"operator",
4983 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4986 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4987 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4988 version, @"version",
4990 installed, @"installed",
4993 // yes, seriously. (wtf?)
5001 pkgDepCache::StateCache &state(cache[iterator]);
5003 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
5005 if (state.NewInstall())
5006 [installs addObject:name];
5007 // XXX: else if (state.Install())
5008 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5009 [reinstalls addObject:name];
5010 // XXX: move before previous if
5011 else if (state.Upgrade())
5012 [upgrades addObject:name];
5013 else if (state.Downgrade())
5014 [downgrades addObject:name];
5015 else if (!state.Delete())
5016 // XXX: _assert(state.Keep());
5018 else if (special_r(name))
5019 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5020 [NSNull null], @"package",
5021 [NSArray arrayWithObjects:
5022 [NSDictionary dictionaryWithObjectsAndKeys:
5023 @"Conflicts", @"relationship",
5024 [NSArray arrayWithObjects:
5025 [NSDictionary dictionaryWithObjectsAndKeys:
5027 [NSNull null], @"version",
5028 @"installed", @"reason",
5035 if ([package essential])
5037 [removes addObject:name];
5040 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5041 substrate_ |= DepSubstrate(iterator.CurrentVer());
5046 else if (Advanced_) {
5047 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5049 essential_ = [[[UIAlertView alloc]
5050 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5051 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5053 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5055 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5059 [essential_ setContext:@"remove"];
5060 [essential_ setNumberOfRows:2];
5062 essential_ = [[[UIAlertView alloc]
5063 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5064 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5066 cancelButtonTitle:UCLocalize("OKAY")
5067 otherButtonTitles:nil
5070 [essential_ setContext:@"unable"];
5073 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5074 installs, @"installs",
5075 reinstalls, @"reinstalls",
5076 upgrades, @"upgrades",
5077 downgrades, @"downgrades",
5078 removes, @"removes",
5081 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5082 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5083 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5086 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5090 - (UIBarButtonItem *) leftButton {
5091 return [[[UIBarButtonItem alloc]
5092 initWithTitle:UCLocalize("CANCEL")
5093 style:UIBarButtonItemStylePlain
5095 action:@selector(cancelButtonClicked)
5100 - (void) applyRightButton {
5101 if ([issues_ count] == 0 && ![self isLoading])
5102 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5103 initWithTitle:UCLocalize("CONFIRM")
5104 style:UIBarButtonItemStyleDone
5106 action:@selector(confirmButtonClicked)
5109 [[self navigationItem] setRightBarButtonItem:nil];
5113 - (void) cancelButtonClicked {
5114 [delegate_ cancelAndClear:YES];
5115 [self dismissModalViewControllerAnimated:YES];
5119 - (void) confirmButtonClicked {
5120 if (essential_ != nil)
5130 /* Progress Data {{{ */
5131 @interface CydiaProgressData : NSObject {
5132 _transient id delegate_;
5141 _H<NSMutableArray> events_;
5142 _H<NSString> title_;
5144 _H<NSString> status_;
5145 _H<NSString> finish_;
5150 @implementation CydiaProgressData
5152 + (NSArray *) _attributeKeys {
5153 return [NSArray arrayWithObjects:
5165 - (NSArray *) attributeKeys {
5166 return [[self class] _attributeKeys];
5169 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5170 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5174 if ((self = [super init]) != nil) {
5175 events_ = [NSMutableArray arrayWithCapacity:32];
5183 - (void) setDelegate:(id)delegate {
5184 delegate_ = delegate;
5187 - (void) setPercent:(float)value {
5191 - (NSNumber *) percent {
5192 return [NSNumber numberWithFloat:percent_];
5195 - (void) setCurrent:(float)value {
5199 - (NSNumber *) current {
5200 return [NSNumber numberWithFloat:current_];
5203 - (void) setTotal:(float)value {
5207 - (NSNumber *) total {
5208 return [NSNumber numberWithFloat:total_];
5211 - (void) setSpeed:(float)value {
5215 - (NSNumber *) speed {
5216 return [NSNumber numberWithFloat:speed_];
5219 - (NSArray *) events {
5223 - (void) removeAllEvents {
5224 [events_ removeAllObjects];
5227 - (void) addEvent:(CydiaProgressEvent *)event {
5228 [events_ addObject:event];
5231 - (void) setTitle:(NSString *)text {
5235 - (NSString *) title {
5239 - (void) setFinish:(NSString *)text {
5243 - (NSString *) finish {
5244 return (id) finish_ ?: [NSNull null];
5247 - (void) setRunning:(bool)running {
5251 - (NSNumber *) running {
5252 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5257 /* Progress Controller {{{ */
5258 @interface ProgressController : CydiaWebViewController <
5261 _transient Database *database_;
5262 _H<CydiaProgressData, 1> progress_;
5266 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5268 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5270 - (void) setTitle:(NSString *)title;
5271 - (void) setCancellable:(bool)cancellable;
5275 @implementation ProgressController
5278 [database_ setProgressDelegate:nil];
5282 - (UIBarButtonItem *) leftButton {
5283 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5284 initWithTitle:UCLocalize("CANCEL")
5285 style:UIBarButtonItemStylePlain
5287 action:@selector(cancel)
5288 ] autorelease] : nil;
5291 - (void) updateCancel {
5292 [super applyLeftButton];
5295 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5296 if ((self = [super init]) != nil) {
5297 database_ = database;
5298 delegate_ = delegate;
5300 [database_ setProgressDelegate:self];
5302 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5303 [progress_ setDelegate:self];
5305 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5307 [scroller_ setBackgroundColor:[UIColor blackColor]];
5309 [[self navigationItem] setHidesBackButton:YES];
5311 [self updateCancel];
5315 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5316 [super webView:view didClearWindowObject:window forFrame:frame];
5317 [window setValue:progress_ forKey:@"cydiaProgress"];
5320 - (void) updateProgress {
5321 [self dispatchEvent:@"CydiaProgressUpdate"];
5324 - (void) viewWillAppear:(BOOL)animated {
5325 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5326 [super viewWillAppear:animated];
5329 - (void) reloadSpringBoard {
5330 if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
5331 system("/bin/launchctl stop com.apple.backboardd");
5333 system("/usr/bin/killall backboardd SpringBoard sbreload");
5337 pid_t pid(ExecFork());
5342 pid_t pid(ExecFork());
5344 execl("/usr/bin/sbreload", "sbreload", NULL);
5354 system("/usr/bin/killall backboardd SpringBoard sbreload");
5358 UpdateExternalStatus(0);
5361 [delegate_ saveState];
5365 [delegate_ returnToCydia];
5369 [delegate_ terminateWithSuccess];
5370 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5371 [delegate_ suspendWithAnimation:YES];
5373 [delegate_ suspend];*/
5385 UIProgressHUD *hud([delegate_ addProgressHUD]);
5386 [hud setText:UCLocalize("LOADING")];
5387 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5393 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5394 SBReboot(SBSSpringBoardServerPort());
5396 reboot2(RB_AUTOBOOT);
5403 - (void) setTitle:(NSString *)title {
5404 [progress_ setTitle:title];
5405 [self updateProgress];
5408 - (UIBarButtonItem *) rightButton {
5409 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5410 initWithTitle:UCLocalize("CLOSE")
5411 style:UIBarButtonItemStylePlain
5413 action:@selector(close)
5417 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5418 UpdateExternalStatus(1);
5420 [progress_ setRunning:true];
5421 [self setTitle:title];
5422 // implicit updateProgress
5424 SHA1SumValue notifyconf; {
5426 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5429 MMap mmap(file, MMap::ReadOnly);
5431 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5432 notifyconf = sha1.Result();
5436 SHA1SumValue springlist; {
5438 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5441 MMap mmap(file, MMap::ReadOnly);
5443 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5444 springlist = sha1.Result();
5448 if (invocation != nil) {
5449 [invocation yieldToSelector:@selector(invoke)];
5450 [self setTitle:@"COMPLETE"];
5455 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5458 MMap mmap(file, MMap::ReadOnly);
5460 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5461 if (!(notifyconf == sha1.Result()))
5468 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5471 MMap mmap(file, MMap::ReadOnly);
5473 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5474 if (!(springlist == sha1.Result()))
5480 if (RestartSubstrate_)
5484 RestartSubstrate_ = false;
5487 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5488 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5489 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5490 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5491 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5494 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5496 [progress_ setRunning:false];
5497 [self updateProgress];
5499 [self applyRightButton];
5502 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5503 [progress_ addEvent:event];
5504 [self updateProgress];
5507 - (bool) isProgressCancelled {
5508 return cancel_ == 2;
5513 [self updateCancel];
5516 - (void) setCancellable:(bool)cancellable {
5517 unsigned cancel(cancel_);
5521 else if (cancel_ == 0)
5524 if (cancel != cancel_)
5525 [self updateCancel];
5528 - (void) setProgressCancellable:(NSNumber *)cancellable {
5529 [self setCancellable:[cancellable boolValue]];
5532 - (void) setProgressPercent:(NSNumber *)percent {
5533 [progress_ setPercent:[percent floatValue]];
5534 [self updateProgress];
5537 - (void) setProgressStatus:(NSDictionary *)status {
5538 if (status == nil) {
5539 [progress_ setCurrent:0];
5540 [progress_ setTotal:0];
5541 [progress_ setSpeed:0];
5543 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5545 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5546 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5547 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5550 [self updateProgress];
5556 /* Package Cell {{{ */
5557 @interface PackageCell : CyteTableViewCell <
5558 CyteTableViewCellDelegate
5562 _H<NSString> description_;
5564 _H<NSString> source_;
5566 _H<UIImage> placard_;
5570 - (PackageCell *) init;
5571 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5573 - (void) drawContentRect:(CGRect)rect;
5577 @implementation PackageCell
5579 - (PackageCell *) init {
5580 CGRect frame(CGRectMake(0, 0, 320, 74));
5581 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5582 UIView *content([self contentView]);
5583 CGRect bounds([content bounds]);
5585 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5586 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5587 [content addSubview:content_];
5589 [content_ setDelegate:self];
5590 [content_ setOpaque:YES];
5594 - (NSString *) accessibilityLabel {
5598 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5599 summarized_ = summary;
5609 [content_ setBackgroundColor:[UIColor whiteColor]];
5613 Source *source = [package source];
5615 icon_ = [package icon];
5617 if (NSString *name = [package name])
5618 name_ = [NSString stringWithString:name];
5620 if (NSString *description = [package shortDescription])
5621 description_ = [NSString stringWithString:description];
5623 commercial_ = [package isCommercial];
5625 NSString *label = nil;
5626 bool trusted = false;
5628 if (source != nil) {
5629 label = [source label];
5630 trusted = [source trusted];
5631 } else if ([[package id] isEqualToString:@"firmware"])
5632 label = UCLocalize("APPLE");
5634 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5636 NSString *from(label);
5638 NSString *section = [package simpleSection];
5639 if (section != nil && ![section isEqualToString:label]) {
5640 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5641 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5644 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5646 if (NSString *purpose = [package primaryPurpose])
5647 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5652 if (NSString *mode = [package mode]) {
5653 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5654 color = RemovingColor_;
5655 placard = @"removing";
5657 color = InstallingColor_;
5658 placard = @"installing";
5661 color = [UIColor whiteColor];
5663 if ([package installed] != nil)
5664 placard = @"installed";
5669 [content_ setBackgroundColor:color];
5672 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5675 [self setNeedsDisplay];
5676 [content_ setNeedsDisplay];
5679 - (void) drawSummaryContentRect:(CGRect)rect {
5680 bool highlighted(highlighted_);
5681 float width([self bounds].size.width);
5685 rect.size = [(UIImage *) icon_ size];
5687 while (rect.size.width > 16 || rect.size.height > 16) {
5688 rect.size.width /= 2;
5689 rect.size.height /= 2;
5692 rect.origin.x = 19 - rect.size.width / 2;
5693 rect.origin.y = 19 - rect.size.height / 2;
5695 [icon_ drawInRect:rect];
5698 if (badge_ != nil) {
5700 rect.size = [(UIImage *) badge_ size];
5702 rect.size.width /= 4;
5703 rect.size.height /= 4;
5705 rect.origin.x = 25 - rect.size.width / 2;
5706 rect.origin.y = 25 - rect.size.height / 2;
5708 [badge_ drawInRect:rect];
5711 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5715 UISetColor(commercial_ ? Purple_ : Black_);
5716 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5718 if (placard_ != nil)
5719 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5722 - (void) drawNormalContentRect:(CGRect)rect {
5723 bool highlighted(highlighted_);
5724 float width([self bounds].size.width);
5728 rect.size = [(UIImage *) icon_ size];
5730 while (rect.size.width > 32 || rect.size.height > 32) {
5731 rect.size.width /= 2;
5732 rect.size.height /= 2;
5735 rect.origin.x = 25 - rect.size.width / 2;
5736 rect.origin.y = 25 - rect.size.height / 2;
5738 [icon_ drawInRect:rect];
5741 if (badge_ != nil) {
5743 rect.size = [(UIImage *) badge_ size];
5745 rect.size.width /= 2;
5746 rect.size.height /= 2;
5748 rect.origin.x = 36 - rect.size.width / 2;
5749 rect.origin.y = 36 - rect.size.height / 2;
5751 [badge_ drawInRect:rect];
5754 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5758 UISetColor(commercial_ ? Purple_ : Black_);
5759 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5760 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5763 UISetColor(commercial_ ? Purplish_ : Gray_);
5764 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
5766 if (placard_ != nil)
5767 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5770 - (void) drawContentRect:(CGRect)rect {
5772 [self drawSummaryContentRect:rect];
5774 [self drawNormalContentRect:rect];
5779 /* Section Cell {{{ */
5780 @interface SectionCell : CyteTableViewCell <
5781 CyteTableViewCellDelegate
5783 _H<NSString> basic_;
5784 _H<NSString> section_;
5786 _H<NSString> count_;
5788 _H<UISwitch> switch_;
5792 - (void) setSection:(Section *)section editing:(BOOL)editing;
5796 @implementation SectionCell
5798 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5799 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5800 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5801 // XXX: this initial frame is wrong, but is fixed later
5802 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5803 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5805 UIView *content([self contentView]);
5806 CGRect bounds([content bounds]);
5808 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5809 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5810 [content addSubview:content_];
5811 [content_ setBackgroundColor:[UIColor whiteColor]];
5813 [content_ setDelegate:self];
5817 - (void) onSwitch:(id)sender {
5818 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5819 if (metadata == nil) {
5820 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5821 [Sections_ setObject:metadata forKey:basic_];
5824 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5828 - (void) setSection:(Section *)section editing:(BOOL)editing {
5829 if (editing != editing_) {
5831 [switch_ removeFromSuperview];
5833 [self addSubview:switch_];
5842 if (section == nil) {
5843 name_ = UCLocalize("ALL_PACKAGES");
5846 basic_ = [section name];
5847 section_ = [section localized];
5849 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5850 count_ = [NSString stringWithFormat:@"%zd", [section count]];
5853 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5856 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5857 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5859 [content_ setNeedsDisplay];
5862 - (void) setFrame:(CGRect)frame {
5863 [super setFrame:frame];
5865 CGRect rect([switch_ frame]);
5866 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
5869 - (NSString *) accessibilityLabel {
5873 - (void) drawContentRect:(CGRect)rect {
5874 bool highlighted(highlighted_ && !editing_);
5876 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
5878 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5881 float width(rect.size.width);
5883 width -= 9 + [switch_ frame].size.width;
5887 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
5889 CGSize size = [count_ sizeWithFont:Font14_];
5891 UISetColor(Folder_);
5893 [count_ drawAtPoint:CGPointMake(10 + (30 - size.width) / 2, 18) withFont:Font12Bold_];
5899 /* File Table {{{ */
5900 @interface FileTable : CyteViewController <
5901 UITableViewDataSource,
5904 _transient Database *database_;
5905 _H<Package> package_;
5907 _H<NSMutableArray> files_;
5908 _H<UITableView, 2> list_;
5911 - (id) initWithDatabase:(Database *)database;
5912 - (void) setPackage:(Package *)package;
5916 @implementation FileTable
5918 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5919 return files_ == nil ? 0 : [files_ count];
5922 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5926 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5927 static NSString *reuseIdentifier = @"Cell";
5929 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5931 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5932 [cell setFont:[UIFont systemFontOfSize:16]];
5934 [cell setText:[files_ objectAtIndex:indexPath.row]];
5935 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5940 - (NSURL *) navigationURL {
5941 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5945 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5946 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5947 [list_ setRowHeight:24.0f];
5948 [(UITableView *) list_ setDataSource:self];
5949 [list_ setDelegate:self];
5950 [self setView:list_];
5953 - (void) viewDidLoad {
5954 [super viewDidLoad];
5956 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5959 - (void) releaseSubviews {
5965 [super releaseSubviews];
5968 - (id) initWithDatabase:(Database *)database {
5969 if ((self = [super init]) != nil) {
5970 database_ = database;
5974 - (void) setPackage:(Package *)package {
5978 files_ = [NSMutableArray arrayWithCapacity:32];
5980 if (package != nil) {
5982 name_ = [package id];
5984 if (NSArray *files = [package files])
5985 [files_ addObjectsFromArray:files];
5987 if ([files_ count] != 0) {
5988 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5989 [files_ removeObjectAtIndex:0];
5990 [files_ sortUsingSelector:@selector(compareByPath:)];
5992 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5993 [stack addObject:@"/"];
5995 for (int i(0), e([files_ count]); i != e; ++i) {
5996 NSString *file = [files_ objectAtIndex:i];
5997 while (![file hasPrefix:[stack lastObject]])
5998 [stack removeLastObject];
5999 NSString *directory = [stack lastObject];
6000 [stack addObject:[file stringByAppendingString:@"/"]];
6001 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6002 ([stack count] - 2) * 3, "",
6003 [file substringFromIndex:[directory length]]
6012 - (void) reloadData {
6015 [self setPackage:[database_ packageWithName:name_]];
6020 /* Package Controller {{{ */
6021 @interface CYPackageController : CydiaWebViewController <
6022 UIActionSheetDelegate
6024 _transient Database *database_;
6025 _H<Package> package_;
6028 _H<NSMutableArray> buttons_;
6029 _H<UIBarButtonItem> button_;
6032 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6036 @implementation CYPackageController
6038 - (NSURL *) navigationURL {
6039 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6042 /* XXX: this is not safe at all... localization of /fail/ */
6043 - (void) _clickButtonWithName:(NSString *)name {
6044 if ([name isEqualToString:UCLocalize("CLEAR")])
6045 [delegate_ clearPackage:package_];
6046 else if ([name isEqualToString:UCLocalize("INSTALL")])
6047 [delegate_ installPackage:package_];
6048 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6049 [delegate_ installPackage:package_];
6050 else if ([name isEqualToString:UCLocalize("REMOVE")])
6051 [delegate_ removePackage:package_];
6052 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6053 [delegate_ installPackage:package_];
6054 else _assert(false);
6057 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6058 NSString *context([sheet context]);
6060 if ([context isEqualToString:@"modify"]) {
6061 if (button != [sheet cancelButtonIndex]) {
6062 NSString *buttonName = [buttons_ objectAtIndex:button];
6063 [self _clickButtonWithName:buttonName];
6066 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6070 - (bool) _allowJavaScriptPanel {
6075 - (void) _customButtonClicked {
6076 int count([buttons_ count]);
6081 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6083 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6084 [buttons addObjectsFromArray:buttons_];
6086 UIActionSheet *sheet = [[[UIActionSheet alloc]
6089 cancelButtonTitle:nil
6090 destructiveButtonTitle:nil
6091 otherButtonTitles:nil
6094 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6096 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6097 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6099 [sheet setContext:@"modify"];
6101 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6105 - (void) reloadButtonClicked {
6106 if (commercial_ && function_ == nil && [package_ uninstalled])
6108 [self customButtonClicked];
6111 - (void) applyLoadingTitle {
6112 // Don't show "Loading" as the title. Ever.
6115 - (UIBarButtonItem *) rightButton {
6120 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6121 if ((self = [super init]) != nil) {
6122 database_ = database;
6123 buttons_ = [NSMutableArray arrayWithCapacity:4];
6124 name_ = name == nil ? @"" : [NSString stringWithString:name];
6125 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6129 - (void) reloadData {
6132 package_ = [database_ packageWithName:name_];
6134 [buttons_ removeAllObjects];
6136 if (package_ != nil) {
6137 [(Package *) package_ parse];
6139 commercial_ = [package_ isCommercial];
6141 if ([package_ mode] != nil)
6142 [buttons_ addObject:UCLocalize("CLEAR")];
6143 if ([package_ source] == nil);
6144 else if ([package_ upgradableAndEssential:NO])
6145 [buttons_ addObject:UCLocalize("UPGRADE")];
6146 else if ([package_ uninstalled])
6147 [buttons_ addObject:UCLocalize("INSTALL")];
6149 [buttons_ addObject:UCLocalize("REINSTALL")];
6150 if (![package_ uninstalled])
6151 [buttons_ addObject:UCLocalize("REMOVE")];
6155 switch ([buttons_ count]) {
6156 case 0: title = nil; break;
6157 case 1: title = [buttons_ objectAtIndex:0]; break;
6158 default: title = UCLocalize("MODIFY"); break;
6161 button_ = [[[UIBarButtonItem alloc]
6163 style:UIBarButtonItemStylePlain
6165 action:@selector(customButtonClicked)
6169 - (bool) isLoading {
6170 return commercial_ ? [super isLoading] : false;
6176 /* Package List Controller {{{ */
6177 @interface PackageListController : CyteViewController <
6178 UITableViewDataSource,
6181 _transient Database *database_;
6183 _H<NSArray> packages_;
6184 _H<NSArray> sections_;
6185 _H<UITableView, 2> list_;
6186 _H<NSMutableArray> index_;
6187 _H<NSString> title_;
6188 unsigned reloading_;
6191 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6192 - (void) setDelegate:(id)delegate;
6193 - (void) resetCursor;
6196 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6200 @implementation PackageListController
6202 - (NSURL *) referrerURL {
6203 return [self navigationURL];
6206 - (bool) isSummarized {
6210 - (bool) showsSections {
6214 - (void) deselectWithAnimation:(BOOL)animated {
6215 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6218 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6219 CGRect base = [[self view] bounds];
6220 base.size.height -= bounds.size.height;
6221 base.origin = [list_ frame].origin;
6223 [UIView beginAnimations:nil context:NULL];
6224 [UIView setAnimationBeginsFromCurrentState:YES];
6225 [UIView setAnimationCurve:curve];
6226 [UIView setAnimationDuration:duration];
6227 [list_ setFrame:base];
6228 [UIView commitAnimations];
6231 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6232 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6235 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6236 [self resizeForKeyboardBounds:bounds duration:0];
6239 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6240 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6241 *curve = UIViewAnimationCurveEaseInOut;
6243 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6245 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6248 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6251 - (void) keyboardWillShow:(NSNotification *)notification {
6254 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6255 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6257 NSTimeInterval duration;
6258 UIViewAnimationCurve curve;
6259 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6261 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);
6262 UIViewController *base = self;
6263 while ([base parentOrPresentingViewController] != nil)
6264 base = [base parentOrPresentingViewController];
6265 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6266 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6268 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6269 intersection.size.height += CYStatusBarHeight();
6271 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6274 - (void) keyboardWillHide:(NSNotification *)notification {
6275 NSTimeInterval duration;
6276 UIViewAnimationCurve curve;
6277 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6279 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6282 - (void) viewWillAppear:(BOOL)animated {
6283 [super viewWillAppear:animated];
6285 [self resizeForKeyboardBounds:CGRectZero];
6286 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6287 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6290 - (void) viewWillDisappear:(BOOL)animated {
6291 [super viewWillDisappear:animated];
6293 [self resizeForKeyboardBounds:CGRectZero];
6294 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6295 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6298 - (void) viewDidAppear:(BOOL)animated {
6299 [super viewDidAppear:animated];
6300 [self deselectWithAnimation:animated];
6303 - (void) didSelectPackage:(Package *)package {
6304 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6305 [view setDelegate:delegate_];
6306 [[self navigationController] pushViewController:view animated:YES];
6309 #if TryIndexedCollation
6310 + (BOOL) hasIndexedCollation {
6311 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6315 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6316 NSInteger count([sections_ count]);
6317 return count == 0 ? 1 : count;
6320 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6321 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6323 return [[sections_ objectAtIndex:section] name];
6326 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6327 if ([sections_ count] == 0)
6329 return [[sections_ objectAtIndex:section] count];
6332 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6333 @synchronized (database_) {
6334 if ([database_ era] != era_)
6337 Section *section([sections_ objectAtIndex:[path section]]);
6338 NSInteger row([path row]);
6339 Package *package([packages_ objectAtIndex:([section row] + row)]);
6340 return [[package retain] autorelease];
6343 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6344 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6346 cell = [[[PackageCell alloc] init] autorelease];
6348 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6349 [cell setPackage:package asSummary:[self isSummarized]];
6353 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6354 Package *package([self packageAtIndexPath:path]);
6355 package = [database_ packageWithName:[package id]];
6356 [self didSelectPackage:package];
6359 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6360 if (![self showsSections])
6366 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6367 #if TryIndexedCollation
6368 if ([[self class] hasIndexedCollation]) {
6369 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6376 - (void) updateHeight {
6377 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6380 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6381 if ((self = [super init]) != nil) {
6382 database_ = database;
6383 title_ = [title copy];
6384 [[self navigationItem] setTitle:title_];
6389 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6390 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6391 [self setView:view];
6393 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6394 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6395 [view addSubview:list_];
6397 // XXX: is 20 the most optimal number here?
6398 [list_ setSectionIndexMinimumDisplayRowCount:20];
6400 [(UITableView *) list_ setDataSource:self];
6401 [list_ setDelegate:self];
6403 [self updateHeight];
6406 - (void) releaseSubviews {
6413 [super releaseSubviews];
6416 - (void) setDelegate:(id)delegate {
6417 delegate_ = delegate;
6420 - (bool) shouldYield {
6424 - (bool) shouldBlock {
6428 - (NSMutableArray *) _reloadPackages {
6429 @synchronized (database_) {
6430 era_ = [database_ era];
6431 NSArray *packages([database_ packages]);
6433 return [NSMutableArray arrayWithArray:packages];
6436 - (void) _reloadData {
6437 if (reloading_ != 0) {
6442 NSMutableArray *packages;
6445 if ([self shouldYield]) {
6449 if (![self shouldBlock])
6452 hud = [delegate_ addProgressHUD];
6453 [hud setText:UCLocalize("LOADING")];
6457 packages = [self yieldToSelector:@selector(_reloadPackages)];
6460 [delegate_ removeProgressHUD:hud];
6461 } while (reloading_ == 2);
6463 packages = [self _reloadPackages];
6466 @synchronized (database_) {
6467 if (era_ != [database_ era])
6471 packages_ = packages;
6472 sections_ = [self sectionsForPackages:packages];
6474 [self updateHeight];
6476 _profile(PackageTable$reloadData$List)
6477 [(UITableView *) list_ setDataSource:self];
6482 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6483 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6485 Section *section = nil;
6487 #if TryIndexedCollation
6488 if ([[self class] hasIndexedCollation]) {
6489 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6491 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6492 NSArray *titles = [collation sectionIndexTitles];
6495 _profile(PackageTable$reloadData$Section)
6496 for (size_t offset(0), end([packages count]); offset != end; ++offset) {
6500 _profile(PackageTable$reloadData$Section$Package)
6501 package = [packages objectAtIndex:offset];
6502 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6505 while (secidx < index) {
6508 _profile(PackageTable$reloadData$Section$Allocate)
6509 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6512 _profile(PackageTable$reloadData$Section$Add)
6513 [sections addObject:section];
6517 [section addToCount];
6523 index_ = [NSMutableArray arrayWithCapacity:32];
6525 bool sectioned([self showsSections]);
6527 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6528 [sections addObject:section];
6531 _profile(PackageTable$reloadData$Section)
6532 for (size_t offset(0), end([packages count]); offset != end; ++offset) {
6536 _profile(PackageTable$reloadData$Section$Package)
6537 package = [packages objectAtIndex:offset];
6538 index = [package index];
6541 if (sectioned && (section == nil || [section index] != index)) {
6542 _profile(PackageTable$reloadData$Section$Allocate)
6543 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6546 [index_ addObject:[section name]];
6548 _profile(PackageTable$reloadData$Section$Add)
6549 [sections addObject:section];
6553 [section addToCount];
6561 - (void) reloadData {
6564 if ([self shouldYield])
6565 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6570 - (void) resetCursor {
6571 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6574 - (void) clearData {
6575 [self updateHeight];
6577 [list_ setDataSource:nil];
6585 /* Filtered Package List Controller {{{ */
6586 typedef Function<bool, Package *> PackageFilter;
6587 typedef Function<void, NSMutableArray *> PackageSorter;
6588 @interface FilteredPackageListController : PackageListController {
6589 PackageFilter filter_;
6590 PackageSorter sorter_;
6593 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6595 - (void) setFilter:(PackageFilter)filter;
6596 - (void) setSorter:(PackageSorter)sorter;
6600 @implementation FilteredPackageListController
6602 - (void) setFilter:(PackageFilter)filter {
6603 @synchronized (self) {
6607 - (void) setSorter:(PackageSorter)sorter {
6608 @synchronized (self) {
6612 - (NSMutableArray *) _reloadPackages {
6613 @synchronized (database_) {
6614 era_ = [database_ era];
6616 NSArray *packages([database_ packages]);
6617 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6619 PackageFilter filter;
6620 PackageSorter sorter;
6622 @synchronized (self) {
6627 _profile(PackageTable$reloadData$Filter)
6628 for (Package *package in packages)
6629 if ([package valid] && filter(package))
6630 [filtered addObject:package];
6638 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6639 if ((self = [super initWithDatabase:database title:title]) != nil) {
6640 [self setFilter:filter];
6647 /* Home Controller {{{ */
6648 @interface HomeController : CydiaWebViewController {
6649 CFRunLoopRef runloop_;
6650 SCNetworkReachabilityRef reachability_;
6655 @implementation HomeController
6657 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6658 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6662 if ((self = [super init]) != nil) {
6663 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6666 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6667 if (reachability_ != NULL) {
6668 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6669 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6671 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6672 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6679 if (reachability_ != NULL && runloop_ != NULL)
6680 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6684 - (NSURL *) navigationURL {
6685 return [NSURL URLWithString:@"cydia://home"];
6688 - (void) aboutButtonClicked {
6689 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6691 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6692 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6693 [alert setCancelButtonIndex:0];
6696 @"Copyright \u00a9 2008-2013\n"
6699 "Jay Freeman (saurik)\n"
6700 "saurik@saurik.com\n"
6701 "http://www.saurik.com/"
6707 - (UIBarButtonItem *) leftButton {
6708 return [[[UIBarButtonItem alloc]
6709 initWithTitle:UCLocalize("ABOUT")
6710 style:UIBarButtonItemStylePlain
6712 action:@selector(aboutButtonClicked)
6719 /* Cydia Navigation Controller Interface {{{ */
6720 @interface UINavigationController (Cydia)
6722 - (NSArray *) navigationURLCollection;
6723 - (void) unloadData;
6728 /* Cydia Tab Bar Controller {{{ */
6729 @interface CydiaTabBarController : CyteTabBarController <
6730 UITabBarControllerDelegate,
6733 _transient Database *database_;
6735 _H<UIActivityIndicatorView> indicator_;
6738 // XXX: ok, "updatedelegate_"?...
6739 _transient NSObject<CydiaDelegate> *updatedelegate_;
6742 - (NSArray *) navigationURLCollection;
6743 - (void) beginUpdate;
6748 @implementation CydiaTabBarController
6750 - (NSArray *) navigationURLCollection {
6751 NSMutableArray *items([NSMutableArray array]);
6753 // XXX: Should this deal with transient view controllers?
6754 for (id navigation in [self viewControllers]) {
6755 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6757 [items addObject:stack];
6763 - (id) initWithDatabase:(Database *)database {
6764 if ((self = [super init]) != nil) {
6765 database_ = database;
6766 [self setDelegate:self];
6768 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6769 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6771 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6775 - (void) setUpdate:(NSDate *)date {
6779 - (void) beginUpdate {
6783 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6784 UITabBarItem *item([controller tabBarItem]);
6786 [item setBadgeValue:@""];
6787 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6789 [indicator_ startAnimating];
6790 [badge addSubview:indicator_];
6792 [updatedelegate_ retainNetworkActivityIndicator];
6796 detachNewThreadSelector:@selector(performUpdate)
6802 - (void) performUpdate {
6803 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6805 SourceStatus status(self, database_);
6806 [database_ updateWithStatus:status];
6809 performSelectorOnMainThread:@selector(completeUpdate)
6817 - (void) stopUpdateWithSelector:(SEL)selector {
6819 [updatedelegate_ releaseNetworkActivityIndicator];
6821 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6822 [[controller tabBarItem] setBadgeValue:nil];
6824 [indicator_ removeFromSuperview];
6825 [indicator_ stopAnimating];
6827 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6830 - (void) completeUpdate {
6833 [self stopUpdateWithSelector:@selector(reloadData)];
6836 - (void) cancelUpdate {
6837 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
6840 - (void) cancelPressed {
6841 [self cancelUpdate];
6848 - (bool) isSourceCancelled {
6852 - (void) startSourceFetch:(NSString *)uri {
6855 - (void) stopSourceFetch:(NSString *)uri {
6858 - (void) setUpdateDelegate:(id)delegate {
6859 updatedelegate_ = delegate;
6862 - (UIView *) transitionView {
6863 if (![self respondsToSelector:@selector(_transitionView)])
6864 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6865 else if (kCFCoreFoundationVersionNumber < 800)
6866 return [self _transitionView];
6868 return [[[self _transitionView] superview] superview];
6874 /* Cydia Navigation Controller Implementation {{{ */
6875 @implementation UINavigationController (Cydia)
6877 - (NSArray *) navigationURLCollection {
6878 NSMutableArray *stack([NSMutableArray array]);
6880 for (CyteViewController *controller in [self viewControllers]) {
6881 NSString *url = [[controller navigationURL] absoluteString];
6883 [stack addObject:url];
6889 - (void) reloadData {
6892 UIViewController *visible([self visibleViewController]);
6894 [visible reloadData];
6896 // on the iPad, this view controller is ALSO visible. :(
6898 if (UIViewController *top = [self topViewController])
6903 - (void) unloadData {
6904 for (CyteViewController *page in [self viewControllers])
6913 /* Cydia:// Protocol {{{ */
6914 @interface CydiaURLProtocol : NSURLProtocol {
6919 @implementation CydiaURLProtocol
6921 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6922 NSURL *url([request URL]);
6926 NSString *scheme([[url scheme] lowercaseString]);
6927 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6929 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6935 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6939 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6940 id<NSURLProtocolClient> client([self client]);
6942 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6944 NSData *data(UIImagePNGRepresentation(icon));
6946 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6947 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6948 [client URLProtocol:self didLoadData:data];
6949 [client URLProtocolDidFinishLoading:self];
6953 - (void) startLoading {
6954 id<NSURLProtocolClient> client([self client]);
6955 NSURLRequest *request([self request]);
6957 NSURL *url([request URL]);
6958 NSString *href([url absoluteString]);
6959 NSString *scheme([[url scheme] lowercaseString]);
6963 if ([scheme isEqualToString:@"cydia"])
6964 path = [href substringFromIndex:8];
6965 else if ([scheme isEqualToString:@"about"])
6966 path = [href substringFromIndex:12];
6967 else _assert(false);
6969 NSRange slash([path rangeOfString:@"/"]);
6972 if (slash.location == NSNotFound) {
6976 command = [path substringToIndex:slash.location];
6977 path = [path substringFromIndex:(slash.location + 1)];
6980 Database *database([Database sharedInstance]);
6982 if ([command isEqualToString:@"package-icon"]) {
6985 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6986 Package *package([database packageWithName:path]);
6990 UIImage *icon([package icon]);
6991 [self _returnPNGWithImage:icon forRequest:request];
6992 } else if ([command isEqualToString:@"uikit-image"]) {
6995 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6996 UIImage *icon(_UIImageWithName(path));
6997 [self _returnPNGWithImage:icon forRequest:request];
6998 } else if ([command isEqualToString:@"section-icon"]) {
7001 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7002 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7004 icon = [UIImage applicationImageNamed:@"unknown.png"];
7005 [self _returnPNGWithImage:icon forRequest:request];
7007 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7011 - (void) stopLoading {
7017 /* Section Controller {{{ */
7018 @interface SectionController : FilteredPackageListController {
7020 _H<NSString> section_;
7023 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7027 @implementation SectionController
7029 - (NSURL *) referrerURL {
7030 NSString *name(section_);
7031 name = name ?: @"*";
7032 NSString *key(key_);
7034 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7037 - (NSURL *) navigationURL {
7038 NSString *name(section_);
7039 name = name ?: @"*";
7040 NSString *key(key_);
7042 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7045 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7048 title = UCLocalize("ALL_PACKAGES");
7049 else if (![section isEqual:@""])
7050 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7052 title = UCLocalize("NO_SECTION");
7054 if ((self = [super initWithDatabase:database title:title]) != nil) {
7055 key_ = [source key];
7060 - (void) reloadData {
7061 Source *source([database_ sourceWithKey:key_]);
7062 _H<NSString> name(section_);
7064 [self setFilter:[=](Package *package) {
7065 NSString *section([package section]);
7069 section == nil && [name length] == 0 ||
7070 [name isEqualToString:section]
7073 [package source] == source
7074 ) && [package visible];
7082 /* Sections Controller {{{ */
7083 @interface SectionsController : CyteViewController <
7084 UITableViewDataSource,
7087 _transient Database *database_;
7089 _H<NSMutableArray> sections_;
7090 _H<NSMutableArray> filtered_;
7091 _H<UITableView, 2> list_;
7094 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7095 - (void) editButtonClicked;
7099 @implementation SectionsController
7101 - (NSURL *) navigationURL {
7102 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7105 - (Source *) source {
7108 return [database_ sourceWithKey:key_];
7111 - (void) updateNavigationItem {
7112 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7113 if ([sections_ count] == 0) {
7114 [[self navigationItem] setRightBarButtonItem:nil];
7116 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7117 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7119 action:@selector(editButtonClicked)
7120 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7124 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7125 [super setEditing:editing animated:animated];
7130 [delegate_ updateData];
7132 [self updateNavigationItem];
7135 - (void) viewDidAppear:(BOOL)animated {
7136 [super viewDidAppear:animated];
7137 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7140 - (void) viewWillDisappear:(BOOL)animated {
7141 [super viewWillDisappear:animated];
7142 [self setEditing:NO];
7145 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7146 Section *section = nil;
7147 int index = [indexPath row];
7148 if (![self isEditing]) {
7151 section = [filtered_ objectAtIndex:index];
7153 section = [sections_ objectAtIndex:index];
7158 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7159 if ([self isEditing])
7160 return [sections_ count];
7162 return [filtered_ count] + 1;
7165 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7169 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7170 static NSString *reuseIdentifier = @"SectionCell";
7172 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7174 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7176 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7181 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7182 if ([self isEditing])
7185 Section *section = [self sectionAtIndexPath:indexPath];
7187 SectionController *controller = [[[SectionController alloc]
7188 initWithDatabase:database_
7189 source:[self source]
7190 section:[section name]
7192 [controller setDelegate:delegate_];
7194 [[self navigationController] pushViewController:controller animated:YES];
7198 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7199 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7200 [list_ setRowHeight:46];
7201 [(UITableView *) list_ setDataSource:self];
7202 [list_ setDelegate:self];
7203 [self setView:list_];
7206 - (void) viewDidLoad {
7207 [super viewDidLoad];
7209 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7212 - (void) releaseSubviews {
7218 [super releaseSubviews];
7221 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7222 if ((self = [super init]) != nil) {
7223 database_ = database;
7224 key_ = [source key];
7228 - (void) reloadData {
7231 NSArray *packages = [database_ packages];
7233 sections_ = [NSMutableArray arrayWithCapacity:16];
7234 filtered_ = [NSMutableArray arrayWithCapacity:16];
7236 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7238 Source *source([self source]);
7241 for (Package *package in packages) {
7242 if (source != nil && [package source] != source)
7245 NSString *name([package section]);
7246 NSString *key(name == nil ? @"" : name);
7250 _profile(SectionsView$reloadData$Section)
7251 section = [sections objectForKey:key];
7252 if (section == nil) {
7253 _profile(SectionsView$reloadData$Section$Allocate)
7254 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7255 [sections setObject:section forKey:key];
7260 [section addToCount];
7262 _profile(SectionsView$reloadData$Filter)
7263 if (![package valid] || ![package visible])
7271 [sections_ addObjectsFromArray:[sections allValues]];
7273 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7275 for (Section *section in (id) sections_) {
7276 size_t count([section row]);
7280 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7281 [section setCount:count];
7282 [filtered_ addObject:section];
7285 [self updateNavigationItem];
7290 - (void) editButtonClicked {
7291 [self setEditing:![self isEditing] animated:YES];
7297 /* Changes Controller {{{ */
7298 @interface ChangesController : FilteredPackageListController {
7302 - (id) initWithDatabase:(Database *)database;
7306 @implementation ChangesController
7308 - (NSURL *) referrerURL {
7309 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7312 - (NSURL *) navigationURL {
7313 return [NSURL URLWithString:@"cydia://changes"];
7316 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7317 @synchronized (database_) {
7318 if ([database_ era] != era_)
7321 NSUInteger sectionIndex([path section]);
7322 if (sectionIndex >= [sections_ count])
7324 Section *section([sections_ objectAtIndex:sectionIndex]);
7325 NSInteger row([path row]);
7326 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7329 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7330 NSString *context([alert context]);
7332 if ([context isEqualToString:@"norefresh"])
7333 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7336 - (void) setLeftBarButtonItem {
7337 if ([delegate_ updating])
7338 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7339 initWithTitle:UCLocalize("CANCEL")
7340 style:UIBarButtonItemStyleDone
7342 action:@selector(cancelButtonClicked)
7343 ] autorelease] animated:YES];
7345 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7346 initWithTitle:UCLocalize("REFRESH")
7347 style:UIBarButtonItemStylePlain
7349 action:@selector(refreshButtonClicked)
7350 ] autorelease] animated:YES];
7353 - (void) refreshButtonClicked {
7354 if ([delegate_ requestUpdate])
7355 [self setLeftBarButtonItem];
7358 - (void) cancelButtonClicked {
7359 [delegate_ cancelUpdate];
7362 - (void) upgradeButtonClicked {
7363 [delegate_ distUpgrade];
7364 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7367 - (bool) shouldYield {
7371 - (bool) shouldBlock {
7375 - (void) useFilter {
7376 @synchronized (self) {
7377 [self setFilter:[](Package *package) {
7378 return [package upgradableAndEssential:YES] || [package visible];
7381 [self setSorter:[](NSMutableArray *packages) {
7382 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7386 - (id) initWithDatabase:(Database *)database {
7387 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7392 - (void) reloadData {
7393 [self setLeftBarButtonItem];
7397 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7398 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7400 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7401 Section *ignored = nil;
7402 Section *section = nil;
7406 bool unseens = false;
7408 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7410 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7411 Package *package = [packages objectAtIndex:offset];
7413 BOOL uae = [package upgradableAndEssential:YES];
7417 time_t seen([package seen]);
7419 if (section == nil || last != seen) {
7423 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7426 _profile(ChangesController$reloadData$Allocate)
7427 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7428 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7429 [sections addObject:section];
7433 [section addToCount];
7434 } else if ([package ignored]) {
7435 if (ignored == nil) {
7436 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7438 [ignored addToCount];
7441 [upgradable addToCount];
7446 CFRelease(formatter);
7449 Section *last = [sections lastObject];
7450 size_t count = [last count];
7451 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7452 [sections removeLastObject];
7455 if ([ignored count] != 0)
7456 [sections insertObject:ignored atIndex:0];
7458 [sections insertObject:upgradable atIndex:0];
7462 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7463 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7464 style:UIBarButtonItemStylePlain
7466 action:@selector(upgradeButtonClicked)
7467 ] autorelease]) animated:YES];
7475 /* Search Controller {{{ */
7476 @interface SearchController : FilteredPackageListController <
7479 _H<UISearchBar, 1> search_;
7484 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7485 - (void) reloadData;
7489 @implementation SearchController
7491 - (NSURL *) referrerURL {
7492 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7495 - (NSURL *) navigationURL {
7496 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7497 return [NSURL URLWithString:@"cydia://search"];
7499 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7502 - (NSArray *) termsForQuery:(NSString *)query {
7503 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7504 for (NSString *component in [query componentsSeparatedByString:@" "])
7505 if ([component length] != 0)
7506 [terms addObject:component];
7511 - (void) useSearch {
7512 _H<NSArray> query([self termsForQuery:[search_ text]]);
7515 @synchronized (self) {
7516 [self setFilter:[=](Package *package) {
7517 if (![package unfiltered])
7519 if (![package matches:query])
7524 [self setSorter:[](NSMutableArray *packages) {
7525 [packages radixSortUsingSelector:@selector(rank)];
7533 - (void) usePrefix:(NSString *)prefix {
7534 _H<NSString> query(prefix);
7537 @synchronized (self) {
7538 [self setFilter:[=](Package *package) {
7539 if ([query length] == 0)
7541 if (![package unfiltered])
7543 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7548 [self setSorter:nullptr];
7554 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7556 [self usePrefix:[search_ text]];
7559 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7560 [search_ resignFirstResponder];
7564 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7565 [search_ setText:@""];
7566 [self searchBarButtonClicked:searchBar];
7569 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7570 [self searchBarButtonClicked:searchBar];
7573 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7574 [self usePrefix:text];
7577 - (bool) shouldYield {
7581 - (bool) shouldBlock {
7585 - (bool) isSummarized {
7589 - (bool) showsSections {
7593 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7594 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7595 search_ = [[[UISearchBar alloc] init] autorelease];
7596 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7597 [search_ setDelegate:self];
7599 UITextField *textField;
7600 if ([search_ respondsToSelector:@selector(searchField)])
7601 textField = [search_ searchField];
7603 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7605 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7606 [textField setEnablesReturnKeyAutomatically:NO];
7607 [[self navigationItem] setTitleView:textField];
7610 [search_ setText:query];
7615 - (void) viewDidAppear:(BOOL)animated {
7616 [super viewDidAppear:animated];
7618 if (!searchloaded_) {
7619 searchloaded_ = YES;
7620 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7621 [search_ layoutSubviews];
7624 if ([self isSummarized])
7625 [search_ becomeFirstResponder];
7628 - (void) reloadData {
7633 - (void) didSelectPackage:(Package *)package {
7634 [search_ resignFirstResponder];
7635 [super didSelectPackage:package];
7640 /* Package Settings Controller {{{ */
7641 @interface PackageSettingsController : CyteViewController <
7642 UITableViewDataSource,
7645 _transient Database *database_;
7647 _H<Package> package_;
7648 _H<UITableView, 2> table_;
7649 _H<UISwitch> subscribedSwitch_;
7650 _H<UISwitch> ignoredSwitch_;
7651 _H<UITableViewCell> subscribedCell_;
7652 _H<UITableViewCell> ignoredCell_;
7655 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7659 @implementation PackageSettingsController
7661 - (NSURL *) navigationURL {
7662 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7665 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7666 if (package_ == nil)
7669 if ([package_ installed] == nil)
7675 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7676 if (package_ == nil)
7679 // both sections contain just one item right now.
7683 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7687 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7689 return UCLocalize("SHOW_ALL_CHANGES_EX");
7691 return UCLocalize("IGNORE_UPGRADES_EX");
7694 - (void) onSubscribed:(id)control {
7695 bool value([control isOn]);
7696 if (package_ == nil)
7698 if ([package_ setSubscribed:value])
7699 [delegate_ updateData];
7702 - (void) _updateIgnored {
7703 const char *package([name_ UTF8String]);
7704 bool on([ignoredSwitch_ isOn]);
7706 pid_t pid(ExecFork());
7708 FILE *dpkg(popen("dpkg --set-selections", "w"));
7709 fwrite(package, strlen(package), 1, dpkg);
7712 fwrite(" hold\n", 6, 1, dpkg);
7714 fwrite(" install\n", 9, 1, dpkg);
7722 - (void) onIgnored:(id)control {
7723 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7724 [invocation setTarget:self];
7725 [invocation setSelector:@selector(_updateIgnored)];
7727 [delegate_ reloadDataWithInvocation:invocation];
7730 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7731 if (package_ == nil)
7734 switch ([indexPath section]) {
7735 case 0: return subscribedCell_;
7736 case 1: return ignoredCell_;
7745 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7746 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7747 [self setView:view];
7749 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7750 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7751 [(UITableView *) table_ setDataSource:self];
7752 [table_ setDelegate:self];
7753 [view addSubview:table_];
7755 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7756 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7757 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7759 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7760 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7761 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7763 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7764 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7765 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7766 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7768 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7769 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7770 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7771 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7774 - (void) viewDidLoad {
7775 [super viewDidLoad];
7777 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7780 - (void) releaseSubviews {
7782 subscribedCell_ = nil;
7784 ignoredSwitch_ = nil;
7785 subscribedSwitch_ = nil;
7787 [super releaseSubviews];
7790 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7791 if ((self = [super init]) != nil) {
7792 database_ = database;
7797 - (void) reloadData {
7800 package_ = [database_ packageWithName:name_];
7802 if (package_ != nil) {
7803 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7804 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7805 } // XXX: what now, G?
7807 [table_ reloadData];
7813 /* Installed Controller {{{ */
7814 @interface InstalledController : FilteredPackageListController {
7818 - (id) initWithDatabase:(Database *)database;
7819 - (void) queueStatusDidChange;
7823 @implementation InstalledController
7825 - (NSURL *) referrerURL {
7826 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
7829 - (NSURL *) navigationURL {
7830 return [NSURL URLWithString:@"cydia://installed"];
7833 - (bool) showsSections {
7837 - (void) useUpdated {
7840 @synchronized (self) {
7841 [self setFilter:[](Package *package) {
7842 return ![package uninstalled] && package->role_ < 7;
7845 [self setSorter:[](NSMutableArray *packages) {
7846 [packages radixSortUsingSelector:@selector(updated)];
7850 - (void) useFilter:(UISegmentedControl *)segmented {
7851 NSInteger selected([segmented selectedSegmentIndex]);
7853 return [self useUpdated];
7854 bool simple(selected == 0);
7857 @synchronized (self) {
7858 [self setFilter:[=](Package *package) {
7859 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
7862 [self setSorter:nullptr];
7865 - (id) initWithDatabase:(Database *)database {
7866 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
7867 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
7868 [segmented setSelectedSegmentIndex:0];
7869 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
7870 [[self navigationItem] setTitleView:segmented];
7872 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
7873 [self useFilter:segmented];
7875 [self queueStatusDidChange];
7880 - (void) queueButtonClicked {
7885 - (void) queueStatusDidChange {
7888 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7889 initWithTitle:UCLocalize("QUEUE")
7890 style:UIBarButtonItemStyleDone
7892 action:@selector(queueButtonClicked)
7895 [[self navigationItem] setLeftBarButtonItem:nil];
7900 - (void) modeChanged:(UISegmentedControl *)segmented {
7901 [self useFilter:segmented];
7908 /* Source Cell {{{ */
7909 @interface SourceCell : CyteTableViewCell <
7910 CyteTableViewCellDelegate,
7913 _H<Source, 1> source_;
7916 _H<NSString> origin_;
7917 _H<NSString> label_;
7918 _H<UIActivityIndicatorView> indicator_;
7921 - (void) setSource:(Source *)source;
7922 - (void) setFetch:(NSNumber *)fetch;
7926 @implementation SourceCell
7928 - (void) _setImage:(NSArray *)data {
7929 if ([url_ isEqual:[data objectAtIndex:0]]) {
7930 icon_ = [data objectAtIndex:1];
7931 [content_ setNeedsDisplay];
7935 - (void) _setSource:(NSURL *) url {
7936 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7938 if (NSData *data = [NSURLConnection
7939 sendSynchronousRequest:[NSURLRequest
7941 cachePolicy:NSURLRequestUseProtocolCachePolicy
7945 returningResponse:NULL
7948 if (UIImage *image = [UIImage imageWithData:data])
7949 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
7954 - (void) setSource:(Source *)source {
7956 [source_ setDelegate:self];
7958 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
7960 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7962 origin_ = [source name];
7963 label_ = [source rooturi];
7965 [content_ setNeedsDisplay];
7967 url_ = [source iconURL];
7968 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
7971 - (void) setAllSource {
7973 [indicator_ stopAnimating];
7975 icon_ = [UIImage applicationImageNamed:@"folder.png"];
7976 origin_ = UCLocalize("ALL_SOURCES");
7977 label_ = UCLocalize("ALL_SOURCES_EX");
7978 [content_ setNeedsDisplay];
7981 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7982 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7983 UIView *content([self contentView]);
7984 CGRect bounds([content bounds]);
7986 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7987 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7988 [content_ setBackgroundColor:[UIColor whiteColor]];
7989 [content addSubview:content_];
7991 [content_ setDelegate:self];
7992 [content_ setOpaque:YES];
7994 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
7995 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
7996 [content addSubview:indicator_];
7998 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8002 - (void) layoutSubviews {
8003 [super layoutSubviews];
8005 UIView *content([self contentView]);
8006 CGRect bounds([content bounds]);
8008 CGRect frame([indicator_ frame]);
8009 frame.origin.x = bounds.size.width - frame.size.width;
8010 frame.origin.y = (bounds.size.height - frame.size.height) / 2;
8012 if (kCFCoreFoundationVersionNumber < 800)
8013 frame.origin.x -= 8;
8014 [indicator_ setFrame:frame];
8017 - (NSString *) accessibilityLabel {
8021 - (void) drawContentRect:(CGRect)rect {
8022 bool highlighted(highlighted_);
8023 float width(rect.size.width);
8027 rect.size = [(UIImage *) icon_ size];
8029 while (rect.size.width > 32 || rect.size.height > 32) {
8030 rect.size.width /= 2;
8031 rect.size.height /= 2;
8034 rect.origin.x = 26 - rect.size.width / 2;
8035 rect.origin.y = 26 - rect.size.height / 2;
8037 [icon_ drawInRect:rect];
8040 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8045 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 61) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8049 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 61) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8052 - (void) setFetch:(NSNumber *)fetch {
8053 if ([fetch boolValue])
8054 [indicator_ startAnimating];
8056 [indicator_ stopAnimating];
8061 /* Sources Controller {{{ */
8062 @interface SourcesController : CyteViewController <
8063 UITableViewDataSource,
8066 _transient Database *database_;
8069 _H<UITableView, 2> list_;
8070 _H<NSMutableArray> sources_;
8074 _H<UIProgressHUD> hud_;
8077 NSURLConnection *trivial_bz2_;
8078 NSURLConnection *trivial_gz_;
8083 - (id) initWithDatabase:(Database *)database;
8084 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8088 @implementation SourcesController
8090 - (void) _releaseConnection:(NSURLConnection *)connection {
8091 if (connection != nil) {
8092 [connection cancel];
8093 //[connection setDelegate:nil];
8094 [connection release];
8099 [self _releaseConnection:trivial_gz_];
8100 [self _releaseConnection:trivial_bz2_];
8105 - (NSURL *) navigationURL {
8106 return [NSURL URLWithString:@"cydia://sources"];
8109 - (void) viewDidAppear:(BOOL)animated {
8110 [super viewDidAppear:animated];
8111 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8114 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8118 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8120 return UCLocalize("INDIVIDUAL_SOURCES");
8124 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8127 case 1: return [sources_ count];
8132 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8133 @synchronized (database_) {
8134 if ([database_ era] != era_)
8136 if ([indexPath section] != 1)
8138 NSUInteger index([indexPath row]);
8139 if (index >= [sources_ count])
8141 return [sources_ objectAtIndex:index];
8144 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8145 static NSString *cellIdentifier = @"SourceCell";
8147 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8148 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8149 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8151 Source *source([self sourceAtIndexPath:indexPath]);
8153 [cell setAllSource];
8155 [cell setSource:source];
8160 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8161 SectionsController *controller([[[SectionsController alloc]
8162 initWithDatabase:database_
8163 source:[self sourceAtIndexPath:indexPath]
8166 [controller setDelegate:delegate_];
8167 [[self navigationController] pushViewController:controller animated:YES];
8170 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8171 if ([indexPath section] != 1)
8173 Source *source = [self sourceAtIndexPath:indexPath];
8174 return [source record] != nil;
8177 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8178 _assert([indexPath section] == 1);
8179 if (editingStyle == UITableViewCellEditingStyleDelete) {
8180 Source *source = [self sourceAtIndexPath:indexPath];
8181 if (source == nil) return;
8183 [Sources_ removeObjectForKey:[source key]];
8186 [delegate_ _saveConfig];
8187 [delegate_ reloadDataWithInvocation:nil];
8191 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8192 [self updateButtonsForEditingStatusAnimated:YES];
8196 [delegate_ addTrivialSource:href_];
8199 [delegate_ syncData];
8202 - (NSString *) getWarning {
8203 NSString *href(href_);
8204 NSRange colon([href rangeOfString:@"://"]);
8205 if (colon.location != NSNotFound)
8206 href = [href substringFromIndex:(colon.location + 3)];
8207 href = [href stringByAddingPercentEscapes];
8208 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8210 NSURL *url([NSURL URLWithString:href]);
8212 NSStringEncoding encoding;
8213 NSError *error(nil);
8215 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8216 return [warning length] == 0 ? nil : warning;
8220 - (void) _endConnection:(NSURLConnection *)connection {
8221 // XXX: the memory management in this method is horribly awkward
8223 NSURLConnection **field = NULL;
8224 if (connection == trivial_bz2_)
8225 field = &trivial_bz2_;
8226 else if (connection == trivial_gz_)
8227 field = &trivial_gz_;
8228 _assert(field != NULL);
8229 [connection release];
8233 trivial_bz2_ == nil &&
8236 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8238 [delegate_ releaseNetworkActivityIndicator];
8240 [delegate_ removeProgressHUD:hud_];
8244 if (warning != nil) {
8245 UIAlertView *alert = [[[UIAlertView alloc]
8246 initWithTitle:UCLocalize("SOURCE_WARNING")
8249 cancelButtonTitle:UCLocalize("CANCEL")
8251 UCLocalize("ADD_ANYWAY"),
8255 [alert setContext:@"warning"];
8256 [alert setNumberOfRows:1];
8259 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8265 } else if (error_ != nil) {
8266 UIAlertView *alert = [[[UIAlertView alloc]
8267 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8268 message:[error_ localizedDescription]
8270 cancelButtonTitle:UCLocalize("OK")
8271 otherButtonTitles:nil
8274 [alert setContext:@"urlerror"];
8279 UIAlertView *alert = [[[UIAlertView alloc]
8280 initWithTitle:UCLocalize("NOT_REPOSITORY")
8281 message:UCLocalize("NOT_REPOSITORY_EX")
8283 cancelButtonTitle:UCLocalize("OK")
8284 otherButtonTitles:nil
8287 [alert setContext:@"trivial"];
8297 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8298 switch ([response statusCode]) {
8304 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8305 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8307 [self _endConnection:connection];
8310 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8311 [self _endConnection:connection];
8314 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8315 NSURL *url([NSURL URLWithString:href]);
8317 NSMutableURLRequest *request = [NSMutableURLRequest
8319 cachePolicy:NSURLRequestUseProtocolCachePolicy
8323 [request setHTTPMethod:method];
8325 if (Machine_ != NULL)
8326 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8328 if (UniqueID_ != nil)
8329 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8331 if ([url isCydiaSecure]) {
8332 if (UniqueID_ != nil)
8333 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8336 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8339 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8340 NSString *context([alert context]);
8342 if ([context isEqualToString:@"source"]) {
8345 NSString *href = [[alert textField] text];
8347 static Pcre href_r("^http(s?)://[^# ]*$");
8348 if (!href_r(href)) {
8349 UIAlertView *alert = [[[UIAlertView alloc]
8350 initWithTitle:Error_
8351 message:UCLocalize("INVALID_URL")
8353 cancelButtonTitle:UCLocalize("OK")
8354 otherButtonTitles:nil
8357 [alert setContext:@"badurl"];
8363 if (![href hasSuffix:@"/"])
8364 href_ = [href stringByAppendingString:@"/"];
8368 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8369 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8373 // XXX: this is stupid
8374 hud_ = [delegate_ addProgressHUD];
8375 [hud_ setText:UCLocalize("VERIFYING_URL")];
8376 [delegate_ retainNetworkActivityIndicator];
8385 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8386 } else if ([context isEqualToString:@"trivial"])
8387 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8388 else if ([context isEqualToString:@"urlerror"])
8389 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8390 else if ([context isEqualToString:@"warning"]) {
8393 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8402 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8406 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8407 BOOL editing([list_ isEditing]);
8410 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8411 initWithTitle:UCLocalize("ADD")
8412 style:UIBarButtonItemStylePlain
8414 action:@selector(addButtonClicked)
8415 ] autorelease] animated:animated];
8416 else if ([delegate_ updating])
8417 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8418 initWithTitle:UCLocalize("CANCEL")
8419 style:UIBarButtonItemStyleDone
8421 action:@selector(cancelButtonClicked)
8422 ] autorelease] animated:animated];
8424 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8425 initWithTitle:UCLocalize("REFRESH")
8426 style:UIBarButtonItemStylePlain
8428 action:@selector(refreshButtonClicked)
8429 ] autorelease] animated:animated];
8431 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8432 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8433 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8435 action:@selector(editButtonClicked)
8436 ] autorelease] animated:animated];
8440 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8441 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8442 [list_ setRowHeight:53];
8443 [(UITableView *) list_ setDataSource:self];
8444 [list_ setDelegate:self];
8445 [self setView:list_];
8448 - (void) viewDidLoad {
8449 [super viewDidLoad];
8451 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8452 [self updateButtonsForEditingStatusAnimated:NO];
8455 - (void) viewWillAppear:(BOOL)animated {
8456 [super viewWillAppear:animated];
8458 [list_ setEditing:NO];
8459 [self updateButtonsForEditingStatusAnimated:NO];
8462 - (void) releaseSubviews {
8467 [super releaseSubviews];
8470 - (id) initWithDatabase:(Database *)database {
8471 if ((self = [super init]) != nil) {
8472 database_ = database;
8476 - (void) reloadData {
8478 [self updateButtonsForEditingStatusAnimated:YES];
8480 @synchronized (database_) {
8481 era_ = [database_ era];
8483 sources_ = [NSMutableArray arrayWithCapacity:16];
8484 [sources_ addObjectsFromArray:[database_ sources]];
8486 [sources_ sortUsingSelector:@selector(compareByName:)];
8489 int count([sources_ count]);
8491 for (int i = 0; i != count; i++) {
8492 if ([[sources_ objectAtIndex:i] record] == nil)
8500 - (void) showAddSourcePrompt {
8501 UIAlertView *alert = [[[UIAlertView alloc]
8502 initWithTitle:UCLocalize("ENTER_APT_URL")
8505 cancelButtonTitle:UCLocalize("CANCEL")
8507 UCLocalize("ADD_SOURCE"),
8511 [alert setContext:@"source"];
8513 [alert setNumberOfRows:1];
8514 [alert addTextFieldWithValue:@"http://" label:@""];
8516 UITextInputTraits *traits = [[alert textField] textInputTraits];
8517 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8518 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8519 [traits setKeyboardType:UIKeyboardTypeURL];
8520 // XXX: UIReturnKeyDone
8521 [traits setReturnKeyType:UIReturnKeyNext];
8526 - (void) addButtonClicked {
8527 [self showAddSourcePrompt];
8530 - (void) refreshButtonClicked {
8531 if ([delegate_ requestUpdate])
8532 [self updateButtonsForEditingStatusAnimated:YES];
8535 - (void) cancelButtonClicked {
8536 [delegate_ cancelUpdate];
8539 - (void) editButtonClicked {
8540 [list_ setEditing:![list_ isEditing] animated:YES];
8541 [self updateButtonsForEditingStatusAnimated:YES];
8547 /* Stash Controller {{{ */
8548 @interface StashController : CyteViewController {
8549 _H<UIActivityIndicatorView> spinner_;
8550 _H<UILabel> status_;
8551 _H<UILabel> caption_;
8556 @implementation StashController
8559 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8560 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8561 [self setView:view];
8563 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8565 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8566 CGRect spinrect = [spinner_ frame];
8567 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8568 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8569 [spinner_ setFrame:spinrect];
8570 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8571 [view addSubview:spinner_];
8572 [spinner_ startAnimating];
8575 captrect.size.width = [[self view] frame].size.width;
8576 captrect.size.height = 40.0f;
8577 captrect.origin.x = 0;
8578 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8579 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8580 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8581 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8582 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8583 [caption_ setTextColor:[UIColor whiteColor]];
8584 [caption_ setBackgroundColor:[UIColor clearColor]];
8585 [caption_ setShadowColor:[UIColor blackColor]];
8586 [caption_ setTextAlignment:NSTextAlignmentCenter];
8587 [view addSubview:caption_];
8590 statusrect.size.width = [[self view] frame].size.width;
8591 statusrect.size.height = 30.0f;
8592 statusrect.origin.x = 0;
8593 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8594 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8595 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8596 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8597 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8598 [status_ setTextColor:[UIColor whiteColor]];
8599 [status_ setBackgroundColor:[UIColor clearColor]];
8600 [status_ setShadowColor:[UIColor blackColor]];
8601 [status_ setTextAlignment:NSTextAlignmentCenter];
8602 [view addSubview:status_];
8605 - (void) releaseSubviews {
8610 [super releaseSubviews];
8616 @interface CYURLCache : SDURLCache {
8621 @implementation CYURLCache
8623 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8626 else if ([event isEqualToString:@"no-cache"])
8628 else if ([event isEqualToString:@"store"])
8630 else if ([event isEqualToString:@"invalid"])
8632 else if ([event isEqualToString:@"memory"])
8634 else if ([event isEqualToString:@"disk"])
8636 else if ([event isEqualToString:@"miss"])
8639 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8643 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8644 if (NSURLResponse *response = [cached response])
8645 if (NSString *mime = [response MIMEType])
8646 if ([mime isEqualToString:@"text/cache-manifest"]) {
8647 NSURL *url([response URL]);
8650 NSLog(@"###: %@", [url absoluteString]);
8653 @synchronized (HostConfig_) {
8654 [CachedURLs_ addObject:url];
8658 [super storeCachedResponse:cached forRequest:request];
8663 @interface Cydia : UIApplication <
8664 ConfirmationControllerDelegate,
8667 UINavigationControllerDelegate,
8668 UITabBarControllerDelegate
8670 _H<UIWindow> window_;
8671 _H<CydiaTabBarController> tabbar_;
8672 _H<CydiaLoadingViewController> emulated_;
8674 _H<NSMutableArray> essential_;
8675 _H<NSMutableArray> broken_;
8677 Database *database_;
8679 _H<NSURL> starturl_;
8684 _H<StashController> stash_;
8693 @implementation Cydia
8695 - (void) lockSuspend {
8696 if (locked_++ == 0) {
8697 if ($SBSSetInterceptsMenuButtonForever != NULL)
8698 (*$SBSSetInterceptsMenuButtonForever)(true);
8700 [self setIdleTimerDisabled:YES];
8704 - (void) unlockSuspend {
8705 if (--locked_ == 0) {
8706 [self setIdleTimerDisabled:NO];
8708 if ($SBSSetInterceptsMenuButtonForever != NULL)
8709 (*$SBSSetInterceptsMenuButtonForever)(false);
8713 - (void) beginUpdate {
8714 [tabbar_ beginUpdate];
8717 - (void) cancelUpdate {
8718 [tabbar_ cancelUpdate];
8721 - (bool) requestUpdate {
8722 if (IsReachable("cydia.saurik.com")) {
8726 UIAlertView *alert = [[[UIAlertView alloc]
8727 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8728 message:@"Host Unreachable" // XXX: Localize
8730 cancelButtonTitle:UCLocalize("OK")
8731 otherButtonTitles:nil
8734 [alert setContext:@"norefresh"];
8742 return [tabbar_ updating];
8746 if ([broken_ count] != 0) {
8747 int count = [broken_ count];
8749 UIAlertView *alert = [[[UIAlertView alloc]
8750 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8751 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8753 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8755 UCLocalize("TEMPORARY_IGNORE"),
8759 [alert setContext:@"fixhalf"];
8760 [alert setNumberOfRows:2];
8762 } else if (!Ignored_ && [essential_ count] != 0) {
8763 int count = [essential_ count];
8765 UIAlertView *alert = [[[UIAlertView alloc]
8766 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8767 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8769 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8771 UCLocalize("UPGRADE_ESSENTIAL"),
8772 UCLocalize("COMPLETE_UPGRADE"),
8776 [alert setContext:@"upgrade"];
8781 - (void) returnToCydia {
8785 - (void) _saveConfig {
8786 @synchronized (database_) {
8793 NSString *error(nil);
8795 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8797 NSError *error(nil);
8798 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8799 NSLog(@"failure to save metadata data: %@", error);
8804 NSLog(@"failure to serialize metadata: %@", error);
8808 CydiaWriteSources();
8811 // Navigation controller for the queuing badge.
8812 - (UINavigationController *) queueNavigationController {
8813 NSArray *controllers = [tabbar_ viewControllers];
8814 return [controllers objectAtIndex:3];
8817 - (void) unloadData {
8818 [tabbar_ unloadData];
8821 - (void) _updateData {
8825 UINavigationController *navigation = [self queueNavigationController];
8827 id queuedelegate = nil;
8828 if ([[navigation viewControllers] count] > 0)
8829 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8831 [queuedelegate queueStatusDidChange];
8832 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8835 - (void) _refreshIfPossible:(NSDate *)update {
8836 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8838 bool recently = false;
8839 if (update != nil) {
8840 NSTimeInterval interval([update timeIntervalSinceNow]);
8841 if (interval <= 0 && interval > -(15*60))
8845 // Don't automatic refresh if:
8846 // - We already refreshed recently.
8847 // - We already auto-refreshed this launch.
8848 // - Auto-refresh is disabled.
8849 // - Cydia's server is not reachable
8850 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
8851 // If we are cancelling, we need to make sure it knows it's already loaded.
8854 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8856 // We are going to load, so remember that.
8859 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8865 - (void) refreshIfPossible {
8866 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8869 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8870 @synchronized (self) {
8871 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8873 [hud setText:UCLocalize("RELOADING_DATA")];
8875 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8879 [essential_ removeAllObjects];
8880 [broken_ removeAllObjects];
8882 NSArray *packages([database_ packages]);
8883 for (Package *package in packages) {
8885 [broken_ addObject:package];
8886 if ([package upgradableAndEssential:YES] && ![package ignored]) {
8887 if ([package essential] && [package installed] != nil)
8888 [essential_ addObject:package];
8893 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8896 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8897 [changesItem setBadgeValue:badge];
8898 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8899 [self setApplicationIconBadgeNumber:changes];
8902 [changesItem setBadgeValue:nil];
8903 [changesItem setAnimatedBadge:NO];
8904 [self setApplicationIconBadgeNumber:0];
8910 [self removeProgressHUD:hud];
8913 - (void) updateData {
8917 - (void) updateDataAndLoad {
8919 if ([database_ progressDelegate] == nil)
8925 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8928 - (void) disemulate {
8929 if (emulated_ == nil)
8932 if ([window_ respondsToSelector:@selector(setRootViewController:)])
8933 [window_ setRootViewController:tabbar_];
8935 [window_ addSubview:[tabbar_ view]];
8936 [[emulated_ view] removeFromSuperview];
8940 [window_ setUserInteractionEnabled:YES];
8943 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8944 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8946 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8948 UIViewController *parent;
8949 if (emulated_ == nil)
8958 [parent presentModalViewController:navigation animated:YES];
8961 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8962 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8964 if (navigation != nil)
8965 [navigation pushViewController:progress animated:YES];
8967 [self presentModalViewController:progress force:YES];
8969 [progress invoke:invocation withTitle:title];
8973 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8974 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8977 - (void) repairWithInvocation:(NSInvocation *)invocation {
8979 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
8983 - (void) repairWithSelector:(SEL)selector {
8984 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8987 - (void) reloadData {
8988 [self reloadDataWithInvocation:nil];
8989 if ([database_ progressDelegate] == nil)
8995 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
8998 - (void) addSource:(NSDictionary *) source {
8999 CydiaAddSource(source);
9002 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9003 CydiaAddSource(href, distribution, sections);
9006 - (void) addTrivialSource:(NSString *)href {
9007 CydiaAddSource(href, @"./");
9010 - (void) updateValues {
9015 pkgProblemResolver *resolver = [database_ resolver];
9017 resolver->InstallProtect();
9018 if (!resolver->Resolve(true))
9023 // XXX: this is a really crappy way of doing this.
9024 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9025 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9026 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9027 if ([tabbar_ updating])
9028 [tabbar_ cancelUpdate];
9030 if (![database_ prepare])
9033 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9034 [page setDelegate:self];
9035 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9038 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9039 [tabbar_ presentModalViewController:confirm_ animated:YES];
9045 @synchronized (self) {
9050 - (void) clearPackage:(Package *)package {
9051 @synchronized (self) {
9058 - (void) installPackages:(NSArray *)packages {
9059 @synchronized (self) {
9060 for (Package *package in packages)
9067 - (void) installPackage:(Package *)package {
9068 @synchronized (self) {
9075 - (void) removePackage:(Package *)package {
9076 @synchronized (self) {
9083 - (void) distUpgrade {
9084 @synchronized (self) {
9085 if (![database_ upgrade])
9093 system("su -c /usr/bin/uicache mobile");
9098 UIProgressHUD *hud([self addProgressHUD]);
9099 [hud setText:UCLocalize("LOADING")];
9100 [self yieldToSelector:@selector(_uicache)];
9101 [self removeProgressHUD:hud];
9105 [database_ perform];
9106 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9107 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9110 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9113 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9114 [self unlockSuspend];
9117 - (void) retainNetworkActivityIndicator {
9118 if (activity_++ == 0)
9119 [self setNetworkActivityIndicatorVisible:YES];
9122 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9126 - (void) releaseNetworkActivityIndicator {
9127 if (--activity_ == 0)
9128 [self setNetworkActivityIndicatorVisible:NO];
9131 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9136 - (void) cancelAndClear:(bool)clear {
9137 @synchronized (self) {
9149 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9150 NSString *context([alert context]);
9152 if ([context isEqualToString:@"conffile"]) {
9153 FILE *input = [database_ input];
9154 if (button == [alert cancelButtonIndex])
9155 fprintf(input, "N\n");
9156 else if (button == [alert firstOtherButtonIndex])
9157 fprintf(input, "Y\n");
9160 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9161 } else if ([context isEqualToString:@"fixhalf"]) {
9162 if (button == [alert cancelButtonIndex]) {
9163 @synchronized (self) {
9164 for (Package *broken in (id) broken_) {
9167 NSString *id = [broken id];
9168 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9169 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9170 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9171 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9177 } else if (button == [alert firstOtherButtonIndex]) {
9178 [broken_ removeAllObjects];
9182 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9183 } else if ([context isEqualToString:@"upgrade"]) {
9184 if (button == [alert firstOtherButtonIndex]) {
9185 @synchronized (self) {
9186 for (Package *essential in (id) essential_)
9187 [essential install];
9192 } else if (button == [alert firstOtherButtonIndex] + 1) {
9194 } else if (button == [alert cancelButtonIndex]) {
9198 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9202 - (void) system:(NSString *)command {
9203 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9206 system([command UTF8String]);
9212 - (void) applicationWillSuspend {
9214 [super applicationWillSuspend];
9217 - (BOOL) isSafeToSuspend {
9220 NSLog(@"isSafeToSuspend: locked_ != 0");
9225 // Use external process status API internally.
9226 // This is probably a really bad idea.
9227 // XXX: what is the point of this? does this solve anything at all?
9228 uint64_t status = 0;
9230 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9231 notify_get_state(notify_token, &status);
9232 notify_cancel(notify_token);
9237 NSLog(@"isSafeToSuspend: status != 0");
9243 NSLog(@"isSafeToSuspend: -> true");
9248 - (void) applicationSuspend:(__GSEvent *)event {
9249 if ([self isSafeToSuspend])
9250 [super applicationSuspend:event];
9253 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9254 if ([self isSafeToSuspend])
9255 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9258 - (void) _setSuspended:(BOOL)value {
9259 if ([self isSafeToSuspend])
9260 [super _setSuspended:value];
9263 - (UIProgressHUD *) addProgressHUD {
9264 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9265 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9267 [window_ setUserInteractionEnabled:NO];
9269 UIViewController *target(tabbar_);
9270 if (UIViewController *modal = [target modalViewController])
9273 [hud showInView:[target view]];
9279 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9280 [self unlockSuspend];
9282 [hud removeFromSuperview];
9283 [window_ setUserInteractionEnabled:YES];
9286 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9287 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9290 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9291 NSString *scheme([[url scheme] lowercaseString]);
9292 if ([[url absoluteString] length] <= [scheme length] + 3)
9294 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9295 NSArray *components([path componentsSeparatedByString:@"/"]);
9297 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9298 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9299 if (controller != nil)
9300 [controller setDelegate:self];
9304 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9307 NSString *base([components objectAtIndex:0]);
9309 CyteViewController *controller = nil;
9311 if ([base isEqualToString:@"url"]) {
9312 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9313 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9314 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9315 } else if (!external && [components count] == 1) {
9316 if ([base isEqualToString:@"sources"]) {
9317 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9320 if ([base isEqualToString:@"home"]) {
9321 controller = [[[HomeController alloc] init] autorelease];
9324 if ([base isEqualToString:@"sections"]) {
9325 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9328 if ([base isEqualToString:@"search"]) {
9329 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9332 if ([base isEqualToString:@"changes"]) {
9333 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9336 if ([base isEqualToString:@"installed"]) {
9337 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9339 } else if ([components count] == 2) {
9340 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9342 if ([base isEqualToString:@"package"]) {
9343 controller = [self pageForPackage:argument withReferrer:referrer];
9346 if (!external && [base isEqualToString:@"search"]) {
9347 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9350 if (!external && [base isEqualToString:@"sections"]) {
9351 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9353 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9356 if (!external && [base isEqualToString:@"sources"]) {
9357 if ([argument isEqualToString:@"add"]) {
9358 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9359 [(SourcesController *)controller showAddSourcePrompt];
9361 Source *source([database_ sourceWithKey:argument]);
9362 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9366 if (!external && [base isEqualToString:@"launch"]) {
9367 [self launchApplicationWithIdentifier:argument suspended:NO];
9370 } else if (!external && [components count] == 3) {
9371 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9372 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9374 if ([base isEqualToString:@"package"]) {
9375 if ([arg2 isEqualToString:@"settings"]) {
9376 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9377 } else if ([arg2 isEqualToString:@"files"]) {
9378 if (Package *package = [database_ packageWithName:arg1]) {
9379 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9380 [(FileTable *)controller setPackage:package];
9385 if ([base isEqualToString:@"sections"]) {
9386 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9387 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9388 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9392 [controller setDelegate:self];
9396 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9397 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9400 [tabbar_ setUnselectedViewController:page];
9405 - (void) applicationOpenURL:(NSURL *)url {
9406 [super applicationOpenURL:url];
9411 [self openCydiaURL:url forExternal:YES];
9414 - (void) applicationWillResignActive:(UIApplication *)application {
9415 // Stop refreshing if you get a phone call or lock the device.
9416 if ([tabbar_ updating])
9417 [tabbar_ cancelUpdate];
9419 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9420 [super applicationWillResignActive:application];
9423 - (void) saveState {
9424 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9425 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9426 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9432 - (void) applicationWillTerminate:(UIApplication *)application {
9436 - (void) setConfigurationData:(NSString *)data {
9437 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9439 if (!conffile_r(data)) {
9440 lprintf("E:invalid conffile\n");
9444 NSString *ofile = conffile_r[1];
9445 //NSString *nfile = conffile_r[2];
9447 UIAlertView *alert = [[[UIAlertView alloc]
9448 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9449 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9451 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9453 UCLocalize("ACCEPT_NEW_COPY"),
9454 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9458 [alert setContext:@"conffile"];
9459 [alert setNumberOfRows:2];
9463 - (void) addStashController {
9465 stash_ = [[[StashController alloc] init] autorelease];
9466 [window_ addSubview:[stash_ view]];
9469 - (void) removeStashController {
9470 [[stash_ view] removeFromSuperview];
9472 [self unlockSuspend];
9476 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9477 UpdateExternalStatus(1);
9478 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9479 UpdateExternalStatus(0);
9481 [self removeStashController];
9483 pid_t pid(ExecFork());
9485 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9486 perror("launchctl stop");
9492 - (void) setupViewControllers {
9493 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9495 NSMutableArray *items;
9496 if (kCFCoreFoundationVersionNumber < 800) {
9497 items = [NSMutableArray arrayWithObjects:
9498 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9499 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9500 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9501 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease],
9502 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9505 items = [NSMutableArray arrayWithObjects:
9506 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home7.png"] selectedImage:[UIImage applicationImageNamed:@"home7s.png"]] autorelease],
9507 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install7.png"] selectedImage:[UIImage applicationImageNamed:@"install7s.png"]] autorelease],
9508 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes7.png"] selectedImage:[UIImage applicationImageNamed:@"changes7s.png"]] autorelease],
9509 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage7.png"] selectedImage:[UIImage applicationImageNamed:@"manage7s.png"]] autorelease],
9510 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search7.png"] selectedImage:[UIImage applicationImageNamed:@"search7s.png"]] autorelease],
9514 NSMutableArray *controllers([NSMutableArray array]);
9515 for (UITabBarItem *item in items) {
9516 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9517 [controller setTabBarItem:item];
9518 [controllers addObject:controller];
9520 [tabbar_ setViewControllers:controllers];
9522 [tabbar_ setUpdateDelegate:self];
9525 - (void) _sendMemoryWarningNotification {
9526 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9527 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9529 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9532 - (void) _sendMemoryWarningNotifications {
9534 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9540 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9542 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9545 - (void) applicationDidFinishLaunching:(id)unused {
9546 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9549 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9550 [self setApplicationSupportsShakeToEdit:NO];
9552 @synchronized (HostConfig_) {
9553 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9556 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9557 initWithMemoryCapacity:524288
9558 diskCapacity:10485760
9559 diskPath:[NSString stringWithFormat:@"%@/SDURLCache", Cache_]
9562 [CydiaWebViewController _initialize];
9564 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9566 // this would disallow http{,s} URLs from accessing this data
9567 //[WebView registerURLSchemeAsLocal:@"cydia"];
9569 Font12_ = [UIFont systemFontOfSize:12];
9570 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9571 Font14_ = [UIFont systemFontOfSize:14];
9572 Font18_ = [UIFont systemFontOfSize:18];
9573 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9574 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9576 essential_ = [NSMutableArray arrayWithCapacity:4];
9577 broken_ = [NSMutableArray arrayWithCapacity:4];
9579 // XXX: I really need this thing... like, seriously... I'm sorry
9580 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9582 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9583 [window_ orderFront:self];
9584 [window_ makeKey:self];
9585 [window_ setHidden:NO];
9588 [self addStashController];
9589 // XXX: this would be much cleaner as a yieldToSelector:
9590 // that way the removeStashController could happen right here inline
9591 // we also could no longer require the useless stash_ field anymore
9592 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9597 int error(stat("/", &root));
9598 _assert(error != -1);
9600 #define Stash_(path) do { \
9601 struct stat folder; \
9602 int error(lstat((path), &folder)); \
9603 if (error != -1 && ( \
9604 folder.st_dev == root.st_dev && \
9605 S_ISDIR(folder.st_mode) \
9606 ) || error == -1 && ( \
9607 errno == ENOENT || \
9612 Stash_("/Applications");
9613 Stash_("/Library/Ringtones");
9614 Stash_("/Library/Wallpaper");
9615 //Stash_("/usr/bin");
9616 Stash_("/usr/include");
9617 Stash_("/usr/lib/pam");
9618 Stash_("/usr/share");
9619 //Stash_("/var/lib");
9621 database_ = [Database sharedInstance];
9622 [database_ setDelegate:self];
9624 [window_ setUserInteractionEnabled:NO];
9625 [self setupViewControllers];
9627 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9628 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9629 [window_ setRootViewController:emulated_];
9631 [window_ addSubview:[emulated_ view]];
9633 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9637 - (NSArray *) defaultStartPages {
9638 NSMutableArray *standard = [NSMutableArray array];
9639 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9640 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9641 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9642 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9643 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9649 if ([emulated_ modalViewController] != nil)
9650 [emulated_ dismissModalViewControllerAnimated:YES];
9651 [window_ setUserInteractionEnabled:NO];
9653 [self reloadDataWithInvocation:nil];
9654 [self refreshIfPossible];
9659 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9660 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9661 int standardIndex = 0;
9662 NSArray *standard = [self defaultStartPages];
9669 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9670 if (valid && closed != nil) {
9671 NSTimeInterval interval([closed timeIntervalSinceNow]);
9672 // XXX: Is 30 minutes the optimal time here?
9673 if (interval <= -(30*60))
9677 if (valid && [saved count] != [standard count])
9681 for (unsigned int i = 0; i < [standard count]; i++) {
9682 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9683 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9684 // but it's good enough for now.
9685 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9692 NSArray *items = nil;
9694 [tabbar_ setSelectedIndex:savedIndex];
9697 [tabbar_ setSelectedIndex:standardIndex];
9701 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9702 NSArray *stack = [items objectAtIndex:tab];
9703 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9704 NSMutableArray *current = [NSMutableArray array];
9706 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9707 NSString *addr = [stack objectAtIndex:nav];
9708 NSURL *url = [NSURL URLWithString:addr];
9709 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9711 [current addObject:page];
9714 [navigation setViewControllers:current];
9717 // (Try to) show the startup URL.
9718 if (starturl_ != nil) {
9719 [self openCydiaURL:starturl_ forExternal:NO];
9724 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9725 if (item != nil && IsWildcat_) {
9726 [sheet showFromBarButtonItem:item animated:YES];
9728 [sheet showInView:window_];
9732 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9733 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9734 [progress setTitle:task];
9735 [progress addProgressEvent:event];
9738 - (void) addProgressEventForTask:(NSArray *)data {
9739 CydiaProgressEvent *event([data objectAtIndex:0]);
9740 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9741 [self addProgressEvent:event forTask:task];
9744 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9745 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9751 id Alloc_(id self, SEL selector) {
9752 id object = alloc_(self, selector);
9753 lprintf("[%s]A-%p\n", self->isa->name, object);
9758 id Dealloc_(id self, SEL selector) {
9759 id object = dealloc_(self, selector);
9760 lprintf("[%s]D-%p\n", self->isa->name, object);
9764 static NSSet *MobilizedFiles_;
9766 static NSURL *MobilizeURL(NSURL *url) {
9767 NSString *path([url path]);
9768 if ([path hasPrefix:@"/var/root/"]) {
9769 NSString *file([path substringFromIndex:10]);
9770 if ([MobilizedFiles_ containsObject:file])
9771 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9777 Class $CFXPreferencesPropertyListSource;
9778 @class CFXPreferencesPropertyListSource;
9780 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9781 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9782 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9783 url = MobilizeURL(url);
9784 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9785 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9791 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9792 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9793 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9794 url = MobilizeURL(url);
9795 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9796 //NSLog(@"%@ %@", [url absoluteString], value);
9802 Class $NSURLConnection;
9804 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9805 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
9807 NSURL *url([copy URL]);
9809 NSString *host([url host]);
9810 NSString *scheme([[url scheme] lowercaseString]);
9812 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9814 @synchronized (HostConfig_) {
9815 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9816 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9817 [copy setHTTPShouldUsePipelining:YES];
9819 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9820 if ([control isEqualToString:@"max-age=0"])
9821 if ([CachedURLs_ containsObject:url]) {
9823 NSLog(@"~~~: %@", url);
9826 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9828 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9829 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9830 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9834 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9840 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
9841 CGSize size([[UIScreen mainScreen] bounds].size);
9842 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
9843 if ([$WAKWindow hasLandscapeOrientation])
9844 std::swap(size.width, size.height);*/
9848 Class $NSUserDefaults;
9850 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
9851 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
9852 return [NSString stringWithFormat:@"%@/LocalStorage", Cache_];
9853 return _NSUserDefaults$objectForKey$(self, _cmd, key);
9856 int main(int argc, char *argv[]) {
9857 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9861 UpdateExternalStatus(0);
9863 UIScreen *screen([UIScreen mainScreen]);
9864 if ([screen respondsToSelector:@selector(scale)])
9865 ScreenScale_ = [screen scale];
9869 UIDevice *device([UIDevice currentDevice]);
9870 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
9871 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9872 if (idiom == UIUserInterfaceIdiomPad)
9876 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
9878 Pcre pattern("^([0-9]+\\.[0-9]+)");
9880 if (pattern([device systemVersion]))
9881 Firmware_ = pattern[1];
9882 if (pattern(Cydia_))
9883 Major_ = pattern[1];
9885 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9887 HostConfig_ = [[[NSObject alloc] init] autorelease];
9888 @synchronized (HostConfig_) {
9889 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9890 TokenHosts_ = [NSMutableSet setWithCapacity:4];
9891 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9892 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9893 CachedURLs_ = [NSMutableSet setWithCapacity:32];
9896 NSString *ui(@"ui/ios");
9898 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
9899 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
9902 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9904 MobilizedFiles_ = [NSMutableSet setWithObjects:
9905 @"Library/Preferences/com.apple.Accessibility.plist",
9906 @"Library/Preferences/com.apple.preferences.sounds.plist",
9909 /* Library Hacks {{{ */
9910 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9912 $WAKWindow = objc_getClass("WAKWindow");
9913 if ($WAKWindow != NULL)
9914 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
9915 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
9917 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9919 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9920 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9921 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9922 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9925 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9926 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9927 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9928 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9931 $NSURLConnection = objc_getClass("NSURLConnection");
9932 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9933 if (NSURLConnection$init$ != NULL) {
9934 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9935 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9938 $NSUserDefaults = objc_getClass("NSUserDefaults");
9939 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
9940 if (NSUserDefaults$objectForKey$ != NULL) {
9941 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
9942 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
9945 /* Set Locale {{{ */
9946 Locale_ = CFLocaleCopyCurrent();
9947 Languages_ = [NSLocale preferredLanguages];
9949 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9950 //NSLog(@"%@", [Languages_ description]);
9953 if (Locale_ != NULL)
9954 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9955 else if (Languages_ != nil && [Languages_ count] != 0)
9956 lang = [[Languages_ objectAtIndex:0] UTF8String];
9958 // XXX: consider just setting to C and then falling through?
9962 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
9963 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
9966 NSLog(@"Setting Language: %s", lang);
9969 setenv("LANG", lang, true);
9970 std::setlocale(LC_ALL, lang);
9974 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9976 /* Parse Arguments {{{ */
9977 bool substrate(false);
9983 for (int argi(1); argi != argc; ++argi)
9984 if (strcmp(argv[argi], "--") == 0) {
9986 argv[argi] = argv[0];
9992 for (int argi(1); argi != arge; ++argi)
9993 if (strcmp(args[argi], "--substrate") == 0)
9996 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10000 App_ = [[NSBundle mainBundle] bundlePath];
10006 if (access("/var/mobile/Library/Keyboard/UserDictionary.sqlite", F_OK) == 0)
10007 system("mkdir -p /var/root/Library/Keyboard; cp -af /var/mobile/Library/Keyboard/UserDictionary.sqlite /var/root/Library/Keyboard/");
10009 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/root"] retain];
10011 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10012 alloc_ = alloc->method_imp;
10013 alloc->method_imp = (IMP) &Alloc_;*/
10015 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10016 dealloc_ = dealloc->method_imp;
10017 dealloc->method_imp = (IMP) &Dealloc_;*/
10019 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10020 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10022 /* System Information {{{ */
10026 size = sizeof(maxproc);
10027 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10028 perror("sysctlbyname(\"kern.maxproc\", ?)");
10029 else if (maxproc < 64) {
10031 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10032 perror("sysctlbyname(\"kern.maxproc\", #)");
10035 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10036 char *osversion = new char[size];
10037 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10038 perror("sysctlbyname(\"kern.osversion\", ?)");
10040 System_ = [NSString stringWithUTF8String:osversion];
10042 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10043 char *machine = new char[size];
10044 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10045 perror("sysctlbyname(\"hw.machine\", ?)");
10047 Machine_ = machine;
10049 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10050 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10051 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10053 UniqueID_ = UniqueIdentifier(device);
10055 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10056 Product_ = [info objectForKey:@"SafariProductVersion"];
10057 Safari_ = [info objectForKey:@"CFBundleVersion"];
10060 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10062 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10063 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10064 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10065 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10066 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10067 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10069 UserAgent_ = agent;
10071 /* Load Database {{{ */
10073 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10075 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10077 if (Metadata_ == NULL)
10078 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10080 Settings_ = [Metadata_ objectForKey:@"Settings"];
10082 Packages_ = [Metadata_ objectForKey:@"Packages"];
10084 Values_ = [Metadata_ objectForKey:@"Values"];
10085 Sections_ = [Metadata_ objectForKey:@"Sections"];
10086 Sources_ = [Metadata_ objectForKey:@"Sources"];
10088 Token_ = [Metadata_ objectForKey:@"Token"];
10090 Version_ = [Metadata_ objectForKey:@"Version"];
10093 if (Values_ == nil) {
10094 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10095 [Metadata_ setObject:Values_ forKey:@"Values"];
10098 if (Sections_ == nil) {
10099 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10100 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10103 if (Sources_ == nil) {
10104 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10105 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10108 if (Version_ == nil) {
10109 Version_ = [NSNumber numberWithUnsignedInt:0];
10110 [Metadata_ setObject:Version_ forKey:@"Version"];
10113 if ([Version_ unsignedIntValue] == 0) {
10114 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10115 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10116 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10117 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10119 Version_ = [NSNumber numberWithUnsignedInt:1];
10120 [Metadata_ setObject:Version_ forKey:@"Version"];
10122 [Metadata_ removeObjectForKey:@"LastUpdate"];
10127 _H<NSMutableArray> broken([NSMutableArray array]);
10128 for (NSString *key in (id) Sources_)
10129 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound)
10130 [broken addObject:key];
10131 if ([broken count] != 0) {
10132 for (NSString *key in (id) broken)
10133 [Sources_ removeObjectForKey:key];
10138 CydiaWriteSources();
10141 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10144 if (Packages_ != nil) {
10146 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10150 [Metadata_ removeObjectForKey:@"Packages"];
10156 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10158 #define MobileSubstrate_(name) \
10159 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10160 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10161 if (handle == NULL) \
10162 NSLog(@"%s", dlerror()); \
10165 MobileSubstrate_(Activator)
10166 MobileSubstrate_(libstatusbar)
10167 MobileSubstrate_(SimulatedKeyEvents)
10168 MobileSubstrate_(WinterBoard)
10170 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10171 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10173 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10175 if (access("/User", F_OK) != 0 || version != 6) {
10177 system("/usr/libexec/cydia/firmware.sh");
10181 _assert([[NSFileManager defaultManager]
10182 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10183 withIntermediateDirectories:YES
10188 if (access("/tmp/cydia.chk", F_OK) == 0) {
10189 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10190 _assert(errno == ENOENT);
10191 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10192 _assert(errno == ENOENT);
10195 /* APT Initialization {{{ */
10196 _assert(pkgInitConfig(*_config));
10197 _assert(pkgInitSystem(*_config, _system));
10200 _config->Set("APT::Acquire::Translation", lang);
10202 // XXX: this timeout might be important :(
10203 //_config->Set("Acquire::http::Timeout", 15);
10205 _config->Set("Acquire::http::MaxParallel", 3);
10207 /* Color Choices {{{ */
10208 space_ = CGColorSpaceCreateDeviceRGB();
10210 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10211 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10212 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10213 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10214 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10215 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10216 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10217 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10218 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10219 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10221 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10222 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10224 /* UIKit Configuration {{{ */
10225 // XXX: I have a feeling this was important
10226 //UIKeyboardDisableAutomaticAppearance();
10229 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10231 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10232 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10233 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10235 PulseInterval_ = fast ? 50000 : 500000;
10237 Colon_ = UCLocalize("COLON_DELIMITED");
10238 Elision_ = UCLocalize("ELISION");
10239 Error_ = UCLocalize("ERROR");
10240 Warning_ = UCLocalize("WARNING");
10243 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10245 CGColorSpaceRelease(space_);
10246 CFRelease(Locale_);