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(7) << count_ << ", " << std::setw(8) << 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 (0 && !ForRelease)
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)
219 #define _trace(args...)
224 #define _profile(name) {
227 #define PrintTimes() do {} while (false)
230 // Hash Functions/Structures {{{
231 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
239 static NSString *Colon_;
241 static NSString *Error_;
242 static NSString *Warning_;
244 static NSString *Cache_;
246 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
248 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
250 static NSString *UniqueIdentifier(UIDevice *device = nil) {
251 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
252 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
254 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
257 static bool IsReachable(const char *name) {
258 SCNetworkReachabilityFlags flags; {
259 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
260 SCNetworkReachabilityGetFlags(reachability, &flags);
261 CFRelease(reachability);
264 // XXX: this elaborate mess is what Apple is using to determine this? :(
265 // XXX: do we care if the user has to intervene? maybe that's ok?
267 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
268 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
269 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
270 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
271 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
272 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
277 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
279 static _finline NSString *CydiaURL(NSString *path) {
281 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
282 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
283 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
284 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
285 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
287 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
290 static void ReapZombie(pid_t pid) {
293 if (waitpid(pid, &status, 0) == -1)
299 static _finline void UpdateExternalStatus(uint64_t newStatus) {
301 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
302 notify_set_state(notify_token, newStatus);
303 notify_cancel(notify_token);
305 notify_post("com.saurik.Cydia.status");
308 static CGFloat CYStatusBarHeight() {
309 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
310 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
313 /* NSForcedOrderingSearch doesn't work on the iPhone */
314 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
315 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
316 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
318 /* Insertion Sort {{{ */
320 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
321 const char *ptr = (const char *)list;
323 CFIndex half = count / 2;
324 const char *probe = ptr + elementSize * half;
325 CFComparisonResult cr = comparator(element, probe, context);
326 if (0 == cr) return (probe - (const char *)list) / elementSize;
327 ptr = (cr < 0) ? ptr : probe + elementSize;
328 count = (cr < 0) ? half : (half + (count & 1) - 1);
330 return (ptr - (const char *)list) / elementSize;
333 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
334 const char *ptr = (const char *)list;
336 CFIndex half = count / 2;
337 const char *probe = ptr + elementSize * half;
338 CFComparisonResult cr = comparator(element, probe, context);
339 if (0 == cr) return (probe - (const char *)list) / elementSize;
340 ptr = (cr < 0) ? ptr : probe + elementSize;
341 count = (cr < 0) ? half : (half + (count & 1) - 1);
343 return (ptr - (const char *)list) / elementSize;
346 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
347 if (range.length == 0)
349 const void **values(new const void *[range.length]);
350 CFArrayGetValues(array, range, values);
352 #if HistogramInsertionSort > 0
353 uint32_t total(0), *offsets(new uint32_t[range.length]);
356 for (CFIndex index(1); index != range.length; ++index) {
357 const void *value(values[index]);
358 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
359 CFIndex correct(index);
360 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
361 #if HistogramInsertionSort > 1
362 NSLog(@"%@ < %@", value, values[correct - 1]);
367 if (correct != index) {
368 size_t offset(index - correct);
369 #if HistogramInsertionSort
373 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
375 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
376 values[correct] = value;
380 CFArrayReplaceValues(array, range, values, range.length);
383 #if HistogramInsertionSort > 0
384 for (CFIndex index(0); index != range.length; ++index)
385 if (offsets[index] != 0)
386 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
387 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
394 /* Apple Bug Fixes {{{ */
395 @implementation UIWebDocumentView (Cydia)
397 - (void) _setScrollerOffset:(CGPoint)offset {
398 UIScroller *scroller([self _scroller]);
400 CGSize size([scroller contentSize]);
401 CGSize bounds([scroller bounds].size);
404 max.x = size.width - bounds.width;
405 max.y = size.height - bounds.height;
413 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
414 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
416 [scroller setOffset:offset];
422 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
423 size_t length([self length] - state->state);
426 else if (length > count)
428 for (size_t i(0); i != length; ++i)
429 objects[i] = [self item:state->state++];
430 state->itemsPtr = objects;
431 state->mutationsPtr = (unsigned long *) self;
435 /* Cydia NSString Additions {{{ */
436 @interface NSString (Cydia)
437 - (NSComparisonResult) compareByPath:(NSString *)other;
438 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
441 @implementation NSString (Cydia)
443 - (NSComparisonResult) compareByPath:(NSString *)other {
444 NSString *prefix = [self commonPrefixWithString:other options:0];
445 size_t length = [prefix length];
447 NSRange lrange = NSMakeRange(length, [self length] - length);
448 NSRange rrange = NSMakeRange(length, [other length] - length);
450 lrange = [self rangeOfString:@"/" options:0 range:lrange];
451 rrange = [other rangeOfString:@"/" options:0 range:rrange];
453 NSComparisonResult value;
455 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
456 value = NSOrderedSame;
457 else if (lrange.location == NSNotFound)
458 value = NSOrderedAscending;
459 else if (rrange.location == NSNotFound)
460 value = NSOrderedDescending;
462 value = NSOrderedSame;
464 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
465 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
466 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
467 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
469 NSComparisonResult result = [lpath compare:rpath];
470 return result == NSOrderedSame ? value : result;
473 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
474 return [(id)CFURLCreateStringByAddingPercentEscapes(
479 kCFStringEncodingUTF8
486 /* C++ NSString Wrapper Cache {{{ */
487 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
488 return size == 0 ? NULL :
489 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
490 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
493 static _finline CFStringRef CYStringCreate(const char *data) {
494 return CYStringCreate(data, strlen(data));
503 _finline void clear_() {
504 if (cache_ != NULL) {
511 _finline bool empty() const {
515 _finline size_t size() const {
519 _finline char *data() const {
523 _finline void clear() {
528 _finline CYString() :
535 _finline ~CYString() {
539 void operator =(const CYString &rhs) {
543 if (rhs.cache_ == nil)
546 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
549 void copy(apr_pool_t *pool) {
550 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
551 memcpy(temp, data_, size_);
556 void set(apr_pool_t *pool, const char *data, size_t size) {
562 data_ = const_cast<char *>(data);
570 _finline void set(apr_pool_t *pool, const char *data) {
571 set(pool, data, data == NULL ? 0 : strlen(data));
574 _finline void set(apr_pool_t *pool, const std::string &rhs) {
575 set(pool, rhs.data(), rhs.size());
578 bool operator ==(const CYString &rhs) const {
579 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
582 _finline operator CFStringRef() {
584 cache_ = CYStringCreate(data_, size_);
588 _finline operator id() {
589 return (NSString *) static_cast<CFStringRef>(*this);
592 _finline operator const char *() {
593 return reinterpret_cast<const char *>(data_);
597 /* C++ NSString Algorithm Adapters {{{ */
599 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
602 struct NSStringMapHash :
603 std::unary_function<NSString *, size_t>
605 _finline size_t operator ()(NSString *value) const {
606 return CFStringHashNSString((CFStringRef) value);
610 struct NSStringMapLess :
611 std::binary_function<NSString *, NSString *, bool>
613 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
614 return [lhs compare:rhs] == NSOrderedAscending;
618 struct NSStringMapEqual :
619 std::binary_function<NSString *, NSString *, bool>
621 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
622 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
623 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
624 //[lhs isEqualToString:rhs];
629 /* CoreGraphics Primitives {{{ */
634 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
635 CGFloat color[] = {red, green, blue, alpha};
636 return CGColorCreate(space, color);
645 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
646 color_(Create_(space, red, green, blue, alpha))
648 Set(space, red, green, blue, alpha);
653 CGColorRelease(color_);
660 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
662 color_ = Create_(space, red, green, blue, alpha);
665 operator CGColorRef() {
671 /* Random Global Variables {{{ */
672 static int PulseInterval_ = 500000;
674 static const NSString *UI_;
677 static bool RestartSubstrate_;
678 static NSArray *Finishes_;
680 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
681 #define NotifyConfig_ "/etc/notify.conf"
683 static bool Queuing_;
685 static CYColor Blue_;
686 static CYColor Blueish_;
687 static CYColor Black_;
688 static CYColor Folder_;
690 static CYColor White_;
691 static CYColor Gray_;
692 static CYColor Green_;
693 static CYColor Purple_;
694 static CYColor Purplish_;
696 static UIColor *InstallingColor_;
697 static UIColor *RemovingColor_;
699 static NSString *App_;
701 static BOOL Advanced_;
702 static BOOL Ignored_;
704 static _H<UIFont> Font12_;
705 static _H<UIFont> Font12Bold_;
706 static _H<UIFont> Font14_;
707 static _H<UIFont> Font18_;
708 static _H<UIFont> Font18Bold_;
709 static _H<UIFont> Font22Bold_;
711 static const char *Machine_ = NULL;
712 static _H<NSString> System_;
713 static NSString *SerialNumber_ = nil;
714 static NSString *ChipID_ = nil;
715 static NSString *BBSNum_ = nil;
716 static _H<NSString> Token_;
717 static _H<NSString> UniqueID_;
718 static _H<NSString> UserAgent_;
719 static _H<NSString> Product_;
720 static _H<NSString> Safari_;
722 static _H<NSLocale> CollationLocale_;
723 static _H<NSArray> CollationThumbs_;
724 static std::vector<NSInteger> CollationOffset_;
725 static _H<NSArray> CollationTitles_;
726 static _H<NSArray> CollationStarts_;
727 static Function<NSString *, NSString *> CollationModify_;
729 static CFLocaleRef Locale_;
730 static NSArray *Languages_;
731 static CGColorSpaceRef space_;
733 static NSDictionary *SectionMap_;
734 static NSMutableDictionary *Metadata_;
735 static _transient NSMutableDictionary *Settings_;
736 static _transient NSMutableDictionary *Packages_;
737 static _transient NSMutableDictionary *Values_;
738 static _transient NSMutableDictionary *Sections_;
739 _H<NSMutableDictionary> Sources_;
740 static _transient NSNumber *Version_;
745 static CGFloat ScreenScale_;
746 static NSString *Idiom_;
747 static _H<NSString> Firmware_;
748 static NSString *Major_;
750 static _H<NSMutableDictionary> SessionData_;
751 static _H<NSObject> HostConfig_;
752 static _H<NSMutableSet> BridgedHosts_;
753 static _H<NSMutableSet> TokenHosts_;
754 static _H<NSMutableSet> InsecureHosts_;
755 static _H<NSMutableSet> PipelinedHosts_;
756 static _H<NSMutableSet> CachedURLs_;
758 static NSString *kCydiaProgressEventTypeError = @"Error";
759 static NSString *kCydiaProgressEventTypeInformation = @"Information";
760 static NSString *kCydiaProgressEventTypeStatus = @"Status";
761 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
764 /* Display Helpers {{{ */
765 inline float Interpolate(float begin, float end, float fraction) {
766 return (end - begin) * fraction + begin;
769 static _finline const char *StripVersion_(const char *version) {
770 const char *colon(strchr(version, ':'));
771 return colon == NULL ? version : colon + 1;
774 NSString *LocalizeSection(NSString *section) {
775 static Pcre title_r("^(.*?) \\((.*)\\)$");
776 if (title_r(section)) {
777 NSString *parent(title_r[1]);
778 NSString *child(title_r[2]);
780 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
781 LocalizeSection(parent),
782 LocalizeSection(child)
786 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
789 NSString *Simplify(NSString *title) {
790 const char *data = [title UTF8String];
791 size_t size = [title length];
793 static Pcre square_r("^\\[(.*)\\]$");
794 if (square_r(data, size))
795 return Simplify(square_r[1]);
797 static Pcre paren_r("^\\((.*)\\)$");
798 if (paren_r(data, size))
799 return Simplify(paren_r[1]);
801 static Pcre title_r("^(.*?) \\((.*)\\)$");
802 if (title_r(data, size))
803 return Simplify(title_r[1]);
809 NSString *GetLastUpdate() {
810 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
813 return UCLocalize("NEVER_OR_UNKNOWN");
815 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
816 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
818 CFRelease(formatter);
820 return [(NSString *) formatted autorelease];
823 bool isSectionVisible(NSString *section) {
824 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
825 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
826 return hidden == nil || ![hidden boolValue];
829 static NSObject *CYIOGetValue(const char *path, NSString *property) {
830 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
831 if (entry == MACH_PORT_NULL)
834 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
835 IOObjectRelease(entry);
839 return [(id) value autorelease];
842 static NSString *CYHex(NSData *data, bool reverse = false) {
846 size_t length([data length]);
847 uint8_t bytes[length];
848 [data getBytes:bytes];
850 char string[length * 2 + 1];
851 for (size_t i(0); i != length; ++i)
852 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
854 return [NSString stringWithUTF8String:string];
859 /* Delegate Prototypes {{{ */
862 @class CydiaProgressEvent;
864 @protocol DatabaseDelegate
865 - (void) repairWithSelector:(SEL)selector;
866 - (void) setConfigurationData:(NSString *)data;
867 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
870 @class CYPackageController;
872 @protocol SourceDelegate
873 - (void) setFetch:(NSNumber *)fetch;
876 @protocol FetchDelegate
877 - (bool) isSourceCancelled;
878 - (void) startSourceFetch:(NSString *)uri;
879 - (void) stopSourceFetch:(NSString *)uri;
882 @protocol CydiaDelegate
883 - (void) returnToCydia;
885 - (void) retainNetworkActivityIndicator;
886 - (void) releaseNetworkActivityIndicator;
887 - (void) clearPackage:(Package *)package;
888 - (void) installPackage:(Package *)package;
889 - (void) installPackages:(NSArray *)packages;
890 - (void) removePackage:(Package *)package;
891 - (void) beginUpdate;
893 - (bool) requestUpdate;
894 - (void) distUpgrade;
897 - (void) _saveConfig;
899 - (void) addSource:(NSDictionary *)source;
900 - (void) addTrivialSource:(NSString *)href;
901 - (UIProgressHUD *) addProgressHUD;
902 - (void) removeProgressHUD:(UIProgressHUD *)hud;
903 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
904 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
908 /* CancelStatus {{{ */
910 public pkgAcquireStatus
921 virtual bool MediaChange(std::string media, std::string drive) {
925 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
929 virtual bool Pulse_(pkgAcquire *Owner) = 0;
931 virtual bool Pulse(pkgAcquire *Owner) {
932 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
940 _finline bool WasCancelled() const {
945 /* DelegateStatus {{{ */
950 _transient NSObject<ProgressDelegate> *delegate_;
958 void setDelegate(NSObject<ProgressDelegate> *delegate) {
959 delegate_ = delegate;
962 virtual void Fetch(pkgAcquire::ItemDesc &item) {
963 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
964 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
965 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
968 virtual void Done(pkgAcquire::ItemDesc &item) {
969 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
970 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
971 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
974 virtual void Fail(pkgAcquire::ItemDesc &item) {
976 item.Owner->Status == pkgAcquire::Item::StatIdle ||
977 item.Owner->Status == pkgAcquire::Item::StatDone
981 std::string &error(item.Owner->ErrorText);
985 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
986 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
989 virtual bool Pulse_(pkgAcquire *Owner) {
991 double(CurrentBytes + CurrentItems) /
992 double(TotalBytes + TotalItems)
995 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
996 [NSNumber numberWithDouble:percent], @"Percent",
998 [NSNumber numberWithDouble:CurrentBytes], @"Current",
999 [NSNumber numberWithDouble:TotalBytes], @"Total",
1000 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1001 nil] waitUntilDone:YES];
1003 return ![delegate_ isProgressCancelled];
1006 virtual void Start() {
1007 pkgAcquireStatus::Start();
1008 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1011 virtual void Stop() {
1012 pkgAcquireStatus::Stop();
1013 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1014 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1018 /* Database Interface {{{ */
1019 typedef std::map< unsigned long, _H<Source> > SourceMap;
1021 @interface Database : NSObject {
1027 pkgCacheFile cache_;
1028 pkgDepCache::Policy *policy_;
1029 pkgRecords *records_;
1030 pkgProblemResolver *resolver_;
1031 pkgAcquire *fetcher_;
1033 SPtr<pkgPackageManager> manager_;
1034 pkgSourceList *list_;
1036 SourceMap sourceMap_;
1037 _H<NSMutableArray> sourceList_;
1039 CFMutableArrayRef packages_;
1041 _transient NSObject<DatabaseDelegate> *delegate_;
1042 _transient NSObject<ProgressDelegate> *progress_;
1044 CydiaStatus status_;
1050 std::map<const char *, _H<NSString> > sections_;
1053 + (Database *) sharedInstance;
1056 - (void) _readCydia:(NSNumber *)fd;
1057 - (void) _readStatus:(NSNumber *)fd;
1058 - (void) _readOutput:(NSNumber *)fd;
1062 - (Package *) packageWithName:(NSString *)name;
1064 - (pkgCacheFile &) cache;
1065 - (pkgDepCache::Policy *) policy;
1066 - (pkgRecords *) records;
1067 - (pkgProblemResolver *) resolver;
1068 - (pkgAcquire &) fetcher;
1069 - (pkgSourceList &) list;
1070 - (NSArray *) packages;
1071 - (NSArray *) sources;
1072 - (Source *) sourceWithKey:(NSString *)key;
1073 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1081 - (void) updateWithStatus:(CancelStatus &)status;
1083 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1085 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1086 - (NSObject<ProgressDelegate> *) progressDelegate;
1088 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1089 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1090 - (void) resetFetch;
1092 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1096 /* SourceStatus {{{ */
1097 class SourceStatus :
1101 _transient NSObject<FetchDelegate> *delegate_;
1102 _transient Database *database_;
1105 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1106 delegate_(delegate),
1111 void Set(bool fetch, pkgAcquire::ItemDesc &desc) {
1113 [database_ setFetch:fetch forURI:desc.Owner->DescURI().c_str()];
1116 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1120 virtual void Done(pkgAcquire::ItemDesc &desc) {
1124 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1128 virtual bool Pulse_(pkgAcquire *Owner) {
1129 for (pkgAcquire::ItemCIterator item = Owner->ItemsBegin(); item != Owner->ItemsEnd(); ++item)
1130 if ((*item)->ID != 0);
1131 else if ((*item)->Status == pkgAcquire::Item::StatIdle) {
1133 [database_ setFetch:true forURI:(*item)->DescURI().c_str()];
1134 } else (*item)->ID = 0;
1135 return ![delegate_ isSourceCancelled];
1138 virtual void Stop() {
1139 pkgAcquireStatus::Stop();
1140 [database_ resetFetch];
1144 /* ProgressEvent Implementation {{{ */
1145 @implementation CydiaProgressEvent
1147 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1148 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1151 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1152 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1153 [event setPackage:package];
1157 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1158 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1160 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1161 NSArray *fields([description componentsSeparatedByString:@" "]);
1162 [event setItem:fields];
1164 if ([fields count] > 3) {
1165 [event setPackage:[fields objectAtIndex:2]];
1166 [event setVersion:[fields objectAtIndex:3]];
1169 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1174 + (NSArray *) _attributeKeys {
1175 return [NSArray arrayWithObjects:
1185 - (NSArray *) attributeKeys {
1186 return [[self class] _attributeKeys];
1189 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1190 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1193 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1194 if ((self = [super init]) != nil) {
1200 - (NSString *) message {
1204 - (NSString *) type {
1208 - (NSArray *) item {
1209 return (id) item_ ?: [NSNull null];
1212 - (void) setItem:(NSArray *)item {
1216 - (NSString *) package {
1217 return (id) package_ ?: [NSNull null];
1220 - (void) setPackage:(NSString *)package {
1224 - (NSString *) url {
1225 return (id) url_ ?: [NSNull null];
1228 - (void) setURL:(NSString *)url {
1232 - (void) setVersion:(NSString *)version {
1236 - (NSString *) version {
1237 return (id) version_ ?: [NSNull null];
1240 - (NSString *) compound:(NSString *)value {
1242 NSString *mode(nil); {
1243 NSString *type([self type]);
1244 if ([type isEqualToString:kCydiaProgressEventTypeError])
1245 mode = UCLocalize("ERROR");
1246 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1247 mode = UCLocalize("WARNING");
1251 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1257 - (NSString *) compoundMessage {
1258 return [self compound:[self message]];
1261 - (NSString *) compoundTitle {
1264 if (package_ == nil)
1266 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1267 title = [package name];
1271 return [self compound:title];
1277 // Cytore Definitions {{{
1278 struct PackageValue :
1281 Cytore::Offset<PackageValue> next_;
1283 uint32_t index_ : 23;
1284 uint32_t subscribed_ : 1;
1301 Cytore::Offset<PackageValue> packages_[1 << 16];
1304 static Cytore::File<MetaValue> MetaFile_;
1306 // Cytore Helper Functions {{{
1307 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1308 SplitHash nhash = { hashlittle(name, length) };
1310 PackageValue *metadata;
1312 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1313 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1314 *offset = MetaFile_.New<PackageValue>(length + 1);
1315 metadata = &MetaFile_.Get(*offset);
1317 if (metadata == NULL) {
1321 metadata = new PackageValue();
1322 memset(metadata, 0, sizeof(*metadata));
1325 memcpy(metadata->name_, name, length);
1326 metadata->name_[length] = '\0';
1327 metadata->nhash_ = nhash.u16[1];
1329 metadata = &MetaFile_.Get(*offset);
1330 if (metadata->nhash_ != nhash.u16[1])
1332 if (strncmp(metadata->name_, name, length) != 0)
1334 if (metadata->name_[length] != '\0')
1341 static void PackageImport(const void *key, const void *value, void *context) {
1342 bool &fail(*reinterpret_cast<bool *>(context));
1345 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1346 NSLog(@"failed to import package %@", key);
1350 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1351 NSDictionary *package((NSDictionary *) value);
1353 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1354 if ([subscribed boolValue] && !metadata->subscribed_)
1355 metadata->subscribed_ = true;
1357 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1358 time_t time([date timeIntervalSince1970]);
1359 if (metadata->first_ > time || metadata->first_ == 0)
1360 metadata->first_ = time;
1363 NSDate *date([package objectForKey:@"LastSeen"]);
1364 NSString *version([package objectForKey:@"LastVersion"]);
1366 if (date != nil && version != nil) {
1367 time_t time([date timeIntervalSince1970]);
1368 if (metadata->last_ < time || metadata->last_ == 0)
1369 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1370 size_t length(strlen(buffer));
1371 uint16_t vhash(hashlittle(buffer, length));
1373 size_t capped(std::min<size_t>(8, length));
1374 char *latest(buffer + length - capped);
1376 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1377 metadata->vhash_ = vhash;
1379 metadata->last_ = time;
1385 /* Source Class {{{ */
1386 @interface Source : NSObject {
1388 Database *database_;
1391 CYString depiction_;
1392 CYString description_;
1398 CYString distribution_;
1404 _H<NSString> authority_;
1406 CYString defaultIcon_;
1408 _H<NSMutableDictionary> record_;
1411 std::set<std::string> fetches_;
1412 std::set<std::string> files_;
1413 _transient NSObject<SourceDelegate> *delegate_;
1416 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1418 - (NSComparisonResult) compareByName:(Source *)source;
1420 - (NSString *) depictionForPackage:(NSString *)package;
1421 - (NSString *) supportForPackage:(NSString *)package;
1423 - (metaIndex *) metaIndex;
1424 - (NSDictionary *) record;
1427 - (NSString *) rooturi;
1428 - (NSString *) distribution;
1429 - (NSString *) type;
1432 - (NSString *) host;
1434 - (NSString *) name;
1435 - (NSString *) shortDescription;
1436 - (NSString *) label;
1437 - (NSString *) origin;
1438 - (NSString *) version;
1440 - (NSString *) defaultIcon;
1441 - (NSURL *) iconURL;
1443 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1444 - (void) resetFetch;
1448 @implementation Source
1450 + (NSString *) webScriptNameForSelector:(SEL)selector {
1452 else if (selector == @selector(addSection:))
1453 return @"addSection";
1454 else if (selector == @selector(getField:))
1456 else if (selector == @selector(removeSection:))
1457 return @"removeSection";
1458 else if (selector == @selector(remove))
1464 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1465 return [self webScriptNameForSelector:selector] == nil;
1468 + (NSArray *) _attributeKeys {
1469 return [NSArray arrayWithObjects:
1480 @"shortDescription",
1487 - (NSArray *) attributeKeys {
1488 return [[self class] _attributeKeys];
1491 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1492 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1495 - (metaIndex *) metaIndex {
1499 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1500 trusted_ = index->IsTrusted();
1502 uri_.set(pool, index->GetURI());
1503 distribution_.set(pool, index->GetDist());
1504 type_.set(pool, index->GetType());
1506 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1507 if (dindex != NULL) {
1508 std::string file(dindex->MetaIndexURI(""));
1509 base_.set(pool, file);
1512 _profile(Source$setMetaIndex$GetIndexes)
1513 dindex->GetIndexes(&acquire, true);
1515 _profile(Source$setMetaIndex$DescURI)
1516 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1517 std::string file((*item)->DescURI());
1518 files_.insert(file);
1519 if (file.length() < sizeof("Packages.bz2") || file.substr(file.length() - sizeof("Packages.bz2")) != "/Packages.bz2")
1521 file = file.substr(0, file.length() - 4);
1522 files_.insert(file);
1523 files_.insert(file + ".gz");
1524 files_.insert(file + "Index");
1529 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1532 pkgTagFile tags(&fd);
1534 pkgTagSection section;
1541 {"default-icon", &defaultIcon_},
1542 {"depiction", &depiction_},
1543 {"description", &description_},
1545 {"origin", &origin_},
1546 {"support", &support_},
1547 {"version", &version_},
1550 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1551 const char *start, *end;
1553 if (section.Find(names[i].name_, start, end)) {
1554 CYString &value(*names[i].value_);
1555 value.set(pool, start, end - start);
1561 record_ = [Sources_ objectForKey:[self key]];
1563 NSURL *url([NSURL URLWithString:uri_]);
1567 host_ = [host_ lowercaseString];
1572 authority_ = [url path];
1575 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1576 if ((self = [super init]) != nil) {
1577 era_ = [database era];
1578 database_ = database;
1581 _profile(Source$initWithMetaIndex$setMetaIndex)
1582 [self setMetaIndex:index inPool:pool];
1587 - (NSString *) getField:(NSString *)name {
1588 @synchronized (database_) {
1589 if ([database_ era] != era_ || index_ == NULL)
1592 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1597 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1602 pkgTagFile tags(&fd);
1604 pkgTagSection section;
1607 const char *start, *end;
1608 if (!section.Find([name UTF8String], start, end))
1609 return (NSString *) [NSNull null];
1611 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1614 - (NSComparisonResult) compareByName:(Source *)source {
1615 NSString *lhs = [self name];
1616 NSString *rhs = [source name];
1618 if ([lhs length] != 0 && [rhs length] != 0) {
1619 unichar lhc = [lhs characterAtIndex:0];
1620 unichar rhc = [rhs characterAtIndex:0];
1622 if (isalpha(lhc) && !isalpha(rhc))
1623 return NSOrderedAscending;
1624 else if (!isalpha(lhc) && isalpha(rhc))
1625 return NSOrderedDescending;
1628 return [lhs compare:rhs options:LaxCompareOptions_];
1631 - (NSString *) depictionForPackage:(NSString *)package {
1632 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1635 - (NSString *) supportForPackage:(NSString *)package {
1636 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1639 - (NSArray *) sections {
1640 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1643 - (void) _addSection:(NSString *)section {
1646 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1647 if (![sections containsObject:section]) {
1648 [sections addObject:section];
1652 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1657 - (bool) addSection:(NSString *)section {
1661 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1665 - (void) _removeSection:(NSString *)section {
1669 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1670 if ([sections containsObject:section]) {
1671 [sections removeObject:section];
1676 - (bool) removeSection:(NSString *)section {
1680 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1685 [Sources_ removeObjectForKey:[self key]];
1690 bool value(record_ != nil);
1691 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1695 - (NSDictionary *) record {
1703 - (NSString *) rooturi {
1707 - (NSString *) distribution {
1708 return distribution_;
1711 - (NSString *) type {
1715 - (NSString *) baseuri {
1716 return base_.empty() ? nil : (id) base_;
1719 - (NSString *) iconuri {
1720 if (NSString *base = [self baseuri])
1721 return [base stringByAppendingString:@"CydiaIcon.png"];
1726 - (NSURL *) iconURL {
1727 if (NSString *uri = [self iconuri])
1728 return [NSURL URLWithString:uri];
1732 - (NSString *) key {
1733 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1736 - (NSString *) host {
1740 - (NSString *) name {
1741 return origin_.empty() ? (id) authority_ : origin_;
1744 - (NSString *) shortDescription {
1745 return description_;
1748 - (NSString *) label {
1749 return label_.empty() ? (id) authority_ : label_;
1752 - (NSString *) origin {
1756 - (NSString *) version {
1760 - (NSString *) defaultIcon {
1761 return defaultIcon_;
1764 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1765 delegate_ = delegate;
1769 return !fetches_.empty();
1772 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1774 if (fetches_.erase(uri) == 0)
1776 } else if (files_.find(uri) == files_.end())
1778 else if (!fetches_.insert(uri).second)
1781 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1784 - (void) resetFetch {
1786 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1791 /* CydiaOperation Class {{{ */
1792 @interface CydiaOperation : NSObject {
1793 _H<NSString> operator_;
1794 _H<NSString> value_;
1797 - (NSString *) operator;
1798 - (NSString *) value;
1802 @implementation CydiaOperation
1804 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1805 if ((self = [super init]) != nil) {
1806 operator_ = [NSString stringWithUTF8String:_operator];
1807 value_ = [NSString stringWithUTF8String:value];
1811 + (NSArray *) _attributeKeys {
1812 return [NSArray arrayWithObjects:
1818 - (NSArray *) attributeKeys {
1819 return [[self class] _attributeKeys];
1822 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1823 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1826 - (NSString *) operator {
1830 - (NSString *) value {
1836 /* CydiaClause Class {{{ */
1837 @interface CydiaClause : NSObject {
1838 _H<NSString> package_;
1839 _H<CydiaOperation> version_;
1842 - (NSString *) package;
1843 - (CydiaOperation *) version;
1847 @implementation CydiaClause
1849 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1850 if ((self = [super init]) != nil) {
1851 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1853 if (const char *version = dep.TargetVer())
1854 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1856 version_ = (id) [NSNull null];
1860 + (NSArray *) _attributeKeys {
1861 return [NSArray arrayWithObjects:
1867 - (NSArray *) attributeKeys {
1868 return [[self class] _attributeKeys];
1871 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1872 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1875 - (NSString *) package {
1879 - (CydiaOperation *) version {
1885 /* CydiaRelation Class {{{ */
1886 @interface CydiaRelation : NSObject {
1887 _H<NSString> relationship_;
1888 _H<NSMutableArray> clauses_;
1891 - (NSString *) relationship;
1892 - (NSArray *) clauses;
1896 @implementation CydiaRelation
1898 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1899 if ((self = [super init]) != nil) {
1900 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1901 clauses_ = [NSMutableArray arrayWithCapacity:8];
1903 pkgCache::DepIterator start;
1904 pkgCache::DepIterator end;
1905 dep.GlobOr(start, end); // ++dep
1908 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1910 // yes, seriously. (wtf?)
1918 + (NSArray *) _attributeKeys {
1919 return [NSArray arrayWithObjects:
1925 - (NSArray *) attributeKeys {
1926 return [[self class] _attributeKeys];
1929 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1930 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1933 - (NSString *) relationship {
1934 return relationship_;
1937 - (NSArray *) clauses {
1941 - (void) addClause:(CydiaClause *)clause {
1942 [clauses_ addObject:clause];
1947 /* Package Class {{{ */
1948 struct ParsedPackage {
1952 CYString architecture_;
1955 CYString depiction_;
1962 @interface Package : NSObject {
1964 @public uint32_t role_ : 3;
1965 uint32_t essential_ : 1;
1966 uint32_t obsolete_ : 1;
1967 uint32_t ignored_ : 1;
1968 uint32_t pooled_ : 1;
1974 _transient Database *database_;
1976 pkgCache::VerIterator version_;
1977 pkgCache::PkgIterator iterator_;
1978 pkgCache::VerFileIterator file_;
1984 CYString installed_;
1987 const char *section_;
1988 _transient NSString *section$_;
1992 PackageValue *metadata_;
1993 ParsedPackage *parsed_;
1995 _H<NSMutableArray> tags_;
1998 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1999 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2001 - (pkgCache::PkgIterator) iterator;
2004 - (NSString *) section;
2005 - (NSString *) simpleSection;
2007 - (NSString *) longSection;
2008 - (NSString *) shortSection;
2012 - (MIMEAddress *) maintainer;
2014 - (NSString *) longDescription;
2015 - (NSString *) shortDescription;
2018 - (PackageValue *) metadata;
2021 - (bool) subscribed;
2022 - (bool) setSubscribed:(bool)subscribed;
2026 - (NSString *) latest;
2027 - (NSString *) installed;
2028 - (BOOL) uninstalled;
2031 - (BOOL) upgradableAndEssential:(BOOL)essential;
2034 - (BOOL) unfiltered;
2038 - (BOOL) halfConfigured;
2039 - (BOOL) halfInstalled;
2041 - (NSString *) mode;
2044 - (NSString *) name;
2046 - (NSString *) homepage;
2047 - (NSString *) depiction;
2048 - (MIMEAddress *) author;
2050 - (NSString *) support;
2052 - (NSArray *) files;
2053 - (NSArray *) warnings;
2054 - (NSArray *) applications;
2056 - (Source *) source;
2059 - (BOOL) matches:(NSArray *)query;
2061 - (BOOL) hasTag:(NSString *)tag;
2062 - (NSString *) primaryPurpose;
2063 - (NSArray *) purposes;
2064 - (bool) isCommercial;
2066 - (void) setIndex:(size_t)index;
2068 - (CYString &) cyname;
2070 - (uint32_t) compareBySection:(NSArray *)sections;
2077 uint32_t PackageChangesRadix(Package *self, void *) {
2082 uint32_t timestamp : 30;
2083 uint32_t ignored : 1;
2084 uint32_t upgradable : 1;
2088 bool upgradable([self upgradableAndEssential:YES]);
2089 value.bits.upgradable = upgradable ? 1 : 0;
2092 value.bits.timestamp = 0;
2093 value.bits.ignored = [self ignored] ? 0 : 1;
2094 value.bits.upgradable = 1;
2096 value.bits.timestamp = [self seen] >> 2;
2097 value.bits.ignored = 0;
2098 value.bits.upgradable = 0;
2101 return _not(uint32_t) - value.key;
2104 CYString &(*PackageName)(Package *self, SEL sel);
2106 uint32_t PackagePrefixRadix(Package *self, void *context) {
2107 size_t offset(reinterpret_cast<size_t>(context));
2108 CYString &name(PackageName(self, @selector(cyname)));
2110 size_t size(name.size());
2113 char *text(name.data());
2116 if (!isdigit(text[0]))
2120 while (size != digits && isdigit(text[digits]))
2128 if (offset == 0 && zeros != 0) {
2129 memset(data, '0', zeros);
2130 memcpy(data + zeros, text, 4 - zeros);
2132 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2133 if (size <= offset - zeros)
2136 text += offset - zeros;
2137 size -= offset - zeros;
2140 memcpy(data, text, 4);
2142 memcpy(data, text, size);
2143 memset(data + size, 0, 4 - size);
2146 for (size_t i(0); i != 4; ++i)
2147 if (isalpha(data[i]))
2155 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2157 /* XXX: ntohl may be more honest */
2158 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2161 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, void *arg) {
2162 _profile(PackageNameCompare)
2164 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2165 else if (rhn == NULL)
2166 return kCFCompareGreaterThan;
2168 CFIndex lhl(CFStringGetLength(lhn));
2170 _profile(PackageNameCompare$NumbersLast)
2171 if (lhl != 0 && CFStringGetLength(rhn) != 0) {
2172 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2173 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2174 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2175 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2176 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2180 _profile(PackageNameCompare$Compare)
2181 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, lhl), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2186 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2187 CYString &lhi(PackageName(lhs, @selector(cyname)));
2188 CYString &rhi(PackageName(rhs, @selector(cyname)));
2189 CFStringRef lhn(lhi), rhn(rhi);
2190 return StringNameCompare(lhn, rhn, arg);
2193 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2194 return PackageNameCompare(*lhs, *rhs, arg);
2197 struct PackageNameOrdering :
2198 std::binary_function<Package *, Package *, bool>
2200 _finline bool operator ()(Package *lhs, Package *rhs) const {
2201 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2205 @implementation Package
2207 - (NSString *) description {
2208 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2213 apr_pool_destroy(pool_);
2214 if (parsed_ != NULL)
2219 + (NSString *) webScriptNameForSelector:(SEL)selector {
2221 else if (selector == @selector(clear))
2223 else if (selector == @selector(getField:))
2225 else if (selector == @selector(getRecord))
2226 return @"getRecord";
2227 else if (selector == @selector(hasTag:))
2229 else if (selector == @selector(install))
2231 else if (selector == @selector(remove))
2237 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2238 return [self webScriptNameForSelector:selector] == nil;
2241 + (NSArray *) _attributeKeys {
2242 return [NSArray arrayWithObjects:
2263 @"shortDescription",
2275 - (NSArray *) attributeKeys {
2276 return [[self class] _attributeKeys];
2279 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2280 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2283 - (NSArray *) relations {
2284 @synchronized (database_) {
2285 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2286 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2287 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2291 - (NSString *) architecture {
2293 @synchronized (database_) {
2294 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2297 - (NSString *) getField:(NSString *)name {
2298 @synchronized (database_) {
2299 if ([database_ era] != era_ || file_.end())
2302 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2304 const char *start, *end;
2305 if (!parser.Find([name UTF8String], start, end))
2306 return (NSString *) [NSNull null];
2308 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2311 - (NSString *) getRecord {
2312 @synchronized (database_) {
2313 if ([database_ era] != era_ || file_.end())
2316 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2318 const char *start, *end;
2319 parser.GetRec(start, end);
2321 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2325 if (parsed_ != NULL)
2327 @synchronized (database_) {
2328 if ([database_ era] != era_ || file_.end())
2331 ParsedPackage *parsed(new ParsedPackage);
2334 _profile(Package$parse)
2335 pkgRecords::Parser *parser;
2337 _profile(Package$parse$Lookup)
2338 parser = &[database_ records]->Lookup(file_);
2344 _profile(Package$parse$Find)
2349 {"architecture", &parsed->architecture_},
2350 {"icon", &parsed->icon_},
2351 {"depiction", &parsed->depiction_},
2352 {"homepage", &parsed->homepage_},
2353 {"website", &website},
2355 {"support", &parsed->support_},
2356 {"author", &parsed->author_},
2357 {"md5sum", &parsed->md5sum_},
2360 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2361 const char *start, *end;
2363 if (parser->Find(names[i].name_, start, end)) {
2364 CYString &value(*names[i].value_);
2365 _profile(Package$parse$Value)
2366 value.set(pool_, start, end - start);
2372 _profile(Package$parse$Tagline)
2373 const char *start, *end;
2374 if (parser->ShortDesc(start, end)) {
2375 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2378 while (stop != start && stop[-1] == '\r')
2380 parsed->tagline_.set(pool_, start, stop - start);
2384 _profile(Package$parse$Retain)
2385 if (parsed->homepage_.empty())
2386 parsed->homepage_ = website;
2387 if (parsed->homepage_ == parsed->depiction_)
2388 parsed->homepage_.clear();
2389 if (parsed->support_.empty())
2390 parsed->support_ = bugs;
2395 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2396 if ((self = [super init]) != nil) {
2397 _profile(Package$initWithVersion)
2399 apr_pool_create(&pool_, NULL);
2405 database_ = database;
2406 era_ = [database era];
2410 pkgCache::PkgIterator iterator(version.ParentPkg());
2411 iterator_ = iterator;
2413 _profile(Package$initWithVersion$Version)
2414 if (!version_.end())
2415 file_ = version_.FileList();
2417 pkgCache &cache([database_ cache]);
2418 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2422 _profile(Package$initWithVersion$Cache)
2423 name_.set(NULL, iterator.Display());
2425 latest_.set(NULL, StripVersion_(version_.VerStr()));
2427 pkgCache::VerIterator current(iterator.CurrentVer());
2429 installed_.set(NULL, StripVersion_(current.VerStr()));
2432 _profile(Package$initWithVersion$Tags)
2433 pkgCache::TagIterator tag(iterator.TagList());
2435 tags_ = [NSMutableArray arrayWithCapacity:8];
2437 goto tag; for (; !tag.end(); ++tag) tag: {
2438 const char *name(tag.Name());
2439 NSString *string((NSString *) CYStringCreate(name));
2443 [tags_ addObject:[string autorelease]];
2445 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2446 if (strcmp(name + 6, "enduser") == 0)
2448 else if (strcmp(name + 6, "hacker") == 0)
2450 else if (strcmp(name + 6, "developer") == 0)
2452 else if (strcmp(name + 6, "cydia") == 0)
2458 if (strncmp(name, "cydia::", 7) == 0) {
2459 if (strcmp(name + 7, "essential") == 0)
2461 else if (strcmp(name + 7, "obsolete") == 0)
2468 _profile(Package$initWithVersion$Metadata)
2469 const char *mixed(iterator.Name());
2470 size_t size(strlen(mixed));
2471 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2472 char lower[prefix + size + 5 + 1];
2474 for (size_t i(0); i != size; ++i)
2475 lower[prefix + i] = mixed[i] | 0x20;
2477 if (!installed_.empty()) {
2478 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2479 memcpy(lower + prefix + size, ".list", 6);
2481 if (stat(lower, &info) != -1)
2482 updated_ = info.st_birthtime;
2485 PackageValue *metadata(PackageFind(lower + prefix, size));
2486 metadata_ = metadata;
2488 id_.set(NULL, metadata->name_, size);
2490 const char *latest(version_.VerStr());
2491 size_t length(strlen(latest));
2493 uint16_t vhash(hashlittle(latest, length));
2495 size_t capped(std::min<size_t>(8, length));
2496 latest = latest + length - capped;
2498 if (metadata->first_ == 0)
2499 metadata->first_ = now_;
2501 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2502 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2503 metadata->vhash_ = vhash;
2504 metadata->last_ = now_;
2505 } else if (metadata->last_ == 0)
2506 metadata->last_ = metadata->first_;
2509 _profile(Package$initWithVersion$Section)
2510 section_ = version_.Section();
2513 _profile(Package$initWithVersion$Flags)
2514 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2515 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2520 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2521 pkgCache::VerIterator version;
2523 _profile(Package$packageWithIterator$GetCandidateVer)
2524 version = [database policy]->GetCandidateVer(iterator);
2532 _profile(Package$packageWithIterator$Allocate)
2533 package = [Package allocWithZone:zone];
2536 _profile(Package$packageWithIterator$Initialize)
2538 initWithVersion:version
2545 _profile(Package$packageWithIterator$Autorelease)
2546 package = [package autorelease];
2552 - (pkgCache::PkgIterator) iterator {
2556 - (NSString *) section {
2557 if (section$_ == nil) {
2558 if (section_ == NULL)
2561 _profile(Package$section$mappedSectionForPointer)
2562 section$_ = [database_ mappedSectionForPointer:section_];
2567 - (NSString *) simpleSection {
2568 if (NSString *section = [self section])
2569 return Simplify(section);
2574 - (NSString *) longSection {
2575 return LocalizeSection([self section]);
2578 - (NSString *) shortSection {
2579 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2582 - (NSString *) uri {
2585 pkgIndexFile *index;
2586 pkgCache::PkgFileIterator file(file_.File());
2587 if (![database_ list].FindIndex(file, index))
2589 return [NSString stringWithUTF8String:iterator_->Path];
2590 //return [NSString stringWithUTF8String:file.Site()];
2591 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2595 - (MIMEAddress *) maintainer {
2596 @synchronized (database_) {
2597 if ([database_ era] != era_ || file_.end())
2600 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2601 const std::string &maintainer(parser->Maintainer());
2602 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2605 - (NSString *) md5sum {
2606 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2610 @synchronized (database_) {
2611 if ([database_ era] != era_ || version_.end())
2614 return version_->InstalledSize;
2617 - (NSString *) longDescription {
2618 @synchronized (database_) {
2619 if ([database_ era] != era_ || file_.end())
2622 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2623 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2625 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2626 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2627 if ([lines count] < 2)
2630 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2631 for (size_t i(1), e([lines count]); i != e; ++i) {
2632 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2633 [trimmed addObject:trim];
2636 return [trimmed componentsJoinedByString:@"\n"];
2639 - (NSString *) shortDescription {
2640 if (parsed_ != NULL)
2641 return static_cast<NSString *>(parsed_->tagline_);
2643 @synchronized (database_) {
2644 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2646 const char *start, *end;
2647 if (!parser.ShortDesc(start, end))
2650 if (end - start > 200)
2654 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2657 while (end != start && end[-1] == '\r')
2661 return [(id) CYStringCreate(start, end - start) autorelease];
2665 _profile(Package$index)
2666 CFStringRef name((CFStringRef) [self name]);
2667 if (CFStringGetLength(name) == 0)
2669 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2670 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2672 return toupper(character);
2676 - (PackageValue *) metadata {
2681 PackageValue *metadata([self metadata]);
2682 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2685 - (bool) subscribed {
2686 return [self metadata]->subscribed_;
2689 - (bool) setSubscribed:(bool)subscribed {
2690 PackageValue *metadata([self metadata]);
2691 if (metadata->subscribed_ == subscribed)
2693 metadata->subscribed_ = subscribed;
2701 - (NSString *) latest {
2705 - (NSString *) installed {
2709 - (BOOL) uninstalled {
2710 return installed_.empty();
2714 return !version_.end();
2717 - (BOOL) upgradableAndEssential:(BOOL)essential {
2718 _profile(Package$upgradableAndEssential)
2719 pkgCache::VerIterator current(iterator_.CurrentVer());
2721 return essential && essential_;
2723 return !version_.end() && version_ != current;
2727 - (BOOL) essential {
2732 return [database_ cache][iterator_].InstBroken();
2735 - (BOOL) unfiltered {
2736 _profile(Package$unfiltered$obsolete)
2737 if (_unlikely(obsolete_))
2741 _profile(Package$unfiltered$role)
2742 if (_unlikely(role_ > 3))
2750 if (![self unfiltered])
2755 _profile(Package$visible$section)
2756 section = [self section];
2759 _profile(Package$visible$isSectionVisible)
2760 if (!isSectionVisible(section))
2768 unsigned char current(iterator_->CurrentState);
2769 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2772 - (BOOL) halfConfigured {
2773 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2776 - (BOOL) halfInstalled {
2777 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2781 @synchronized (database_) {
2782 if ([database_ era] != era_ || iterator_.end())
2785 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2786 return state.Mode != pkgDepCache::ModeKeep;
2789 - (NSString *) mode {
2790 @synchronized (database_) {
2791 if ([database_ era] != era_ || iterator_.end())
2794 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2796 switch (state.Mode) {
2797 case pkgDepCache::ModeDelete:
2798 if ((state.iFlags & pkgDepCache::Purge) != 0)
2802 case pkgDepCache::ModeKeep:
2803 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2804 return @"REINSTALL";
2805 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2809 case pkgDepCache::ModeInstall:
2810 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2811 return @"REINSTALL";
2812 else*/ switch (state.Status) {
2814 return @"DOWNGRADE";
2820 return @"NEW_INSTALL";
2831 - (NSString *) name {
2832 return name_.empty() ? id_ : name_;
2835 - (UIImage *) icon {
2836 NSString *section = [self simpleSection];
2839 if (parsed_ != NULL)
2840 if (NSString *href = parsed_->icon_)
2841 if ([href hasPrefix:@"file:///"])
2842 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2843 if (icon == nil) if (section != nil)
2844 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2845 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2846 if ([dicon hasPrefix:@"file:///"])
2847 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2849 icon = [UIImage applicationImageNamed:@"unknown.png"];
2853 - (NSString *) homepage {
2854 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2857 - (NSString *) depiction {
2858 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2861 - (MIMEAddress *) author {
2862 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2865 - (NSString *) support {
2866 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
2869 - (NSArray *) files {
2870 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2871 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2874 fin.open([path UTF8String]);
2879 while (std::getline(fin, line))
2880 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2885 - (NSString *) state {
2886 @synchronized (database_) {
2887 if ([database_ era] != era_ || file_.end())
2890 switch (iterator_->CurrentState) {
2891 case pkgCache::State::NotInstalled:
2892 return @"NotInstalled";
2893 case pkgCache::State::UnPacked:
2895 case pkgCache::State::HalfConfigured:
2896 return @"HalfConfigured";
2897 case pkgCache::State::HalfInstalled:
2898 return @"HalfInstalled";
2899 case pkgCache::State::ConfigFiles:
2900 return @"ConfigFiles";
2901 case pkgCache::State::Installed:
2902 return @"Installed";
2903 case pkgCache::State::TriggersAwaited:
2904 return @"TriggersAwaited";
2905 case pkgCache::State::TriggersPending:
2906 return @"TriggersPending";
2909 return (NSString *) [NSNull null];
2912 - (NSString *) selection {
2913 @synchronized (database_) {
2914 if ([database_ era] != era_ || file_.end())
2917 switch (iterator_->SelectedState) {
2918 case pkgCache::State::Unknown:
2920 case pkgCache::State::Install:
2922 case pkgCache::State::Hold:
2924 case pkgCache::State::DeInstall:
2925 return @"DeInstall";
2926 case pkgCache::State::Purge:
2930 return (NSString *) [NSNull null];
2933 - (NSArray *) warnings {
2934 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2935 const char *name(iterator_.Name());
2937 size_t length(strlen(name));
2938 if (length < 2) invalid:
2939 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2940 else for (size_t i(0); i != length; ++i)
2942 /* XXX: technically this is not allowed */
2943 (name[i] < 'A' || name[i] > 'Z') &&
2944 (name[i] < 'a' || name[i] > 'z') &&
2945 (name[i] < '0' || name[i] > '9') &&
2946 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2949 if (strcmp(name, "cydia") != 0) {
2952 bool _private = false;
2955 bool repository = [[self section] isEqualToString:@"Repositories"];
2957 if (NSArray *files = [self files])
2958 for (NSString *file in files)
2959 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2961 else if (!user && [file isEqualToString:@"/User"])
2963 else if (!_private && [file isEqualToString:@"/private"])
2965 else if (!stash && [file isEqualToString:@"/var/stash"])
2968 /* XXX: this is not sensitive enough. only some folders are valid. */
2969 if (cydia && !repository)
2970 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2972 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2974 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2976 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2979 return [warnings count] == 0 ? nil : warnings;
2982 - (NSArray *) applications {
2983 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2985 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2987 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2988 if (NSArray *files = [self files])
2989 for (NSString *file in files)
2990 if (application_r(file)) {
2991 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2992 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2993 if ([id isEqualToString:me])
2996 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2998 display = application_r[1];
3000 NSString *bundle([file stringByDeletingLastPathComponent]);
3001 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3002 // XXX: maybe this should check if this is really a string, not just for length
3003 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3005 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3007 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3008 [applications addObject:application];
3010 [application addObject:id];
3011 [application addObject:display];
3012 [application addObject:url];
3015 return [applications count] == 0 ? nil : applications;
3018 - (Source *) source {
3019 if (source_ == nil) {
3020 @synchronized (database_) {
3021 if ([database_ era] != era_ || file_.end())
3022 source_ = (Source *) [NSNull null];
3024 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3028 return source_ == (Source *) [NSNull null] ? nil : source_;
3031 - (uint32_t) updated {
3032 return std::numeric_limits<uint32_t>::max() - updated_;
3039 - (BOOL) matches:(NSArray *)query {
3040 if (query == nil || [query count] == 0)
3049 string = [self name];
3050 length = [string length];
3052 for (NSString *term in query) {
3053 range = [string rangeOfString:term options:MatchCompareOptions_];
3054 if (range.location != NSNotFound)
3055 rank_ -= 6 * 1000000 / length;
3060 length = [string length];
3062 for (NSString *term in query) {
3063 range = [string rangeOfString:term options:MatchCompareOptions_];
3064 if (range.location != NSNotFound)
3065 rank_ -= 6 * 1000000 / length;
3069 string = [self shortDescription];
3070 length = [string length];
3071 NSUInteger stop(std::min<NSUInteger>(length, 200));
3073 for (NSString *term in query) {
3074 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3075 if (range.location != NSNotFound)
3076 rank_ -= 2 * 100000;
3082 - (NSArray *) tags {
3086 - (BOOL) hasTag:(NSString *)tag {
3087 return tags_ == nil ? NO : [tags_ containsObject:tag];
3090 - (NSString *) primaryPurpose {
3091 for (NSString *tag in (NSArray *) tags_)
3092 if ([tag hasPrefix:@"purpose::"])
3093 return [tag substringFromIndex:9];
3097 - (NSArray *) purposes {
3098 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3099 for (NSString *tag in (NSArray *) tags_)
3100 if ([tag hasPrefix:@"purpose::"])
3101 [purposes addObject:[tag substringFromIndex:9]];
3102 return [purposes count] == 0 ? nil : purposes;
3105 - (bool) isCommercial {
3106 return [self hasTag:@"cydia::commercial"];
3109 - (void) setIndex:(size_t)index {
3110 if (metadata_->index_ != index)
3111 metadata_->index_ = index;
3114 - (CYString &) cyname {
3115 return name_.empty() ? id_ : name_;
3118 - (uint32_t) compareBySection:(NSArray *)sections {
3119 NSString *section([self section]);
3120 for (size_t i(0), e([sections count]); i != e; ++i) {
3121 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3125 return _not(uint32_t);
3129 @synchronized (database_) {
3130 pkgProblemResolver *resolver = [database_ resolver];
3131 resolver->Clear(iterator_);
3133 pkgCacheFile &cache([database_ cache]);
3134 cache->SetReInstall(iterator_, false);
3135 cache->MarkKeep(iterator_, false);
3139 @synchronized (database_) {
3140 pkgProblemResolver *resolver = [database_ resolver];
3141 resolver->Clear(iterator_);
3142 resolver->Protect(iterator_);
3144 pkgCacheFile &cache([database_ cache]);
3145 cache->SetReInstall(iterator_, false);
3146 cache->MarkInstall(iterator_, false);
3148 pkgDepCache::StateCache &state((*cache)[iterator_]);
3149 if (!state.Install())
3150 cache->SetReInstall(iterator_, true);
3154 @synchronized (database_) {
3155 pkgProblemResolver *resolver = [database_ resolver];
3156 resolver->Clear(iterator_);
3157 resolver->Remove(iterator_);
3158 resolver->Protect(iterator_);
3160 pkgCacheFile &cache([database_ cache]);
3161 cache->SetReInstall(iterator_, false);
3162 cache->MarkDelete(iterator_, true);
3167 /* Section Class {{{ */
3168 @interface Section : NSObject {
3172 _H<NSString> localized_;
3175 - (NSComparisonResult) compareByLocalized:(Section *)section;
3176 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3177 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3178 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3180 - (NSString *) name;
3181 - (void) setName:(NSString *)name;
3187 - (void) addToCount;
3189 - (void) setCount:(size_t)count;
3190 - (NSString *) localized;
3194 @implementation Section
3196 - (NSComparisonResult) compareByLocalized:(Section *)section {
3197 NSString *lhs(localized_);
3198 NSString *rhs([section localized]);
3200 /*if ([lhs length] != 0 && [rhs length] != 0) {
3201 unichar lhc = [lhs characterAtIndex:0];
3202 unichar rhc = [rhs characterAtIndex:0];
3204 if (isalpha(lhc) && !isalpha(rhc))
3205 return NSOrderedAscending;
3206 else if (!isalpha(lhc) && isalpha(rhc))
3207 return NSOrderedDescending;
3210 return [lhs compare:rhs options:LaxCompareOptions_];
3213 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3214 if ((self = [self initWithName:name localize:NO]) != nil) {
3215 if (localized != nil)
3216 localized_ = localized;
3220 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3221 return [self initWithName:name row:0 localize:localize];
3224 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3225 if ((self = [super init]) != nil) {
3229 localized_ = LocalizeSection(name_);
3233 - (NSString *) name {
3237 - (void) setName:(NSString *)name {
3253 - (void) addToCount {
3257 - (void) setCount:(size_t)count {
3261 - (NSString *) localized {
3268 class CydiaLogCleaner :
3269 public pkgArchiveCleaner
3272 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3277 /* Database Implementation {{{ */
3278 @implementation Database
3280 + (Database *) sharedInstance {
3281 static _H<Database> instance;
3282 if (instance == nil)
3283 instance = [[[Database alloc] init] autorelease];
3291 - (void) releasePackages {
3292 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3293 CFArrayRemoveAllValues(packages_);
3297 // XXX: actually implement this thing
3299 [self releasePackages];
3300 apr_pool_destroy(pool_);
3301 NSRecycleZone(zone_);
3305 - (void) _readCydia:(NSNumber *)fd {
3306 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3307 std::istream is(&ib);
3310 static Pcre finish_r("^finish:([^:]*)$");
3312 while (std::getline(is, line)) {
3313 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3315 const char *data(line.c_str());
3316 size_t size = line.size();
3317 lprintf("C:%s\n", data);
3319 if (finish_r(data, size)) {
3320 NSString *finish = finish_r[1];
3321 int index = [Finishes_ indexOfObject:finish];
3322 if (index != INT_MAX && index > Finish_)
3332 - (void) _readStatus:(NSNumber *)fd {
3333 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3334 std::istream is(&ib);
3337 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3338 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3340 while (std::getline(is, line)) {
3341 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3343 const char *data(line.c_str());
3344 size_t size(line.size());
3345 lprintf("S:%s\n", data);
3347 if (conffile_r(data, size)) {
3348 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3349 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3350 } else if (strncmp(data, "status: ", 8) == 0) {
3351 // status: <package>: {unpacked,half-configured,installed}
3352 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3353 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3354 } else if (strncmp(data, "processing: ", 12) == 0) {
3355 // processing: configure: config-test
3356 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3357 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3358 } else if (pmstatus_r(data, size)) {
3359 std::string type([pmstatus_r[1] UTF8String]);
3361 NSString *package = pmstatus_r[2];
3362 if ([package isEqualToString:@"dpkg-exec"])
3365 float percent([pmstatus_r[3] floatValue]);
3366 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3368 NSString *string = pmstatus_r[4];
3370 if (type == "pmerror") {
3371 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3372 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3373 } else if (type == "pmstatus") {
3374 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3375 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3376 } else if (type == "pmconffile")
3377 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3379 lprintf("E:unknown pmstatus\n");
3381 lprintf("E:unknown status\n");
3389 - (void) _readOutput:(NSNumber *)fd {
3390 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3391 std::istream is(&ib);
3394 while (std::getline(is, line)) {
3395 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3397 lprintf("O:%s\n", line.c_str());
3399 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3400 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3412 - (Package *) packageWithName:(NSString *)name {
3415 @synchronized (self) {
3416 if (static_cast<pkgDepCache *>(cache_) == NULL)
3418 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3419 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3423 if ((self = [super init]) != nil) {
3430 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3431 apr_pool_create(&pool_, NULL);
3433 size_t capacity(MetaFile_->active_);
3439 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3440 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3444 _assert(pipe(fds) != -1);
3447 _config->Set("APT::Keep-Fds::", cydiafd_);
3448 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3451 detachNewThreadSelector:@selector(_readCydia:)
3453 withObject:[NSNumber numberWithInt:fds[0]]
3456 _assert(pipe(fds) != -1);
3460 detachNewThreadSelector:@selector(_readStatus:)
3462 withObject:[NSNumber numberWithInt:fds[0]]
3465 _assert(pipe(fds) != -1);
3466 _assert(dup2(fds[0], 0) != -1);
3467 _assert(close(fds[0]) != -1);
3469 input_ = fdopen(fds[1], "a");
3471 _assert(pipe(fds) != -1);
3472 _assert(dup2(fds[1], 1) != -1);
3473 _assert(close(fds[1]) != -1);
3476 detachNewThreadSelector:@selector(_readOutput:)
3478 withObject:[NSNumber numberWithInt:fds[0]]
3483 - (pkgCacheFile &) cache {
3487 - (pkgDepCache::Policy *) policy {
3491 - (pkgRecords *) records {
3495 - (pkgProblemResolver *) resolver {
3499 - (pkgAcquire &) fetcher {
3503 - (pkgSourceList &) list {
3507 - (NSArray *) packages {
3508 return (NSArray *) packages_;
3511 - (NSArray *) sources {
3515 - (Source *) sourceWithKey:(NSString *)key {
3516 for (Source *source in [self sources]) {
3517 if ([[source key] isEqualToString:key])
3522 - (bool) popErrorWithTitle:(NSString *)title {
3525 while (!_error->empty()) {
3527 bool warning(!_error->PopMessage(error));
3532 size_t size(error.size());
3533 if (size == 0 || error[size - 1] != '\n')
3535 error.resize(size - 1);
3538 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3540 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3541 if (warning && no_pubkey(error.c_str()))
3544 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3550 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3551 return [self popErrorWithTitle:title] || !success;
3554 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3555 @synchronized (self) {
3558 [self releasePackages];
3561 [sourceList_ removeAllObjects];
3581 apr_pool_clear(pool_);
3583 NSRecycleZone(zone_);
3584 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3586 int chk(creat("/tmp/cydia.chk", 0644));
3590 if (invocation != nil)
3591 [invocation invoke];
3593 NSString *title(UCLocalize("DATABASE"));
3595 list_ = new pkgSourceList();
3596 _profile(reloadDataWithInvocation$ReadMainList)
3597 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3601 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3602 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3603 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3604 [sourceList_ addObject:object];
3609 OpProgress progress;
3612 _profile(reloadDataWithInvocation$pkgCacheFile)
3613 opened = cache_.Open(progress, true);
3616 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3617 while (!_error->empty()) {
3619 bool warning(!_error->PopMessage(error));
3621 lprintf("cache_.Open():[%s]\n", error.c_str());
3623 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3627 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3628 repair = @selector(configure);
3629 //else if (error == "The package lists or status file could not be parsed or opened.")
3630 // repair = @selector(update);
3631 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3632 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3633 // else if (error == "Malformed Status line")
3634 // else if (error == "The list of sources could not be read.")
3636 if (repair != NULL) {
3638 [delegate_ repairWithSelector:repair];
3647 unlink("/tmp/cydia.chk");
3649 now_ = [[NSDate date] timeIntervalSince1970];
3651 policy_ = new pkgDepCache::Policy();
3652 records_ = new pkgRecords(cache_);
3653 resolver_ = new pkgProblemResolver(cache_);
3654 fetcher_ = new pkgAcquire(&status_);
3657 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3658 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3662 _profile(reloadDataWithInvocation$pkgApplyStatus)
3663 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3667 if (cache_->BrokenCount() != 0) {
3668 _profile(pkgApplyStatus$pkgFixBroken)
3669 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3673 if (cache_->BrokenCount() != 0) {
3674 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3678 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3679 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3684 for (Source *object in (id) sourceList_) {
3685 metaIndex *source([object metaIndex]);
3686 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3687 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3688 // XXX: this could be more intelligent
3689 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3690 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3692 sourceMap_[cached->ID] = object;
3697 /*std::vector<Package *> packages;
3698 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3701 _profile(reloadDataWithInvocation$packageWithIterator)
3702 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3703 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3704 //packages.push_back(package);
3705 CFArrayAppendValue(packages_, CFRetain(package));
3709 /*if (packages.empty())
3710 packages_ = [[NSArray alloc] init];
3712 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3715 _profile(reloadDataWithInvocation$radix$8)
3716 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3719 _profile(reloadDataWithInvocation$radix$4)
3720 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3723 _profile(reloadDataWithInvocation$radix$0)
3724 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3727 _profile(reloadDataWithInvocation$insertion)
3728 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3731 /*_profile(reloadDataWithInvocation$CFQSortArray)
3732 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3735 /*_profile(reloadDataWithInvocation$stdsort)
3736 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3739 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3740 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3743 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3744 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3748 size_t count(CFArrayGetCount(packages_));
3749 MetaFile_->active_ = count;
3750 for (size_t index(0); index != count; ++index)
3751 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3756 @synchronized (self) {
3758 resolver_ = new pkgProblemResolver(cache_);
3760 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3761 if (!cache_[iterator].Keep())
3762 cache_->MarkKeep(iterator, false);
3763 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3764 cache_->SetReInstall(iterator, false);
3767 - (void) configure {
3768 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3770 system([dpkg UTF8String]);
3775 @synchronized (self) {
3776 // XXX: I don't remember this condition
3781 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3783 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3785 if ([self popErrorWithTitle:title])
3789 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3791 CydiaLogCleaner cleaner;
3792 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3799 fetcher_->Shutdown();
3801 pkgRecords records(cache_);
3803 lock_ = new FileFd();
3804 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3806 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3808 if ([self popErrorWithTitle:title])
3812 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3815 manager_ = (_system->CreatePM(cache_));
3816 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3823 bool substrate(RestartSubstrate_);
3824 RestartSubstrate_ = false;
3826 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3828 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3830 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3832 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3833 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3836 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3838 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3840 [self popErrorWithTitle:title];
3844 bool failed = false;
3845 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3846 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3848 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3851 std::string uri = (*item)->DescURI();
3852 std::string error = (*item)->ErrorText;
3854 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3857 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3858 [delegate_ addProgressEventOnMainThread:event forTask:title];
3861 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3869 RestartSubstrate_ = true;
3872 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3873 if ([self popErrorWithTitle:title])
3876 if (result == pkgPackageManager::Failed) {
3881 if (result != pkgPackageManager::Completed) {
3886 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3888 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3890 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3891 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3894 if (![before isEqualToArray:after])
3899 NSString *title(UCLocalize("UPGRADE"));
3900 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3906 [self updateWithStatus:status_];
3909 - (void) updateWithStatus:(CancelStatus &)status {
3910 NSString *title(UCLocalize("REFRESHING_DATA"));
3913 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3917 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3918 if ([self popErrorWithTitle:title])
3921 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3923 bool success(ListUpdate(status, list, PulseInterval_));
3924 if (status.WasCancelled())
3927 [self popErrorWithTitle:title forOperation:success];
3928 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3932 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3935 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3936 delegate_ = delegate;
3939 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3940 progress_ = delegate;
3941 status_.setDelegate(delegate);
3944 - (NSObject<ProgressDelegate> *) progressDelegate {
3948 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3949 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3950 return i == sourceMap_.end() ? nil : i->second;
3953 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
3954 for (Source *source in (id) sourceList_)
3955 [source setFetch:fetch forURI:uri];
3958 - (void) resetFetch {
3959 for (Source *source in (id) sourceList_)
3960 [source resetFetch];
3963 - (NSString *) mappedSectionForPointer:(const char *)section {
3964 _H<NSString> *mapped;
3966 _profile(Database$mappedSectionForPointer$Cache)
3967 mapped = §ions_[section];
3970 if (*mapped == NULL) {
3971 size_t length(strlen(section));
3972 char spaced[length + 1];
3974 _profile(Database$mappedSectionForPointer$Replace)
3975 for (size_t index(0); index != length; ++index)
3976 spaced[index] = section[index] == '_' ? ' ' : section[index];
3977 spaced[length] = '\0';
3982 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3983 string = [NSString stringWithUTF8String:spaced];
3986 _profile(Database$mappedSectionForPointer$Map)
3987 string = [SectionMap_ objectForKey:string] ?: string;
3997 static _H<NSMutableSet> Diversions_;
3999 @interface Diversion : NSObject {
4002 _H<NSString> format_;
4007 @implementation Diversion
4009 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4010 if ((self = [super init]) != nil) {
4011 pattern_ = [from UTF8String];
4017 - (NSString *) divert:(NSString *)url {
4018 return !pattern_(url) ? nil : pattern_->*format_;
4021 + (NSURL *) divertURL:(NSURL *)url {
4023 NSString *href([url absoluteString]);
4025 for (Diversion *diversion in (id) Diversions_)
4026 if (NSString *diverted = [diversion divert:href]) {
4028 NSLog(@"div: %@", diverted);
4030 url = [NSURL URLWithString:diverted];
4037 - (NSString *) key {
4041 - (NSUInteger) hash {
4045 - (BOOL) isEqual:(Diversion *)object {
4046 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4051 @interface CydiaObject : NSObject {
4052 _H<CyteWebViewController> indirect_;
4053 _transient id delegate_;
4056 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4062 @interface CydiaWebViewController : CyteWebViewController {
4063 _H<CydiaObject> cydia_;
4066 + (void) addDiversion:(Diversion *)diversion;
4067 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4068 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4069 - (void) setDelegate:(id)delegate;
4073 /* Web Scripting {{{ */
4074 @implementation CydiaObject
4076 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4077 if ((self = [super init]) != nil) {
4078 indirect_ = (CyteWebViewController *) indirect;
4082 - (void) setDelegate:(id)delegate {
4083 delegate_ = delegate;
4086 + (NSArray *) _attributeKeys {
4087 return [NSArray arrayWithObjects:
4090 @"coreFoundationVersionNumber",
4107 - (NSArray *) attributeKeys {
4108 return [[self class] _attributeKeys];
4111 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4112 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4115 - (NSString *) version {
4119 - (NSString *) build {
4123 - (NSString *) coreFoundationVersionNumber {
4124 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4127 - (NSString *) device {
4128 return UniqueIdentifier();
4131 - (NSString *) firmware {
4132 return [[UIDevice currentDevice] systemVersion];
4135 - (NSString *) hostname {
4136 return [[UIDevice currentDevice] name];
4139 - (NSString *) idiom {
4140 return (id) Idiom_ ?: [NSNull null];
4143 - (NSString *) mcc {
4144 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4145 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4149 - (NSString *) mnc {
4150 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4151 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4155 - (NSString *) operator {
4156 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4157 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4161 - (NSString *) bbsnum {
4162 return (id) BBSNum_ ?: [NSNull null];
4165 - (NSString *) ecid {
4166 return (id) ChipID_ ?: [NSNull null];
4169 - (NSString *) serial {
4170 return SerialNumber_;
4173 - (NSString *) role {
4174 return (id) [NSNull null];
4177 - (NSString *) model {
4178 return [NSString stringWithUTF8String:Machine_];
4181 - (NSString *) token {
4182 return (id) Token_ ?: [NSNull null];
4185 + (NSString *) webScriptNameForSelector:(SEL)selector {
4187 else if (selector == @selector(addBridgedHost:))
4188 return @"addBridgedHost";
4189 else if (selector == @selector(addInsecureHost:))
4190 return @"addInsecureHost";
4191 else if (selector == @selector(addInternalRedirect::))
4192 return @"addInternalRedirect";
4193 else if (selector == @selector(addPipelinedHost:scheme:))
4194 return @"addPipelinedHost";
4195 else if (selector == @selector(addSource:::))
4196 return @"addSource";
4197 else if (selector == @selector(addTokenHost:))
4198 return @"addTokenHost";
4199 else if (selector == @selector(addTrivialSource:))
4200 return @"addTrivialSource";
4201 else if (selector == @selector(close))
4203 else if (selector == @selector(du:))
4205 else if (selector == @selector(stringWithFormat:arguments:))
4207 else if (selector == @selector(getAllSources))
4208 return @"getAllSources";
4209 else if (selector == @selector(getApplicationInfo:value:))
4210 return @"getApplicationInfoValue";
4211 else if (selector == @selector(getKernelNumber:))
4212 return @"getKernelNumber";
4213 else if (selector == @selector(getKernelString:))
4214 return @"getKernelString";
4215 else if (selector == @selector(getInstalledPackages))
4216 return @"getInstalledPackages";
4217 else if (selector == @selector(getIORegistryEntry::))
4218 return @"getIORegistryEntry";
4219 else if (selector == @selector(getLocaleIdentifier))
4220 return @"getLocaleIdentifier";
4221 else if (selector == @selector(getPreferredLanguages))
4222 return @"getPreferredLanguages";
4223 else if (selector == @selector(getPackageById:))
4224 return @"getPackageById";
4225 else if (selector == @selector(getMetadataKeys))
4226 return @"getMetadataKeys";
4227 else if (selector == @selector(getMetadataValue:))
4228 return @"getMetadataValue";
4229 else if (selector == @selector(getSessionValue:))
4230 return @"getSessionValue";
4231 else if (selector == @selector(installPackages:))
4232 return @"installPackages";
4233 else if (selector == @selector(isReachable:))
4234 return @"isReachable";
4235 else if (selector == @selector(localizedStringForKey:value:table:))
4237 else if (selector == @selector(popViewController:))
4238 return @"popViewController";
4239 else if (selector == @selector(refreshSources))
4240 return @"refreshSources";
4241 else if (selector == @selector(registerFrame:))
4242 return @"registerFrame";
4243 else if (selector == @selector(removeButton))
4244 return @"removeButton";
4245 else if (selector == @selector(saveConfig))
4246 return @"saveConfig";
4247 else if (selector == @selector(setMetadataValue::))
4248 return @"setMetadataValue";
4249 else if (selector == @selector(setSessionValue::))
4250 return @"setSessionValue";
4251 else if (selector == @selector(substitutePackageNames:))
4252 return @"substitutePackageNames";
4253 else if (selector == @selector(scrollToBottom:))
4254 return @"scrollToBottom";
4255 else if (selector == @selector(setAllowsNavigationAction:))
4256 return @"setAllowsNavigationAction";
4257 else if (selector == @selector(setBadgeValue:))
4258 return @"setBadgeValue";
4259 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4260 return @"setButtonImage";
4261 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4262 return @"setButtonTitle";
4263 else if (selector == @selector(setHidesBackButton:))
4264 return @"setHidesBackButton";
4265 else if (selector == @selector(setHidesNavigationBar:))
4266 return @"setHidesNavigationBar";
4267 else if (selector == @selector(setNavigationBarStyle:))
4268 return @"setNavigationBarStyle";
4269 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4270 return @"setNavigationBarTintColor";
4271 else if (selector == @selector(setPasteboardString:))
4272 return @"setPasteboardString";
4273 else if (selector == @selector(setPasteboardURL:))
4274 return @"setPasteboardURL";
4275 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4276 return @"setScrollAlwaysBounceVertical";
4277 else if (selector == @selector(setScrollIndicatorStyle:))
4278 return @"setScrollIndicatorStyle";
4279 else if (selector == @selector(setToken:))
4281 else if (selector == @selector(setViewportWidth:))
4282 return @"setViewportWidth";
4283 else if (selector == @selector(statfs:))
4285 else if (selector == @selector(supports:))
4287 else if (selector == @selector(unload))
4293 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4294 return [self webScriptNameForSelector:selector] == nil;
4297 - (BOOL) supports:(NSString *)feature {
4298 return [feature isEqualToString:@"window.open"];
4302 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4305 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4306 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4309 - (void) setScrollIndicatorStyle:(NSString *)style {
4310 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4313 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4314 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4317 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4319 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4320 return (id) [NSNull null];
4321 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4323 return (id) [NSNull null];
4324 return [info objectForKey:key];
4327 - (NSNumber *) getKernelNumber:(NSString *)name {
4328 const char *string([name UTF8String]);
4331 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4332 return (id) [NSNull null];
4334 if (size != sizeof(int))
4335 return (id) [NSNull null];
4338 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4339 return (id) [NSNull null];
4341 return [NSNumber numberWithInt:value];
4344 - (NSString *) getKernelString:(NSString *)name {
4345 const char *string([name UTF8String]);
4348 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4349 return (id) [NSNull null];
4351 char value[size + 1];
4352 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4353 return (id) [NSNull null];
4355 // XXX: just in case you request something ludicrous
4358 return [NSString stringWithCString:value];
4361 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4362 NSObject *value(CYIOGetValue([path UTF8String], entry));
4365 if ([value isKindOfClass:[NSData class]])
4366 value = CYHex((NSData *) value);
4371 - (NSArray *) getMetadataKeys {
4372 @synchronized (Values_) {
4373 return [Values_ allKeys];
4376 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4377 WebFrame *frame([iframe contentFrame]);
4378 [indirect_ registerFrame:frame];
4381 - (id) getMetadataValue:(NSString *)key {
4382 @synchronized (Values_) {
4383 return [Values_ objectForKey:key];
4386 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4387 @synchronized (Values_) {
4388 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4389 [Values_ removeObjectForKey:key];
4391 [Values_ setObject:value forKey:key];
4393 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4396 - (id) getSessionValue:(NSString *)key {
4397 @synchronized (SessionData_) {
4398 return [SessionData_ objectForKey:key];
4401 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4402 @synchronized (SessionData_) {
4403 if (value == (id) [WebUndefined undefined])
4404 [SessionData_ removeObjectForKey:key];
4406 [SessionData_ setObject:value forKey:key];
4409 - (void) addBridgedHost:(NSString *)host {
4410 @synchronized (HostConfig_) {
4411 [BridgedHosts_ addObject:host];
4414 - (void) addInsecureHost:(NSString *)host {
4415 @synchronized (HostConfig_) {
4416 [InsecureHosts_ addObject:host];
4419 - (void) addTokenHost:(NSString *)host {
4420 @synchronized (HostConfig_) {
4421 [TokenHosts_ addObject:host];
4424 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4425 @synchronized (HostConfig_) {
4426 if (scheme != (id) [WebUndefined undefined])
4427 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4429 [PipelinedHosts_ addObject:host];
4432 - (void) popViewController:(NSNumber *)value {
4433 if (value == (id) [WebUndefined undefined])
4434 value = [NSNumber numberWithBool:YES];
4435 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4438 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4439 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4441 for (NSString *section in sections)
4442 [array addObject:section];
4444 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4447 distribution, @"Distribution",
4449 nil] waitUntilDone:NO];
4452 - (void) addTrivialSource:(NSString *)href {
4453 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4456 - (void) refreshSources {
4457 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4460 - (void) saveConfig {
4461 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4464 - (NSArray *) getAllSources {
4465 return [[Database sharedInstance] sources];
4468 - (NSArray *) getInstalledPackages {
4469 Database *database([Database sharedInstance]);
4470 @synchronized (database) {
4471 NSArray *packages([database packages]);
4472 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4473 for (Package *package in packages)
4474 if (![package uninstalled])
4475 [installed addObject:package];
4479 - (Package *) getPackageById:(NSString *)id {
4480 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4484 return (Package *) [NSNull null];
4487 - (NSString *) getLocaleIdentifier {
4488 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4491 - (NSArray *) getPreferredLanguages {
4495 - (NSArray *) statfs:(NSString *)path {
4498 if (path == nil || statfs([path UTF8String], &stat) == -1)
4501 return [NSArray arrayWithObjects:
4502 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4503 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4504 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4508 - (NSNumber *) du:(NSString *)path {
4509 NSNumber *value(nil);
4512 _assert(pipe(fds) != -1);
4514 pid_t pid(ExecFork());
4516 _assert(dup2(fds[1], 1) != -1);
4517 _assert(close(fds[0]) != -1);
4518 _assert(close(fds[1]) != -1);
4519 /* XXX: this should probably not use du */
4520 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4523 _assert(close(fds[1]) != -1);
4525 if (FILE *du = fdopen(fds[0], "r")) {
4527 while (fgets(line, sizeof(line), du) != NULL) {
4528 size_t length(strlen(line));
4529 while (length != 0 && line[length - 1] == '\n')
4530 line[--length] = '\0';
4531 if (char *tab = strchr(line, '\t')) {
4533 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4539 _assert(close(fds[0]) != -1);
4546 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4549 - (NSNumber *) isReachable:(NSString *)name {
4550 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4553 - (void) installPackages:(NSArray *)packages {
4554 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4557 - (NSString *) substitutePackageNames:(NSString *)message {
4558 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4559 for (size_t i(0), e([words count]); i != e; ++i) {
4560 NSString *word([words objectAtIndex:i]);
4561 if (Package *package = [[Database sharedInstance] packageWithName:word])
4562 [words replaceObjectAtIndex:i withObject:[package name]];
4565 return [words componentsJoinedByString:@" "];
4568 - (void) removeButton {
4569 [indirect_ removeButton];
4572 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4573 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4576 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4577 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4580 - (void) setBadgeValue:(id)value {
4581 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4584 - (void) setAllowsNavigationAction:(NSString *)value {
4585 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4588 - (void) setHidesBackButton:(NSString *)value {
4589 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4592 - (void) setHidesNavigationBar:(NSString *)value {
4593 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4596 - (void) setNavigationBarStyle:(NSString *)value {
4597 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4600 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4601 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4602 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4603 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4606 - (void) setPasteboardString:(NSString *)value {
4607 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4610 - (void) setPasteboardURL:(NSString *)value {
4611 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4614 - (void) _setToken:(NSString *)token {
4618 [Metadata_ removeObjectForKey:@"Token"];
4620 [Metadata_ setObject:Token_ forKey:@"Token"];
4625 - (void) setToken:(NSString *)token {
4626 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4629 - (void) scrollToBottom:(NSNumber *)animated {
4630 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4633 - (void) setViewportWidth:(float)width {
4634 [indirect_ setViewportWidthOnMainThread:width];
4637 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4638 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4639 unsigned count([arguments count]);
4641 for (unsigned i(0); i != count; ++i)
4642 values[i] = [arguments objectAtIndex:i];
4643 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4646 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4647 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4649 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4651 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4657 @interface NSURL (CydiaSecure)
4660 @implementation NSURL (CydiaSecure)
4662 - (bool) isCydiaSecure {
4663 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4666 @synchronized (HostConfig_) {
4667 if ([InsecureHosts_ containsObject:[self host]])
4676 /* Cydia Browser Controller {{{ */
4677 @implementation CydiaWebViewController
4679 - (NSURL *) navigationURL {
4680 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4683 + (void) _initialize {
4684 [super _initialize];
4686 Diversions_ = [NSMutableSet setWithCapacity:0];
4689 + (void) addDiversion:(Diversion *)diversion {
4690 [Diversions_ addObject:diversion];
4693 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4694 [super webView:view didClearWindowObject:window forFrame:frame];
4695 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4698 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4699 WebDataSource *source([frame dataSource]);
4700 NSURLResponse *response([source response]);
4701 NSURL *url([response URL]);
4702 NSString *scheme([[url scheme] lowercaseString]);
4704 bool bridged(false);
4706 @synchronized (HostConfig_) {
4707 if ([scheme isEqualToString:@"file"])
4709 else if ([scheme isEqualToString:@"https"])
4710 if ([BridgedHosts_ containsObject:[url host]])
4715 [window setValue:cydia forKey:@"cydia"];
4718 - (void) _setupMail:(MFMailComposeViewController *)controller {
4719 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4721 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4722 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4725 - (NSURL *) URLWithURL:(NSURL *)url {
4726 return [Diversion divertURL:url];
4729 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4730 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4733 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4734 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4736 NSURL *url([copy URL]);
4737 NSString *href([url absoluteString]);
4738 NSString *host([url host]);
4740 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4741 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4742 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4743 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4746 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4747 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4749 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4753 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4754 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4755 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4756 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4761 @synchronized (HostConfig_) {
4762 bridged = [BridgedHosts_ containsObject:host];
4763 token = [TokenHosts_ containsObject:host];
4766 if ([url isCydiaSecure]) {
4768 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4769 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4771 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4772 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4779 - (void) setDelegate:(id)delegate {
4780 [super setDelegate:delegate];
4781 [cydia_ setDelegate:delegate];
4784 - (NSString *) applicationNameForUserAgent {
4789 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4790 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4796 @interface AppCacheController : CydiaWebViewController {
4801 @implementation AppCacheController
4803 - (void) didReceiveMemoryWarning {
4804 // XXX: this doesn't work
4807 - (bool) retainsNetworkActivityIndicator {
4815 @interface NSObject (CydiaScript)
4816 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4819 @implementation NSObject (CydiaScript)
4821 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4827 @implementation NSArray (CydiaScript)
4829 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4830 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4831 for (size_t i(0), e([self count]); i != e; ++i)
4832 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4838 @implementation NSDictionary (CydiaScript)
4840 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4841 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4843 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4850 /* Confirmation Controller {{{ */
4851 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4852 if (!iterator.end())
4853 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4854 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4856 pkgCache::PkgIterator package(dep.TargetPkg());
4859 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4866 @protocol ConfirmationControllerDelegate
4867 - (void) cancelAndClear:(bool)clear;
4868 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4872 @interface ConfirmationController : CydiaWebViewController {
4873 _transient Database *database_;
4875 _H<UIAlertView> essential_;
4877 _H<NSDictionary> changes_;
4878 _H<NSMutableArray> issues_;
4879 _H<NSDictionary> sizes_;
4884 - (id) initWithDatabase:(Database *)database;
4888 @implementation ConfirmationController
4892 RestartSubstrate_ = true;
4893 [delegate_ confirmWithNavigationController:[self navigationController]];
4896 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4897 NSString *context([alert context]);
4899 if ([context isEqualToString:@"remove"]) {
4900 if (button == [alert cancelButtonIndex])
4901 [self dismissModalViewControllerAnimated:YES];
4902 else if (button == [alert firstOtherButtonIndex]) {
4903 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
4906 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4907 } else if ([context isEqualToString:@"unable"]) {
4908 [self dismissModalViewControllerAnimated:YES];
4909 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4911 [super alertView:alert clickedButtonAtIndex:button];
4915 - (void) _doContinue {
4916 [delegate_ cancelAndClear:NO];
4917 [self dismissModalViewControllerAnimated:YES];
4920 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4921 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4925 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4926 [super webView:view didClearWindowObject:window forFrame:frame];
4928 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4929 (id) changes_, @"changes",
4930 (id) issues_, @"issues",
4931 (id) sizes_, @"sizes",
4933 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4936 - (id) initWithDatabase:(Database *)database {
4937 if ((self = [super init]) != nil) {
4938 database_ = database;
4940 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4941 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4942 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4943 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4944 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4948 pkgCacheFile &cache([database_ cache]);
4949 NSArray *packages([database_ packages]);
4950 pkgDepCache::Policy *policy([database_ policy]);
4952 issues_ = [NSMutableArray arrayWithCapacity:4];
4954 for (Package *package in packages) {
4955 pkgCache::PkgIterator iterator([package iterator]);
4956 NSString *name([package id]);
4958 if ([package broken]) {
4959 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4961 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4963 reasons, @"reasons",
4966 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4970 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4971 pkgCache::DepIterator start;
4972 pkgCache::DepIterator end;
4973 dep.GlobOr(start, end); // ++dep
4975 if (!cache->IsImportantDep(end))
4977 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4980 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4982 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4983 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4984 clauses, @"clauses",
4988 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4990 pkgCache::PkgIterator target(start.TargetPkg());
4991 if (target->ProvidesList != 0)
4992 reason = @"missing";
4994 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4996 reason = @"installed";
4997 installed = [NSString stringWithUTF8String:ver.VerStr()];
4998 } else if (!cache[target].CandidateVerIter(cache).end())
4999 reason = @"uninstalled";
5000 else if (target->ProvidesList == 0)
5001 reason = @"uninstallable";
5003 reason = @"virtual";
5006 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5007 [NSString stringWithUTF8String:start.CompType()], @"operator",
5008 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5011 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5012 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5013 version, @"version",
5015 installed, @"installed",
5018 // yes, seriously. (wtf?)
5026 pkgDepCache::StateCache &state(cache[iterator]);
5028 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
5030 if (state.NewInstall())
5031 [installs addObject:name];
5032 // XXX: else if (state.Install())
5033 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5034 [reinstalls addObject:name];
5035 // XXX: move before previous if
5036 else if (state.Upgrade())
5037 [upgrades addObject:name];
5038 else if (state.Downgrade())
5039 [downgrades addObject:name];
5040 else if (!state.Delete())
5041 // XXX: _assert(state.Keep());
5043 else if (special_r(name))
5044 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5045 [NSNull null], @"package",
5046 [NSArray arrayWithObjects:
5047 [NSDictionary dictionaryWithObjectsAndKeys:
5048 @"Conflicts", @"relationship",
5049 [NSArray arrayWithObjects:
5050 [NSDictionary dictionaryWithObjectsAndKeys:
5052 [NSNull null], @"version",
5053 @"installed", @"reason",
5060 if ([package essential])
5062 [removes addObject:name];
5065 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5066 substrate_ |= DepSubstrate(iterator.CurrentVer());
5071 else if (Advanced_) {
5072 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5074 essential_ = [[[UIAlertView alloc]
5075 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5076 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5078 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5080 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5084 [essential_ setContext:@"remove"];
5085 [essential_ setNumberOfRows:2];
5087 essential_ = [[[UIAlertView alloc]
5088 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5089 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5091 cancelButtonTitle:UCLocalize("OKAY")
5092 otherButtonTitles:nil
5095 [essential_ setContext:@"unable"];
5098 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5099 installs, @"installs",
5100 reinstalls, @"reinstalls",
5101 upgrades, @"upgrades",
5102 downgrades, @"downgrades",
5103 removes, @"removes",
5106 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5107 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5108 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5111 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5115 - (UIBarButtonItem *) leftButton {
5116 return [[[UIBarButtonItem alloc]
5117 initWithTitle:UCLocalize("CANCEL")
5118 style:UIBarButtonItemStylePlain
5120 action:@selector(cancelButtonClicked)
5125 - (void) applyRightButton {
5126 if ([issues_ count] == 0 && ![self isLoading])
5127 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5128 initWithTitle:UCLocalize("CONFIRM")
5129 style:UIBarButtonItemStyleDone
5131 action:@selector(confirmButtonClicked)
5134 [[self navigationItem] setRightBarButtonItem:nil];
5138 - (void) cancelButtonClicked {
5139 [delegate_ cancelAndClear:YES];
5140 [self dismissModalViewControllerAnimated:YES];
5144 - (void) confirmButtonClicked {
5145 if (essential_ != nil)
5155 /* Progress Data {{{ */
5156 @interface CydiaProgressData : NSObject {
5157 _transient id delegate_;
5166 _H<NSMutableArray> events_;
5167 _H<NSString> title_;
5169 _H<NSString> status_;
5170 _H<NSString> finish_;
5175 @implementation CydiaProgressData
5177 + (NSArray *) _attributeKeys {
5178 return [NSArray arrayWithObjects:
5190 - (NSArray *) attributeKeys {
5191 return [[self class] _attributeKeys];
5194 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5195 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5199 if ((self = [super init]) != nil) {
5200 events_ = [NSMutableArray arrayWithCapacity:32];
5208 - (void) setDelegate:(id)delegate {
5209 delegate_ = delegate;
5212 - (void) setPercent:(float)value {
5216 - (NSNumber *) percent {
5217 return [NSNumber numberWithFloat:percent_];
5220 - (void) setCurrent:(float)value {
5224 - (NSNumber *) current {
5225 return [NSNumber numberWithFloat:current_];
5228 - (void) setTotal:(float)value {
5232 - (NSNumber *) total {
5233 return [NSNumber numberWithFloat:total_];
5236 - (void) setSpeed:(float)value {
5240 - (NSNumber *) speed {
5241 return [NSNumber numberWithFloat:speed_];
5244 - (NSArray *) events {
5248 - (void) removeAllEvents {
5249 [events_ removeAllObjects];
5252 - (void) addEvent:(CydiaProgressEvent *)event {
5253 [events_ addObject:event];
5256 - (void) setTitle:(NSString *)text {
5260 - (NSString *) title {
5264 - (void) setFinish:(NSString *)text {
5268 - (NSString *) finish {
5269 return (id) finish_ ?: [NSNull null];
5272 - (void) setRunning:(bool)running {
5276 - (NSNumber *) running {
5277 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5282 /* Progress Controller {{{ */
5283 @interface ProgressController : CydiaWebViewController <
5286 _transient Database *database_;
5287 _H<CydiaProgressData, 1> progress_;
5291 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5293 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5295 - (void) setTitle:(NSString *)title;
5296 - (void) setCancellable:(bool)cancellable;
5300 @implementation ProgressController
5303 [database_ setProgressDelegate:nil];
5307 - (UIBarButtonItem *) leftButton {
5308 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5309 initWithTitle:UCLocalize("CANCEL")
5310 style:UIBarButtonItemStylePlain
5312 action:@selector(cancel)
5313 ] autorelease] : nil;
5316 - (void) updateCancel {
5317 [super applyLeftButton];
5320 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5321 if ((self = [super init]) != nil) {
5322 database_ = database;
5323 delegate_ = delegate;
5325 [database_ setProgressDelegate:self];
5327 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5328 [progress_ setDelegate:self];
5330 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5332 [scroller_ setBackgroundColor:[UIColor blackColor]];
5334 [[self navigationItem] setHidesBackButton:YES];
5336 [self updateCancel];
5340 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5341 [super webView:view didClearWindowObject:window forFrame:frame];
5342 [window setValue:progress_ forKey:@"cydiaProgress"];
5345 - (void) updateProgress {
5346 [self dispatchEvent:@"CydiaProgressUpdate"];
5349 - (void) viewWillAppear:(BOOL)animated {
5350 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5351 [super viewWillAppear:animated];
5354 - (void) reloadSpringBoard {
5355 if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
5356 system("/bin/launchctl stop com.apple.backboardd");
5358 system("/usr/bin/killall backboardd SpringBoard sbreload");
5362 pid_t pid(ExecFork());
5367 pid_t pid(ExecFork());
5369 execl("/usr/bin/sbreload", "sbreload", NULL);
5379 system("/usr/bin/killall backboardd SpringBoard sbreload");
5383 UpdateExternalStatus(0);
5386 [delegate_ saveState];
5390 [delegate_ returnToCydia];
5394 [delegate_ terminateWithSuccess];
5395 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5396 [delegate_ suspendWithAnimation:YES];
5398 [delegate_ suspend];*/
5410 UIProgressHUD *hud([delegate_ addProgressHUD]);
5411 [hud setText:UCLocalize("LOADING")];
5412 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5418 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5419 SBReboot(SBSSpringBoardServerPort());
5421 reboot2(RB_AUTOBOOT);
5428 - (void) setTitle:(NSString *)title {
5429 [progress_ setTitle:title];
5430 [self updateProgress];
5433 - (UIBarButtonItem *) rightButton {
5434 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5435 initWithTitle:UCLocalize("CLOSE")
5436 style:UIBarButtonItemStylePlain
5438 action:@selector(close)
5442 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5443 UpdateExternalStatus(1);
5445 [progress_ setRunning:true];
5446 [self setTitle:title];
5447 // implicit updateProgress
5449 SHA1SumValue notifyconf; {
5451 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5454 MMap mmap(file, MMap::ReadOnly);
5456 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5457 notifyconf = sha1.Result();
5461 SHA1SumValue springlist; {
5463 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5466 MMap mmap(file, MMap::ReadOnly);
5468 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5469 springlist = sha1.Result();
5473 if (invocation != nil) {
5474 [invocation yieldToSelector:@selector(invoke)];
5475 [self setTitle:@"COMPLETE"];
5480 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5483 MMap mmap(file, MMap::ReadOnly);
5485 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5486 if (!(notifyconf == sha1.Result()))
5493 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5496 MMap mmap(file, MMap::ReadOnly);
5498 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5499 if (!(springlist == sha1.Result()))
5505 if (RestartSubstrate_)
5509 RestartSubstrate_ = false;
5512 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5513 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5514 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5515 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5516 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5519 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5521 [progress_ setRunning:false];
5522 [self updateProgress];
5524 [self applyRightButton];
5527 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5528 [progress_ addEvent:event];
5529 [self updateProgress];
5532 - (bool) isProgressCancelled {
5533 return cancel_ == 2;
5538 [self updateCancel];
5541 - (void) setCancellable:(bool)cancellable {
5542 unsigned cancel(cancel_);
5546 else if (cancel_ == 0)
5549 if (cancel != cancel_)
5550 [self updateCancel];
5553 - (void) setProgressCancellable:(NSNumber *)cancellable {
5554 [self setCancellable:[cancellable boolValue]];
5557 - (void) setProgressPercent:(NSNumber *)percent {
5558 [progress_ setPercent:[percent floatValue]];
5559 [self updateProgress];
5562 - (void) setProgressStatus:(NSDictionary *)status {
5563 if (status == nil) {
5564 [progress_ setCurrent:0];
5565 [progress_ setTotal:0];
5566 [progress_ setSpeed:0];
5568 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5570 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5571 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5572 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5575 [self updateProgress];
5581 /* Package Cell {{{ */
5582 @interface PackageCell : CyteTableViewCell <
5583 CyteTableViewCellDelegate
5587 _H<NSString> description_;
5589 _H<NSString> source_;
5591 _H<UIImage> placard_;
5595 - (PackageCell *) init;
5596 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5598 - (void) drawContentRect:(CGRect)rect;
5602 @implementation PackageCell
5604 - (PackageCell *) init {
5605 CGRect frame(CGRectMake(0, 0, 320, 74));
5606 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5607 UIView *content([self contentView]);
5608 CGRect bounds([content bounds]);
5610 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5611 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5612 [content addSubview:content_];
5614 [content_ setDelegate:self];
5615 [content_ setOpaque:YES];
5619 - (NSString *) accessibilityLabel {
5623 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5624 summarized_ = summary;
5634 [content_ setBackgroundColor:[UIColor whiteColor]];
5638 Source *source = [package source];
5640 icon_ = [package icon];
5642 if (NSString *name = [package name])
5643 name_ = [NSString stringWithString:name];
5645 if (NSString *description = [package shortDescription])
5646 description_ = [NSString stringWithString:description];
5648 commercial_ = [package isCommercial];
5650 NSString *label = nil;
5651 bool trusted = false;
5653 if (source != nil) {
5654 label = [source label];
5655 trusted = [source trusted];
5656 } else if ([[package id] isEqualToString:@"firmware"])
5657 label = UCLocalize("APPLE");
5659 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5661 NSString *from(label);
5663 NSString *section = [package simpleSection];
5664 if (section != nil && ![section isEqualToString:label]) {
5665 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5666 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5669 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5671 if (NSString *purpose = [package primaryPurpose])
5672 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5677 if (NSString *mode = [package mode]) {
5678 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5679 color = RemovingColor_;
5680 placard = @"removing";
5682 color = InstallingColor_;
5683 placard = @"installing";
5686 color = [UIColor whiteColor];
5688 if ([package installed] != nil)
5689 placard = @"installed";
5694 [content_ setBackgroundColor:color];
5697 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5700 [self setNeedsDisplay];
5701 [content_ setNeedsDisplay];
5704 - (void) drawSummaryContentRect:(CGRect)rect {
5705 bool highlighted(highlighted_);
5706 float width([self bounds].size.width);
5710 rect.size = [(UIImage *) icon_ size];
5712 while (rect.size.width > 16 || rect.size.height > 16) {
5713 rect.size.width /= 2;
5714 rect.size.height /= 2;
5717 rect.origin.x = 19 - rect.size.width / 2;
5718 rect.origin.y = 19 - rect.size.height / 2;
5720 [icon_ drawInRect:rect];
5723 if (badge_ != nil) {
5725 rect.size = [(UIImage *) badge_ size];
5727 rect.size.width /= 4;
5728 rect.size.height /= 4;
5730 rect.origin.x = 25 - rect.size.width / 2;
5731 rect.origin.y = 25 - rect.size.height / 2;
5733 [badge_ drawInRect:rect];
5736 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5740 UISetColor(commercial_ ? Purple_ : Black_);
5741 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5743 if (placard_ != nil)
5744 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5747 - (void) drawNormalContentRect:(CGRect)rect {
5748 bool highlighted(highlighted_);
5749 float width([self bounds].size.width);
5753 rect.size = [(UIImage *) icon_ size];
5755 while (rect.size.width > 32 || rect.size.height > 32) {
5756 rect.size.width /= 2;
5757 rect.size.height /= 2;
5760 rect.origin.x = 25 - rect.size.width / 2;
5761 rect.origin.y = 25 - rect.size.height / 2;
5763 [icon_ drawInRect:rect];
5766 if (badge_ != nil) {
5768 rect.size = [(UIImage *) badge_ size];
5770 rect.size.width /= 2;
5771 rect.size.height /= 2;
5773 rect.origin.x = 36 - rect.size.width / 2;
5774 rect.origin.y = 36 - rect.size.height / 2;
5776 [badge_ drawInRect:rect];
5779 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5783 UISetColor(commercial_ ? Purple_ : Black_);
5784 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5785 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5788 UISetColor(commercial_ ? Purplish_ : Gray_);
5789 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
5791 if (placard_ != nil)
5792 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5795 - (void) drawContentRect:(CGRect)rect {
5797 [self drawSummaryContentRect:rect];
5799 [self drawNormalContentRect:rect];
5804 /* Section Cell {{{ */
5805 @interface SectionCell : CyteTableViewCell <
5806 CyteTableViewCellDelegate
5808 _H<NSString> basic_;
5809 _H<NSString> section_;
5811 _H<NSString> count_;
5813 _H<UISwitch> switch_;
5817 - (void) setSection:(Section *)section editing:(BOOL)editing;
5821 @implementation SectionCell
5823 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5824 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5825 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5826 // XXX: this initial frame is wrong, but is fixed later
5827 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5828 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5830 UIView *content([self contentView]);
5831 CGRect bounds([content bounds]);
5833 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5834 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5835 [content addSubview:content_];
5836 [content_ setBackgroundColor:[UIColor whiteColor]];
5838 [content_ setDelegate:self];
5842 - (void) onSwitch:(id)sender {
5843 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5844 if (metadata == nil) {
5845 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5846 [Sections_ setObject:metadata forKey:basic_];
5849 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5853 - (void) setSection:(Section *)section editing:(BOOL)editing {
5854 if (editing != editing_) {
5856 [switch_ removeFromSuperview];
5858 [self addSubview:switch_];
5867 if (section == nil) {
5868 name_ = UCLocalize("ALL_PACKAGES");
5871 basic_ = [section name];
5872 section_ = [section localized];
5874 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5875 count_ = [NSString stringWithFormat:@"%zd", [section count]];
5878 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5881 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5882 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5884 [content_ setNeedsDisplay];
5887 - (void) setFrame:(CGRect)frame {
5888 [super setFrame:frame];
5890 CGRect rect([switch_ frame]);
5891 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
5894 - (NSString *) accessibilityLabel {
5898 - (void) drawContentRect:(CGRect)rect {
5899 bool highlighted(highlighted_ && !editing_);
5901 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
5903 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5906 float width(rect.size.width);
5908 width -= 9 + [switch_ frame].size.width;
5912 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
5914 CGSize size = [count_ sizeWithFont:Font14_];
5916 UISetColor(Folder_);
5918 [count_ drawAtPoint:CGPointMake(10 + (30 - size.width) / 2, 18) withFont:Font12Bold_];
5924 /* File Table {{{ */
5925 @interface FileTable : CyteViewController <
5926 UITableViewDataSource,
5929 _transient Database *database_;
5930 _H<Package> package_;
5932 _H<NSMutableArray> files_;
5933 _H<UITableView, 2> list_;
5936 - (id) initWithDatabase:(Database *)database;
5937 - (void) setPackage:(Package *)package;
5941 @implementation FileTable
5943 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5944 return files_ == nil ? 0 : [files_ count];
5947 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5951 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5952 static NSString *reuseIdentifier = @"Cell";
5954 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5956 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5957 [cell setFont:[UIFont systemFontOfSize:16]];
5959 [cell setText:[files_ objectAtIndex:indexPath.row]];
5960 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5965 - (NSURL *) navigationURL {
5966 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5970 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5971 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5972 [list_ setRowHeight:24.0f];
5973 [(UITableView *) list_ setDataSource:self];
5974 [list_ setDelegate:self];
5975 [self setView:list_];
5978 - (void) viewDidLoad {
5979 [super viewDidLoad];
5981 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5984 - (void) releaseSubviews {
5990 [super releaseSubviews];
5993 - (id) initWithDatabase:(Database *)database {
5994 if ((self = [super init]) != nil) {
5995 database_ = database;
5999 - (void) setPackage:(Package *)package {
6003 files_ = [NSMutableArray arrayWithCapacity:32];
6005 if (package != nil) {
6007 name_ = [package id];
6009 if (NSArray *files = [package files])
6010 [files_ addObjectsFromArray:files];
6012 if ([files_ count] != 0) {
6013 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6014 [files_ removeObjectAtIndex:0];
6015 [files_ sortUsingSelector:@selector(compareByPath:)];
6017 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6018 [stack addObject:@"/"];
6020 for (int i(0), e([files_ count]); i != e; ++i) {
6021 NSString *file = [files_ objectAtIndex:i];
6022 while (![file hasPrefix:[stack lastObject]])
6023 [stack removeLastObject];
6024 NSString *directory = [stack lastObject];
6025 [stack addObject:[file stringByAppendingString:@"/"]];
6026 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6027 ([stack count] - 2) * 3, "",
6028 [file substringFromIndex:[directory length]]
6037 - (void) reloadData {
6040 [self setPackage:[database_ packageWithName:name_]];
6045 /* Package Controller {{{ */
6046 @interface CYPackageController : CydiaWebViewController <
6047 UIActionSheetDelegate
6049 _transient Database *database_;
6050 _H<Package> package_;
6053 _H<NSMutableArray> buttons_;
6054 _H<UIBarButtonItem> button_;
6057 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6061 @implementation CYPackageController
6063 - (NSURL *) navigationURL {
6064 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6067 /* XXX: this is not safe at all... localization of /fail/ */
6068 - (void) _clickButtonWithName:(NSString *)name {
6069 if ([name isEqualToString:UCLocalize("CLEAR")])
6070 [delegate_ clearPackage:package_];
6071 else if ([name isEqualToString:UCLocalize("INSTALL")])
6072 [delegate_ installPackage:package_];
6073 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6074 [delegate_ installPackage:package_];
6075 else if ([name isEqualToString:UCLocalize("REMOVE")])
6076 [delegate_ removePackage:package_];
6077 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6078 [delegate_ installPackage:package_];
6079 else _assert(false);
6082 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6083 NSString *context([sheet context]);
6085 if ([context isEqualToString:@"modify"]) {
6086 if (button != [sheet cancelButtonIndex]) {
6087 NSString *buttonName = [buttons_ objectAtIndex:button];
6088 [self _clickButtonWithName:buttonName];
6091 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6095 - (bool) _allowJavaScriptPanel {
6100 - (void) _customButtonClicked {
6101 int count([buttons_ count]);
6106 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6108 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6109 [buttons addObjectsFromArray:buttons_];
6111 UIActionSheet *sheet = [[[UIActionSheet alloc]
6114 cancelButtonTitle:nil
6115 destructiveButtonTitle:nil
6116 otherButtonTitles:nil
6119 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6121 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6122 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6124 [sheet setContext:@"modify"];
6126 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6130 - (void) reloadButtonClicked {
6131 if (commercial_ && function_ == nil && [package_ uninstalled])
6133 [self customButtonClicked];
6136 - (void) applyLoadingTitle {
6137 // Don't show "Loading" as the title. Ever.
6140 - (UIBarButtonItem *) rightButton {
6145 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6146 if ((self = [super init]) != nil) {
6147 database_ = database;
6148 buttons_ = [NSMutableArray arrayWithCapacity:4];
6149 name_ = name == nil ? @"" : [NSString stringWithString:name];
6150 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6154 - (void) reloadData {
6157 package_ = [database_ packageWithName:name_];
6159 [buttons_ removeAllObjects];
6161 if (package_ != nil) {
6162 [(Package *) package_ parse];
6164 commercial_ = [package_ isCommercial];
6166 if ([package_ mode] != nil)
6167 [buttons_ addObject:UCLocalize("CLEAR")];
6168 if ([package_ source] == nil);
6169 else if ([package_ upgradableAndEssential:NO])
6170 [buttons_ addObject:UCLocalize("UPGRADE")];
6171 else if ([package_ uninstalled])
6172 [buttons_ addObject:UCLocalize("INSTALL")];
6174 [buttons_ addObject:UCLocalize("REINSTALL")];
6175 if (![package_ uninstalled])
6176 [buttons_ addObject:UCLocalize("REMOVE")];
6180 switch ([buttons_ count]) {
6181 case 0: title = nil; break;
6182 case 1: title = [buttons_ objectAtIndex:0]; break;
6183 default: title = UCLocalize("MODIFY"); break;
6186 button_ = [[[UIBarButtonItem alloc]
6188 style:UIBarButtonItemStylePlain
6190 action:@selector(customButtonClicked)
6194 - (bool) isLoading {
6195 return commercial_ ? [super isLoading] : false;
6201 /* Package List Controller {{{ */
6202 @interface PackageListController : CyteViewController <
6203 UITableViewDataSource,
6206 _transient Database *database_;
6208 _H<NSArray> packages_;
6209 _H<NSArray> sections_;
6210 _H<UITableView, 2> list_;
6212 _H<NSArray> thumbs_;
6213 std::vector<NSInteger> offset_;
6215 _H<NSString> title_;
6216 unsigned reloading_;
6219 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6220 - (void) setDelegate:(id)delegate;
6221 - (void) resetCursor;
6224 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6228 @implementation PackageListController
6230 - (NSURL *) referrerURL {
6231 return [self navigationURL];
6234 - (bool) isSummarized {
6238 - (bool) showsSections {
6242 - (void) deselectWithAnimation:(BOOL)animated {
6243 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6246 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6247 CGRect base = [[self view] bounds];
6248 base.size.height -= bounds.size.height;
6249 base.origin = [list_ frame].origin;
6251 [UIView beginAnimations:nil context:NULL];
6252 [UIView setAnimationBeginsFromCurrentState:YES];
6253 [UIView setAnimationCurve:curve];
6254 [UIView setAnimationDuration:duration];
6255 [list_ setFrame:base];
6256 [UIView commitAnimations];
6259 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6260 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6263 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6264 [self resizeForKeyboardBounds:bounds duration:0];
6267 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6268 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6269 *curve = UIViewAnimationCurveEaseInOut;
6271 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6273 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6276 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6279 - (void) keyboardWillShow:(NSNotification *)notification {
6282 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6283 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6285 NSTimeInterval duration;
6286 UIViewAnimationCurve curve;
6287 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6289 CGRect kbframe = CGRectMake(round(center.x - bounds.size.width / 2.0), round(center.y - bounds.size.height / 2.0), bounds.size.width, bounds.size.height);
6290 UIViewController *base = self;
6291 while ([base parentOrPresentingViewController] != nil)
6292 base = [base parentOrPresentingViewController];
6293 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6294 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6296 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6297 intersection.size.height += CYStatusBarHeight();
6299 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6302 - (void) keyboardWillHide:(NSNotification *)notification {
6303 NSTimeInterval duration;
6304 UIViewAnimationCurve curve;
6305 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6307 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6310 - (void) viewWillAppear:(BOOL)animated {
6311 [super viewWillAppear:animated];
6313 [self resizeForKeyboardBounds:CGRectZero];
6314 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6315 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6318 - (void) viewWillDisappear:(BOOL)animated {
6319 [super viewWillDisappear:animated];
6321 [self resizeForKeyboardBounds:CGRectZero];
6322 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6323 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6326 - (void) viewDidAppear:(BOOL)animated {
6327 [super viewDidAppear:animated];
6328 [self deselectWithAnimation:animated];
6331 - (void) didSelectPackage:(Package *)package {
6332 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6333 [view setDelegate:delegate_];
6334 [[self navigationController] pushViewController:view animated:YES];
6337 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6338 NSInteger count([sections_ count]);
6339 return count == 0 ? 1 : count;
6342 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6343 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6345 return [[sections_ objectAtIndex:section] name];
6348 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6349 if ([sections_ count] == 0)
6351 return [[sections_ objectAtIndex:section] count];
6354 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6355 @synchronized (database_) {
6356 if ([database_ era] != era_)
6359 Section *section([sections_ objectAtIndex:[path section]]);
6360 NSInteger row([path row]);
6361 Package *package([packages_ objectAtIndex:([section row] + row)]);
6362 return [[package retain] autorelease];
6365 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6366 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6368 cell = [[[PackageCell alloc] init] autorelease];
6370 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6371 [cell setPackage:package asSummary:[self isSummarized]];
6375 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6376 Package *package([self packageAtIndexPath:path]);
6377 package = [database_ packageWithName:[package id]];
6378 [self didSelectPackage:package];
6381 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6385 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6386 return offset_[index];
6389 - (void) updateHeight {
6390 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6393 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6394 if ((self = [super init]) != nil) {
6395 database_ = database;
6396 title_ = [title copy];
6397 [[self navigationItem] setTitle:title_];
6402 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6403 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6404 [self setView:view];
6406 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6407 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6408 [view addSubview:list_];
6410 // XXX: is 20 the most optimal number here?
6411 [list_ setSectionIndexMinimumDisplayRowCount:20];
6413 [(UITableView *) list_ setDataSource:self];
6414 [list_ setDelegate:self];
6416 [self updateHeight];
6419 - (void) releaseSubviews {
6428 [super releaseSubviews];
6431 - (void) setDelegate:(id)delegate {
6432 delegate_ = delegate;
6435 - (bool) shouldYield {
6439 - (bool) shouldBlock {
6443 - (NSMutableArray *) _reloadPackages {
6444 @synchronized (database_) {
6445 era_ = [database_ era];
6446 NSArray *packages([database_ packages]);
6448 return [NSMutableArray arrayWithArray:packages];
6451 - (void) _reloadData {
6452 if (reloading_ != 0) {
6457 NSMutableArray *packages;
6460 if ([self shouldYield]) {
6464 if (![self shouldBlock])
6467 hud = [delegate_ addProgressHUD];
6468 [hud setText:UCLocalize("LOADING")];
6472 packages = [self yieldToSelector:@selector(_reloadPackages)];
6475 [delegate_ removeProgressHUD:hud];
6476 } while (reloading_ == 2);
6478 packages = [self _reloadPackages];
6481 @synchronized (database_) {
6482 if (era_ != [database_ era])
6489 packages_ = packages;
6491 if ([self showsSections])
6492 sections_ = [self sectionsForPackages:packages];
6494 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6495 [section setCount:[packages_ count]];
6496 sections_ = [NSArray arrayWithObject:section];
6499 [self updateHeight];
6501 _profile(PackageTable$reloadData$List)
6502 [(UITableView *) list_ setDataSource:self];
6510 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6511 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6512 size_t end([packages count]);
6514 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6515 Section *section(prefix);
6517 thumbs_ = CollationThumbs_;
6518 offset_ = CollationOffset_;
6521 size_t offsets([CollationStarts_ count]);
6523 NSString *start([CollationStarts_ objectAtIndex:offset]);
6524 size_t length([start length]);
6526 for (size_t index(0); index != end; ++index) {
6528 Package *package([packages objectAtIndex:index]);
6529 NSString *name([package name]);
6531 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6532 while (StringNameCompare((CFStringRef) start, (CFStringRef) name, NULL) != kCFCompareGreaterThan) {
6533 NSString *title([CollationTitles_ objectAtIndex:offset]);
6534 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6535 [sections addObject:section];
6537 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6540 length = [start length];
6544 [section addToCount];
6547 for (; offset != offsets; ++offset) {
6548 NSString *title([CollationTitles_ objectAtIndex:offset]);
6549 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6550 [sections addObject:section];
6553 if ([prefix count] != 0) {
6554 Section *suffix([sections lastObject]);
6555 [prefix setName:[suffix name]];
6556 [suffix setName:nil];
6557 [sections insertObject:prefix atIndex:(offsets - 1)];
6563 - (void) reloadData {
6566 if ([self shouldYield])
6567 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6572 - (void) resetCursor {
6573 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6576 - (void) clearData {
6577 [self updateHeight];
6579 [list_ setDataSource:nil];
6587 /* Filtered Package List Controller {{{ */
6588 typedef Function<bool, Package *> PackageFilter;
6589 typedef Function<void, NSMutableArray *> PackageSorter;
6590 @interface FilteredPackageListController : PackageListController {
6591 PackageFilter filter_;
6592 PackageSorter sorter_;
6595 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6597 - (void) setFilter:(PackageFilter)filter;
6598 - (void) setSorter:(PackageSorter)sorter;
6602 @implementation FilteredPackageListController
6604 - (void) setFilter:(PackageFilter)filter {
6605 @synchronized (self) {
6609 - (void) setSorter:(PackageSorter)sorter {
6610 @synchronized (self) {
6614 - (NSMutableArray *) _reloadPackages {
6615 @synchronized (database_) {
6616 era_ = [database_ era];
6618 NSArray *packages([database_ packages]);
6619 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6621 PackageFilter filter;
6622 PackageSorter sorter;
6624 @synchronized (self) {
6629 _profile(PackageTable$reloadData$Filter)
6630 for (Package *package in packages)
6631 if ([package valid] && filter(package))
6632 [filtered addObject:package];
6640 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6641 if ((self = [super initWithDatabase:database title:title]) != nil) {
6642 [self setFilter:filter];
6649 /* Home Controller {{{ */
6650 @interface HomeController : CydiaWebViewController {
6651 CFRunLoopRef runloop_;
6652 SCNetworkReachabilityRef reachability_;
6657 @implementation HomeController
6659 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6660 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6664 if ((self = [super init]) != nil) {
6665 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6668 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6669 if (reachability_ != NULL) {
6670 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6671 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6673 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6674 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6681 if (reachability_ != NULL && runloop_ != NULL)
6682 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6686 - (NSURL *) navigationURL {
6687 return [NSURL URLWithString:@"cydia://home"];
6690 - (void) aboutButtonClicked {
6691 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6693 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6694 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6695 [alert setCancelButtonIndex:0];
6698 @"Copyright \u00a9 2008-2013\n"
6701 "Jay Freeman (saurik)\n"
6702 "saurik@saurik.com\n"
6703 "http://www.saurik.com/"
6709 - (UIBarButtonItem *) leftButton {
6710 return [[[UIBarButtonItem alloc]
6711 initWithTitle:UCLocalize("ABOUT")
6712 style:UIBarButtonItemStylePlain
6714 action:@selector(aboutButtonClicked)
6721 /* Cydia Navigation Controller Interface {{{ */
6722 @interface UINavigationController (Cydia)
6724 - (NSArray *) navigationURLCollection;
6725 - (void) unloadData;
6730 /* Cydia Tab Bar Controller {{{ */
6731 @interface CydiaTabBarController : CyteTabBarController <
6732 UITabBarControllerDelegate,
6735 _transient Database *database_;
6737 _H<UIActivityIndicatorView> indicator_;
6740 // XXX: ok, "updatedelegate_"?...
6741 _transient NSObject<CydiaDelegate> *updatedelegate_;
6744 - (NSArray *) navigationURLCollection;
6745 - (void) beginUpdate;
6750 @implementation CydiaTabBarController
6752 - (NSArray *) navigationURLCollection {
6753 NSMutableArray *items([NSMutableArray array]);
6755 // XXX: Should this deal with transient view controllers?
6756 for (id navigation in [self viewControllers]) {
6757 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6759 [items addObject:stack];
6765 - (id) initWithDatabase:(Database *)database {
6766 if ((self = [super init]) != nil) {
6767 database_ = database;
6768 [self setDelegate:self];
6770 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6771 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6773 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6777 - (void) setUpdate:(NSDate *)date {
6781 - (void) beginUpdate {
6785 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6786 UITabBarItem *item([controller tabBarItem]);
6788 [item setBadgeValue:@""];
6789 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6791 [indicator_ startAnimating];
6792 [badge addSubview:indicator_];
6794 [updatedelegate_ retainNetworkActivityIndicator];
6798 detachNewThreadSelector:@selector(performUpdate)
6804 - (void) performUpdate {
6805 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6807 SourceStatus status(self, database_);
6808 [database_ updateWithStatus:status];
6811 performSelectorOnMainThread:@selector(completeUpdate)
6819 - (void) stopUpdateWithSelector:(SEL)selector {
6821 [updatedelegate_ releaseNetworkActivityIndicator];
6823 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6824 [[controller tabBarItem] setBadgeValue:nil];
6826 [indicator_ removeFromSuperview];
6827 [indicator_ stopAnimating];
6829 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6832 - (void) completeUpdate {
6835 [self stopUpdateWithSelector:@selector(reloadData)];
6838 - (void) cancelUpdate {
6839 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
6842 - (void) cancelPressed {
6843 [self cancelUpdate];
6850 - (bool) isSourceCancelled {
6854 - (void) startSourceFetch:(NSString *)uri {
6857 - (void) stopSourceFetch:(NSString *)uri {
6860 - (void) setUpdateDelegate:(id)delegate {
6861 updatedelegate_ = delegate;
6864 - (UIView *) transitionView {
6865 if (![self respondsToSelector:@selector(_transitionView)])
6866 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6867 else if (kCFCoreFoundationVersionNumber < 800)
6868 return [self _transitionView];
6870 return [[[self _transitionView] superview] superview];
6876 /* Cydia Navigation Controller Implementation {{{ */
6877 @implementation UINavigationController (Cydia)
6879 - (NSArray *) navigationURLCollection {
6880 NSMutableArray *stack([NSMutableArray array]);
6882 for (CyteViewController *controller in [self viewControllers]) {
6883 NSString *url = [[controller navigationURL] absoluteString];
6885 [stack addObject:url];
6891 - (void) reloadData {
6894 UIViewController *visible([self visibleViewController]);
6896 [visible reloadData];
6898 // on the iPad, this view controller is ALSO visible. :(
6900 if (UIViewController *top = [self topViewController])
6905 - (void) unloadData {
6906 for (CyteViewController *page in [self viewControllers])
6915 /* Cydia:// Protocol {{{ */
6916 @interface CydiaURLProtocol : NSURLProtocol {
6921 @implementation CydiaURLProtocol
6923 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6924 NSURL *url([request URL]);
6928 NSString *scheme([[url scheme] lowercaseString]);
6929 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6931 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6937 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6941 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6942 id<NSURLProtocolClient> client([self client]);
6944 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6946 NSData *data(UIImagePNGRepresentation(icon));
6948 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6949 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6950 [client URLProtocol:self didLoadData:data];
6951 [client URLProtocolDidFinishLoading:self];
6955 - (void) startLoading {
6956 id<NSURLProtocolClient> client([self client]);
6957 NSURLRequest *request([self request]);
6959 NSURL *url([request URL]);
6960 NSString *href([url absoluteString]);
6961 NSString *scheme([[url scheme] lowercaseString]);
6965 if ([scheme isEqualToString:@"cydia"])
6966 path = [href substringFromIndex:8];
6967 else if ([scheme isEqualToString:@"about"])
6968 path = [href substringFromIndex:12];
6969 else _assert(false);
6971 NSRange slash([path rangeOfString:@"/"]);
6974 if (slash.location == NSNotFound) {
6978 command = [path substringToIndex:slash.location];
6979 path = [path substringFromIndex:(slash.location + 1)];
6982 Database *database([Database sharedInstance]);
6984 if ([command isEqualToString:@"package-icon"]) {
6987 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6988 Package *package([database packageWithName:path]);
6992 UIImage *icon([package icon]);
6993 [self _returnPNGWithImage:icon forRequest:request];
6994 } else if ([command isEqualToString:@"uikit-image"]) {
6997 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6998 UIImage *icon(_UIImageWithName(path));
6999 [self _returnPNGWithImage:icon forRequest:request];
7000 } else if ([command isEqualToString:@"section-icon"]) {
7003 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7004 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7006 icon = [UIImage applicationImageNamed:@"unknown.png"];
7007 [self _returnPNGWithImage:icon forRequest:request];
7009 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7013 - (void) stopLoading {
7019 /* Section Controller {{{ */
7020 @interface SectionController : FilteredPackageListController {
7022 _H<NSString> section_;
7025 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7029 @implementation SectionController
7031 - (NSURL *) referrerURL {
7032 NSString *name(section_);
7033 name = name ?: @"*";
7034 NSString *key(key_);
7036 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7039 - (NSURL *) navigationURL {
7040 NSString *name(section_);
7041 name = name ?: @"*";
7042 NSString *key(key_);
7044 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7047 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7050 title = UCLocalize("ALL_PACKAGES");
7051 else if (![section isEqual:@""])
7052 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7054 title = UCLocalize("NO_SECTION");
7056 if ((self = [super initWithDatabase:database title:title]) != nil) {
7057 key_ = [source key];
7062 - (void) reloadData {
7063 Source *source([database_ sourceWithKey:key_]);
7064 _H<NSString> name(section_);
7066 [self setFilter:[=](Package *package) {
7067 NSString *section([package section]);
7071 section == nil && [name length] == 0 ||
7072 [name isEqualToString:section]
7075 [package source] == source
7076 ) && [package visible];
7084 /* Sections Controller {{{ */
7085 @interface SectionsController : CyteViewController <
7086 UITableViewDataSource,
7089 _transient Database *database_;
7091 _H<NSMutableArray> sections_;
7092 _H<NSMutableArray> filtered_;
7093 _H<UITableView, 2> list_;
7096 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7097 - (void) editButtonClicked;
7101 @implementation SectionsController
7103 - (NSURL *) navigationURL {
7104 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7107 - (Source *) source {
7110 return [database_ sourceWithKey:key_];
7113 - (void) updateNavigationItem {
7114 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7115 if ([sections_ count] == 0) {
7116 [[self navigationItem] setRightBarButtonItem:nil];
7118 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7119 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7121 action:@selector(editButtonClicked)
7122 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7126 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7127 [super setEditing:editing animated:animated];
7132 [delegate_ updateData];
7134 [self updateNavigationItem];
7137 - (void) viewDidAppear:(BOOL)animated {
7138 [super viewDidAppear:animated];
7139 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7142 - (void) viewWillDisappear:(BOOL)animated {
7143 [super viewWillDisappear:animated];
7144 [self setEditing:NO];
7147 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7148 Section *section = nil;
7149 int index = [indexPath row];
7150 if (![self isEditing]) {
7153 section = [filtered_ objectAtIndex:index];
7155 section = [sections_ objectAtIndex:index];
7160 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7161 if ([self isEditing])
7162 return [sections_ count];
7164 return [filtered_ count] + 1;
7167 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7171 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7172 static NSString *reuseIdentifier = @"SectionCell";
7174 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7176 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7178 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7183 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7184 if ([self isEditing])
7187 Section *section = [self sectionAtIndexPath:indexPath];
7189 SectionController *controller = [[[SectionController alloc]
7190 initWithDatabase:database_
7191 source:[self source]
7192 section:[section name]
7194 [controller setDelegate:delegate_];
7196 [[self navigationController] pushViewController:controller animated:YES];
7200 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7201 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7202 [list_ setRowHeight:46];
7203 [(UITableView *) list_ setDataSource:self];
7204 [list_ setDelegate:self];
7205 [self setView:list_];
7208 - (void) viewDidLoad {
7209 [super viewDidLoad];
7211 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7214 - (void) releaseSubviews {
7220 [super releaseSubviews];
7223 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7224 if ((self = [super init]) != nil) {
7225 database_ = database;
7226 key_ = [source key];
7230 - (void) reloadData {
7233 NSArray *packages = [database_ packages];
7235 sections_ = [NSMutableArray arrayWithCapacity:16];
7236 filtered_ = [NSMutableArray arrayWithCapacity:16];
7238 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7240 Source *source([self source]);
7243 for (Package *package in packages) {
7244 if (source != nil && [package source] != source)
7247 NSString *name([package section]);
7248 NSString *key(name == nil ? @"" : name);
7252 _profile(SectionsView$reloadData$Section)
7253 section = [sections objectForKey:key];
7254 if (section == nil) {
7255 _profile(SectionsView$reloadData$Section$Allocate)
7256 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7257 [sections setObject:section forKey:key];
7262 [section addToCount];
7264 _profile(SectionsView$reloadData$Filter)
7265 if (![package valid] || ![package visible])
7273 [sections_ addObjectsFromArray:[sections allValues]];
7275 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7277 for (Section *section in (id) sections_) {
7278 size_t count([section row]);
7282 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7283 [section setCount:count];
7284 [filtered_ addObject:section];
7287 [self updateNavigationItem];
7292 - (void) editButtonClicked {
7293 [self setEditing:![self isEditing] animated:YES];
7299 /* Changes Controller {{{ */
7300 @interface ChangesController : FilteredPackageListController {
7304 - (id) initWithDatabase:(Database *)database;
7308 @implementation ChangesController
7310 - (NSURL *) referrerURL {
7311 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7314 - (NSURL *) navigationURL {
7315 return [NSURL URLWithString:@"cydia://changes"];
7318 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7319 @synchronized (database_) {
7320 if ([database_ era] != era_)
7323 NSUInteger sectionIndex([path section]);
7324 if (sectionIndex >= [sections_ count])
7326 Section *section([sections_ objectAtIndex:sectionIndex]);
7327 NSInteger row([path row]);
7328 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7331 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7332 NSString *context([alert context]);
7334 if ([context isEqualToString:@"norefresh"])
7335 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7338 - (void) setLeftBarButtonItem {
7339 if ([delegate_ updating])
7340 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7341 initWithTitle:UCLocalize("CANCEL")
7342 style:UIBarButtonItemStyleDone
7344 action:@selector(cancelButtonClicked)
7345 ] autorelease] animated:YES];
7347 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7348 initWithTitle:UCLocalize("REFRESH")
7349 style:UIBarButtonItemStylePlain
7351 action:@selector(refreshButtonClicked)
7352 ] autorelease] animated:YES];
7355 - (void) refreshButtonClicked {
7356 if ([delegate_ requestUpdate])
7357 [self setLeftBarButtonItem];
7360 - (void) cancelButtonClicked {
7361 [delegate_ cancelUpdate];
7364 - (void) upgradeButtonClicked {
7365 [delegate_ distUpgrade];
7366 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7369 - (bool) shouldYield {
7373 - (bool) shouldBlock {
7377 - (void) useFilter {
7378 @synchronized (self) {
7379 [self setFilter:[](Package *package) {
7380 return [package upgradableAndEssential:YES] || [package visible];
7383 [self setSorter:[](NSMutableArray *packages) {
7384 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7388 - (id) initWithDatabase:(Database *)database {
7389 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7394 - (void) reloadData {
7395 [self setLeftBarButtonItem];
7399 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7400 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7402 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7403 Section *ignored = nil;
7404 Section *section = nil;
7408 bool unseens = false;
7410 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7412 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7413 Package *package = [packages objectAtIndex:offset];
7415 BOOL uae = [package upgradableAndEssential:YES];
7419 time_t seen([package seen]);
7421 if (section == nil || last != seen) {
7425 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7428 _profile(ChangesController$reloadData$Allocate)
7429 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7430 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7431 [sections addObject:section];
7435 [section addToCount];
7436 } else if ([package ignored]) {
7437 if (ignored == nil) {
7438 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7440 [ignored addToCount];
7443 [upgradable addToCount];
7448 CFRelease(formatter);
7451 Section *last = [sections lastObject];
7452 size_t count = [last count];
7453 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7454 [sections removeLastObject];
7457 if ([ignored count] != 0)
7458 [sections insertObject:ignored atIndex:0];
7460 [sections insertObject:upgradable atIndex:0];
7464 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7465 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7466 style:UIBarButtonItemStylePlain
7468 action:@selector(upgradeButtonClicked)
7469 ] autorelease]) animated:YES];
7476 /* Search Controller {{{ */
7477 @interface SearchController : FilteredPackageListController <
7480 _H<UISearchBar, 1> search_;
7485 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7486 - (void) reloadData;
7490 @implementation SearchController
7492 - (NSURL *) referrerURL {
7493 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7496 - (NSURL *) navigationURL {
7497 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7498 return [NSURL URLWithString:@"cydia://search"];
7500 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7503 - (NSArray *) termsForQuery:(NSString *)query {
7504 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7505 for (NSString *component in [query componentsSeparatedByString:@" "])
7506 if ([component length] != 0)
7507 [terms addObject:component];
7512 - (void) useSearch {
7513 _H<NSArray> query([self termsForQuery:[search_ text]]);
7516 @synchronized (self) {
7517 [self setFilter:[=](Package *package) {
7518 if (![package unfiltered])
7520 if (![package matches:query])
7525 [self setSorter:[](NSMutableArray *packages) {
7526 [packages radixSortUsingSelector:@selector(rank)];
7534 - (void) usePrefix:(NSString *)prefix {
7535 _H<NSString> query(prefix);
7538 @synchronized (self) {
7539 [self setFilter:[=](Package *package) {
7540 if ([query length] == 0)
7542 if (![package unfiltered])
7544 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7549 [self setSorter:nullptr];
7555 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7557 [self usePrefix:[search_ text]];
7560 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7561 [search_ resignFirstResponder];
7565 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7566 [search_ setText:@""];
7567 [self searchBarButtonClicked:searchBar];
7570 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7571 [self searchBarButtonClicked:searchBar];
7574 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7575 [self usePrefix:text];
7578 - (bool) shouldYield {
7582 - (bool) shouldBlock {
7586 - (bool) isSummarized {
7590 - (bool) showsSections {
7594 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7595 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7596 search_ = [[[UISearchBar alloc] init] autorelease];
7597 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7598 [search_ setDelegate:self];
7600 UITextField *textField;
7601 if ([search_ respondsToSelector:@selector(searchField)])
7602 textField = [search_ searchField];
7604 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7606 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7607 [textField setEnablesReturnKeyAutomatically:NO];
7608 [[self navigationItem] setTitleView:textField];
7611 [search_ setText:query];
7616 - (void) viewDidAppear:(BOOL)animated {
7617 [super viewDidAppear:animated];
7619 if (!searchloaded_) {
7620 searchloaded_ = YES;
7621 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7622 [search_ layoutSubviews];
7625 if ([self isSummarized])
7626 [search_ becomeFirstResponder];
7629 - (void) reloadData {
7634 - (void) didSelectPackage:(Package *)package {
7635 [search_ resignFirstResponder];
7636 [super didSelectPackage:package];
7641 /* Package Settings Controller {{{ */
7642 @interface PackageSettingsController : CyteViewController <
7643 UITableViewDataSource,
7646 _transient Database *database_;
7648 _H<Package> package_;
7649 _H<UITableView, 2> table_;
7650 _H<UISwitch> subscribedSwitch_;
7651 _H<UISwitch> ignoredSwitch_;
7652 _H<UITableViewCell> subscribedCell_;
7653 _H<UITableViewCell> ignoredCell_;
7656 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7660 @implementation PackageSettingsController
7662 - (NSURL *) navigationURL {
7663 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7666 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7667 if (package_ == nil)
7670 if ([package_ installed] == nil)
7676 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7677 if (package_ == nil)
7680 // both sections contain just one item right now.
7684 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7688 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7690 return UCLocalize("SHOW_ALL_CHANGES_EX");
7692 return UCLocalize("IGNORE_UPGRADES_EX");
7695 - (void) onSubscribed:(id)control {
7696 bool value([control isOn]);
7697 if (package_ == nil)
7699 if ([package_ setSubscribed:value])
7700 [delegate_ updateData];
7703 - (void) _updateIgnored {
7704 const char *package([name_ UTF8String]);
7705 bool on([ignoredSwitch_ isOn]);
7707 pid_t pid(ExecFork());
7709 FILE *dpkg(popen("dpkg --set-selections", "w"));
7710 fwrite(package, strlen(package), 1, dpkg);
7713 fwrite(" hold\n", 6, 1, dpkg);
7715 fwrite(" install\n", 9, 1, dpkg);
7723 - (void) onIgnored:(id)control {
7724 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7725 [invocation setTarget:self];
7726 [invocation setSelector:@selector(_updateIgnored)];
7728 [delegate_ reloadDataWithInvocation:invocation];
7731 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7732 if (package_ == nil)
7735 switch ([indexPath section]) {
7736 case 0: return subscribedCell_;
7737 case 1: return ignoredCell_;
7746 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7747 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7748 [self setView:view];
7750 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7751 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7752 [(UITableView *) table_ setDataSource:self];
7753 [table_ setDelegate:self];
7754 [view addSubview:table_];
7756 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7757 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7758 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7760 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7761 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7762 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7764 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7765 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7766 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7767 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7769 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7770 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7771 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7772 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7775 - (void) viewDidLoad {
7776 [super viewDidLoad];
7778 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7781 - (void) releaseSubviews {
7783 subscribedCell_ = nil;
7785 ignoredSwitch_ = nil;
7786 subscribedSwitch_ = nil;
7788 [super releaseSubviews];
7791 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7792 if ((self = [super init]) != nil) {
7793 database_ = database;
7798 - (void) reloadData {
7801 package_ = [database_ packageWithName:name_];
7803 if (package_ != nil) {
7804 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7805 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7806 } // XXX: what now, G?
7808 [table_ reloadData];
7814 /* Installed Controller {{{ */
7815 @interface InstalledController : FilteredPackageListController {
7819 - (id) initWithDatabase:(Database *)database;
7820 - (void) queueStatusDidChange;
7824 @implementation InstalledController
7826 - (NSURL *) referrerURL {
7827 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
7830 - (NSURL *) navigationURL {
7831 return [NSURL URLWithString:@"cydia://installed"];
7834 - (bool) showsSections {
7838 - (void) useUpdated {
7841 @synchronized (self) {
7842 [self setFilter:[](Package *package) {
7843 return ![package uninstalled] && package->role_ < 7;
7846 [self setSorter:[](NSMutableArray *packages) {
7847 [packages radixSortUsingSelector:@selector(updated)];
7851 - (void) useFilter:(UISegmentedControl *)segmented {
7852 NSInteger selected([segmented selectedSegmentIndex]);
7854 return [self useUpdated];
7855 bool simple(selected == 0);
7858 @synchronized (self) {
7859 [self setFilter:[=](Package *package) {
7860 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
7863 [self setSorter:nullptr];
7866 - (id) initWithDatabase:(Database *)database {
7867 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
7868 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
7869 [segmented setSelectedSegmentIndex:0];
7870 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
7871 [[self navigationItem] setTitleView:segmented];
7873 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
7874 [self useFilter:segmented];
7876 [self queueStatusDidChange];
7881 - (void) queueButtonClicked {
7886 - (void) queueStatusDidChange {
7889 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7890 initWithTitle:UCLocalize("QUEUE")
7891 style:UIBarButtonItemStyleDone
7893 action:@selector(queueButtonClicked)
7896 [[self navigationItem] setLeftBarButtonItem:nil];
7901 - (void) modeChanged:(UISegmentedControl *)segmented {
7902 [self useFilter:segmented];
7909 /* Source Cell {{{ */
7910 @interface SourceCell : CyteTableViewCell <
7911 CyteTableViewCellDelegate,
7914 _H<Source, 1> source_;
7917 _H<NSString> origin_;
7918 _H<NSString> label_;
7919 _H<UIActivityIndicatorView> indicator_;
7922 - (void) setSource:(Source *)source;
7923 - (void) setFetch:(NSNumber *)fetch;
7927 @implementation SourceCell
7929 - (void) _setImage:(NSArray *)data {
7930 if ([url_ isEqual:[data objectAtIndex:0]]) {
7931 icon_ = [data objectAtIndex:1];
7932 [content_ setNeedsDisplay];
7936 - (void) _setSource:(NSURL *) url {
7937 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7939 if (NSData *data = [NSURLConnection
7940 sendSynchronousRequest:[NSURLRequest
7942 cachePolicy:NSURLRequestUseProtocolCachePolicy
7946 returningResponse:NULL
7949 if (UIImage *image = [UIImage imageWithData:data])
7950 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
7955 - (void) setSource:(Source *)source {
7957 [source_ setDelegate:self];
7959 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
7961 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7963 origin_ = [source name];
7964 label_ = [source rooturi];
7966 [content_ setNeedsDisplay];
7968 url_ = [source iconURL];
7969 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
7972 - (void) setAllSource {
7974 [indicator_ stopAnimating];
7976 icon_ = [UIImage applicationImageNamed:@"folder.png"];
7977 origin_ = UCLocalize("ALL_SOURCES");
7978 label_ = UCLocalize("ALL_SOURCES_EX");
7979 [content_ setNeedsDisplay];
7982 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7983 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7984 UIView *content([self contentView]);
7985 CGRect bounds([content bounds]);
7987 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7988 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7989 [content_ setBackgroundColor:[UIColor whiteColor]];
7990 [content addSubview:content_];
7992 [content_ setDelegate:self];
7993 [content_ setOpaque:YES];
7995 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
7996 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
7997 [content addSubview:indicator_];
7999 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8003 - (void) layoutSubviews {
8004 [super layoutSubviews];
8006 UIView *content([self contentView]);
8007 CGRect bounds([content bounds]);
8009 CGRect frame([indicator_ frame]);
8010 frame.origin.x = bounds.size.width - frame.size.width;
8011 frame.origin.y = (bounds.size.height - frame.size.height) / 2;
8013 if (kCFCoreFoundationVersionNumber < 800)
8014 frame.origin.x -= 8;
8015 [indicator_ setFrame:frame];
8018 - (NSString *) accessibilityLabel {
8022 - (void) drawContentRect:(CGRect)rect {
8023 bool highlighted(highlighted_);
8024 float width(rect.size.width);
8028 rect.size = [(UIImage *) icon_ size];
8030 while (rect.size.width > 32 || rect.size.height > 32) {
8031 rect.size.width /= 2;
8032 rect.size.height /= 2;
8035 rect.origin.x = 26 - rect.size.width / 2;
8036 rect.origin.y = 26 - rect.size.height / 2;
8038 [icon_ drawInRect:rect];
8041 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8046 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 61) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8050 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 61) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8053 - (void) setFetch:(NSNumber *)fetch {
8054 if ([fetch boolValue])
8055 [indicator_ startAnimating];
8057 [indicator_ stopAnimating];
8062 /* Sources Controller {{{ */
8063 @interface SourcesController : CyteViewController <
8064 UITableViewDataSource,
8067 _transient Database *database_;
8070 _H<UITableView, 2> list_;
8071 _H<NSMutableArray> sources_;
8075 _H<UIProgressHUD> hud_;
8078 NSURLConnection *trivial_bz2_;
8079 NSURLConnection *trivial_gz_;
8084 - (id) initWithDatabase:(Database *)database;
8085 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8089 @implementation SourcesController
8091 - (void) _releaseConnection:(NSURLConnection *)connection {
8092 if (connection != nil) {
8093 [connection cancel];
8094 //[connection setDelegate:nil];
8095 [connection release];
8100 [self _releaseConnection:trivial_gz_];
8101 [self _releaseConnection:trivial_bz2_];
8106 - (NSURL *) navigationURL {
8107 return [NSURL URLWithString:@"cydia://sources"];
8110 - (void) viewDidAppear:(BOOL)animated {
8111 [super viewDidAppear:animated];
8112 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8115 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8119 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8121 return UCLocalize("INDIVIDUAL_SOURCES");
8125 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8128 case 1: return [sources_ count];
8133 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8134 @synchronized (database_) {
8135 if ([database_ era] != era_)
8137 if ([indexPath section] != 1)
8139 NSUInteger index([indexPath row]);
8140 if (index >= [sources_ count])
8142 return [sources_ objectAtIndex:index];
8145 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8146 static NSString *cellIdentifier = @"SourceCell";
8148 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8149 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8150 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8152 Source *source([self sourceAtIndexPath:indexPath]);
8154 [cell setAllSource];
8156 [cell setSource:source];
8161 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8162 SectionsController *controller([[[SectionsController alloc]
8163 initWithDatabase:database_
8164 source:[self sourceAtIndexPath:indexPath]
8167 [controller setDelegate:delegate_];
8168 [[self navigationController] pushViewController:controller animated:YES];
8171 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8172 if ([indexPath section] != 1)
8174 Source *source = [self sourceAtIndexPath:indexPath];
8175 return [source record] != nil;
8178 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8179 _assert([indexPath section] == 1);
8180 if (editingStyle == UITableViewCellEditingStyleDelete) {
8181 Source *source = [self sourceAtIndexPath:indexPath];
8182 if (source == nil) return;
8184 [Sources_ removeObjectForKey:[source key]];
8187 [delegate_ _saveConfig];
8188 [delegate_ reloadDataWithInvocation:nil];
8192 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8193 [self updateButtonsForEditingStatusAnimated:YES];
8197 [delegate_ addTrivialSource:href_];
8200 [delegate_ syncData];
8203 - (NSString *) getWarning {
8204 NSString *href(href_);
8205 NSRange colon([href rangeOfString:@"://"]);
8206 if (colon.location != NSNotFound)
8207 href = [href substringFromIndex:(colon.location + 3)];
8208 href = [href stringByAddingPercentEscapes];
8209 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8211 NSURL *url([NSURL URLWithString:href]);
8213 NSStringEncoding encoding;
8214 NSError *error(nil);
8216 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8217 return [warning length] == 0 ? nil : warning;
8221 - (void) _endConnection:(NSURLConnection *)connection {
8222 // XXX: the memory management in this method is horribly awkward
8224 NSURLConnection **field = NULL;
8225 if (connection == trivial_bz2_)
8226 field = &trivial_bz2_;
8227 else if (connection == trivial_gz_)
8228 field = &trivial_gz_;
8229 _assert(field != NULL);
8230 [connection release];
8234 trivial_bz2_ == nil &&
8237 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8239 [delegate_ releaseNetworkActivityIndicator];
8241 [delegate_ removeProgressHUD:hud_];
8245 if (warning != nil) {
8246 UIAlertView *alert = [[[UIAlertView alloc]
8247 initWithTitle:UCLocalize("SOURCE_WARNING")
8250 cancelButtonTitle:UCLocalize("CANCEL")
8252 UCLocalize("ADD_ANYWAY"),
8256 [alert setContext:@"warning"];
8257 [alert setNumberOfRows:1];
8260 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8266 } else if (error_ != nil) {
8267 UIAlertView *alert = [[[UIAlertView alloc]
8268 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8269 message:[error_ localizedDescription]
8271 cancelButtonTitle:UCLocalize("OK")
8272 otherButtonTitles:nil
8275 [alert setContext:@"urlerror"];
8280 UIAlertView *alert = [[[UIAlertView alloc]
8281 initWithTitle:UCLocalize("NOT_REPOSITORY")
8282 message:UCLocalize("NOT_REPOSITORY_EX")
8284 cancelButtonTitle:UCLocalize("OK")
8285 otherButtonTitles:nil
8288 [alert setContext:@"trivial"];
8298 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8299 switch ([response statusCode]) {
8305 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8306 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8308 [self _endConnection:connection];
8311 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8312 [self _endConnection:connection];
8315 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8316 NSURL *url([NSURL URLWithString:href]);
8318 NSMutableURLRequest *request = [NSMutableURLRequest
8320 cachePolicy:NSURLRequestUseProtocolCachePolicy
8324 [request setHTTPMethod:method];
8326 if (Machine_ != NULL)
8327 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8329 if (UniqueID_ != nil)
8330 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8332 if ([url isCydiaSecure]) {
8333 if (UniqueID_ != nil)
8334 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8337 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8340 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8341 NSString *context([alert context]);
8343 if ([context isEqualToString:@"source"]) {
8346 NSString *href = [[alert textField] text];
8348 static Pcre href_r("^http(s?)://[^# ]*$");
8349 if (!href_r(href)) {
8350 UIAlertView *alert = [[[UIAlertView alloc]
8351 initWithTitle:Error_
8352 message:UCLocalize("INVALID_URL")
8354 cancelButtonTitle:UCLocalize("OK")
8355 otherButtonTitles:nil
8358 [alert setContext:@"badurl"];
8364 if (![href hasSuffix:@"/"])
8365 href_ = [href stringByAppendingString:@"/"];
8369 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8370 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8374 // XXX: this is stupid
8375 hud_ = [delegate_ addProgressHUD];
8376 [hud_ setText:UCLocalize("VERIFYING_URL")];
8377 [delegate_ retainNetworkActivityIndicator];
8386 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8387 } else if ([context isEqualToString:@"trivial"])
8388 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8389 else if ([context isEqualToString:@"urlerror"])
8390 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8391 else if ([context isEqualToString:@"warning"]) {
8394 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8403 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8407 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8408 BOOL editing([list_ isEditing]);
8411 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8412 initWithTitle:UCLocalize("ADD")
8413 style:UIBarButtonItemStylePlain
8415 action:@selector(addButtonClicked)
8416 ] autorelease] animated:animated];
8417 else if ([delegate_ updating])
8418 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8419 initWithTitle:UCLocalize("CANCEL")
8420 style:UIBarButtonItemStyleDone
8422 action:@selector(cancelButtonClicked)
8423 ] autorelease] animated:animated];
8425 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8426 initWithTitle:UCLocalize("REFRESH")
8427 style:UIBarButtonItemStylePlain
8429 action:@selector(refreshButtonClicked)
8430 ] autorelease] animated:animated];
8432 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8433 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8434 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8436 action:@selector(editButtonClicked)
8437 ] autorelease] animated:animated];
8441 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8442 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8443 [list_ setRowHeight:53];
8444 [(UITableView *) list_ setDataSource:self];
8445 [list_ setDelegate:self];
8446 [self setView:list_];
8449 - (void) viewDidLoad {
8450 [super viewDidLoad];
8452 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8453 [self updateButtonsForEditingStatusAnimated:NO];
8456 - (void) viewWillAppear:(BOOL)animated {
8457 [super viewWillAppear:animated];
8459 [list_ setEditing:NO];
8460 [self updateButtonsForEditingStatusAnimated:NO];
8463 - (void) releaseSubviews {
8468 [super releaseSubviews];
8471 - (id) initWithDatabase:(Database *)database {
8472 if ((self = [super init]) != nil) {
8473 database_ = database;
8477 - (void) reloadData {
8479 [self updateButtonsForEditingStatusAnimated:YES];
8481 @synchronized (database_) {
8482 era_ = [database_ era];
8484 sources_ = [NSMutableArray arrayWithCapacity:16];
8485 [sources_ addObjectsFromArray:[database_ sources]];
8487 [sources_ sortUsingSelector:@selector(compareByName:)];
8490 int count([sources_ count]);
8492 for (int i = 0; i != count; i++) {
8493 if ([[sources_ objectAtIndex:i] record] == nil)
8501 - (void) showAddSourcePrompt {
8502 UIAlertView *alert = [[[UIAlertView alloc]
8503 initWithTitle:UCLocalize("ENTER_APT_URL")
8506 cancelButtonTitle:UCLocalize("CANCEL")
8508 UCLocalize("ADD_SOURCE"),
8512 [alert setContext:@"source"];
8514 [alert setNumberOfRows:1];
8515 [alert addTextFieldWithValue:@"http://" label:@""];
8517 UITextInputTraits *traits = [[alert textField] textInputTraits];
8518 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8519 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8520 [traits setKeyboardType:UIKeyboardTypeURL];
8521 // XXX: UIReturnKeyDone
8522 [traits setReturnKeyType:UIReturnKeyNext];
8527 - (void) addButtonClicked {
8528 [self showAddSourcePrompt];
8531 - (void) refreshButtonClicked {
8532 if ([delegate_ requestUpdate])
8533 [self updateButtonsForEditingStatusAnimated:YES];
8536 - (void) cancelButtonClicked {
8537 [delegate_ cancelUpdate];
8540 - (void) editButtonClicked {
8541 [list_ setEditing:![list_ isEditing] animated:YES];
8542 [self updateButtonsForEditingStatusAnimated:YES];
8548 /* Stash Controller {{{ */
8549 @interface StashController : CyteViewController {
8550 _H<UIActivityIndicatorView> spinner_;
8551 _H<UILabel> status_;
8552 _H<UILabel> caption_;
8557 @implementation StashController
8560 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8561 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8562 [self setView:view];
8564 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8566 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8567 CGRect spinrect = [spinner_ frame];
8568 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8569 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8570 [spinner_ setFrame:spinrect];
8571 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8572 [view addSubview:spinner_];
8573 [spinner_ startAnimating];
8576 captrect.size.width = [[self view] frame].size.width;
8577 captrect.size.height = 40.0f;
8578 captrect.origin.x = 0;
8579 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8580 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8581 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8582 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8583 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8584 [caption_ setTextColor:[UIColor whiteColor]];
8585 [caption_ setBackgroundColor:[UIColor clearColor]];
8586 [caption_ setShadowColor:[UIColor blackColor]];
8587 [caption_ setTextAlignment:NSTextAlignmentCenter];
8588 [view addSubview:caption_];
8591 statusrect.size.width = [[self view] frame].size.width;
8592 statusrect.size.height = 30.0f;
8593 statusrect.origin.x = 0;
8594 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8595 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8596 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8597 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8598 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8599 [status_ setTextColor:[UIColor whiteColor]];
8600 [status_ setBackgroundColor:[UIColor clearColor]];
8601 [status_ setShadowColor:[UIColor blackColor]];
8602 [status_ setTextAlignment:NSTextAlignmentCenter];
8603 [view addSubview:status_];
8606 - (void) releaseSubviews {
8611 [super releaseSubviews];
8617 @interface CYURLCache : SDURLCache {
8622 @implementation CYURLCache
8624 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8627 else if ([event isEqualToString:@"no-cache"])
8629 else if ([event isEqualToString:@"store"])
8631 else if ([event isEqualToString:@"invalid"])
8633 else if ([event isEqualToString:@"memory"])
8635 else if ([event isEqualToString:@"disk"])
8637 else if ([event isEqualToString:@"miss"])
8640 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8644 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8645 if (NSURLResponse *response = [cached response])
8646 if (NSString *mime = [response MIMEType])
8647 if ([mime isEqualToString:@"text/cache-manifest"]) {
8648 NSURL *url([response URL]);
8651 NSLog(@"###: %@", [url absoluteString]);
8654 @synchronized (HostConfig_) {
8655 [CachedURLs_ addObject:url];
8659 [super storeCachedResponse:cached forRequest:request];
8664 @interface Cydia : UIApplication <
8665 ConfirmationControllerDelegate,
8668 UINavigationControllerDelegate,
8669 UITabBarControllerDelegate
8671 _H<UIWindow> window_;
8672 _H<CydiaTabBarController> tabbar_;
8673 _H<CydiaLoadingViewController> emulated_;
8675 _H<NSMutableArray> essential_;
8676 _H<NSMutableArray> broken_;
8678 Database *database_;
8680 _H<NSURL> starturl_;
8685 _H<StashController> stash_;
8694 @implementation Cydia
8696 - (void) lockSuspend {
8697 if (locked_++ == 0) {
8698 if ($SBSSetInterceptsMenuButtonForever != NULL)
8699 (*$SBSSetInterceptsMenuButtonForever)(true);
8701 [self setIdleTimerDisabled:YES];
8705 - (void) unlockSuspend {
8706 if (--locked_ == 0) {
8707 [self setIdleTimerDisabled:NO];
8709 if ($SBSSetInterceptsMenuButtonForever != NULL)
8710 (*$SBSSetInterceptsMenuButtonForever)(false);
8714 - (void) beginUpdate {
8715 [tabbar_ beginUpdate];
8718 - (void) cancelUpdate {
8719 [tabbar_ cancelUpdate];
8722 - (bool) requestUpdate {
8723 if (IsReachable("cydia.saurik.com")) {
8727 UIAlertView *alert = [[[UIAlertView alloc]
8728 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8729 message:@"Host Unreachable" // XXX: Localize
8731 cancelButtonTitle:UCLocalize("OK")
8732 otherButtonTitles:nil
8735 [alert setContext:@"norefresh"];
8743 return [tabbar_ updating];
8747 if ([broken_ count] != 0) {
8748 int count = [broken_ count];
8750 UIAlertView *alert = [[[UIAlertView alloc]
8751 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8752 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8754 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8756 UCLocalize("TEMPORARY_IGNORE"),
8760 [alert setContext:@"fixhalf"];
8761 [alert setNumberOfRows:2];
8763 } else if (!Ignored_ && [essential_ count] != 0) {
8764 int count = [essential_ count];
8766 UIAlertView *alert = [[[UIAlertView alloc]
8767 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8768 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8770 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8772 UCLocalize("UPGRADE_ESSENTIAL"),
8773 UCLocalize("COMPLETE_UPGRADE"),
8777 [alert setContext:@"upgrade"];
8782 - (void) returnToCydia {
8786 - (void) _saveConfig {
8787 @synchronized (database_) {
8794 NSString *error(nil);
8796 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8798 NSError *error(nil);
8799 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8800 NSLog(@"failure to save metadata data: %@", error);
8805 NSLog(@"failure to serialize metadata: %@", error);
8809 CydiaWriteSources();
8812 // Navigation controller for the queuing badge.
8813 - (UINavigationController *) queueNavigationController {
8814 NSArray *controllers = [tabbar_ viewControllers];
8815 return [controllers objectAtIndex:3];
8818 - (void) unloadData {
8819 [tabbar_ unloadData];
8822 - (void) _updateData {
8826 UINavigationController *navigation = [self queueNavigationController];
8828 id queuedelegate = nil;
8829 if ([[navigation viewControllers] count] > 0)
8830 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8832 [queuedelegate queueStatusDidChange];
8833 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8836 - (void) _refreshIfPossible:(NSDate *)update {
8837 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8839 bool recently = false;
8840 if (update != nil) {
8841 NSTimeInterval interval([update timeIntervalSinceNow]);
8842 if (interval <= 0 && interval > -(15*60))
8846 // Don't automatic refresh if:
8847 // - We already refreshed recently.
8848 // - We already auto-refreshed this launch.
8849 // - Auto-refresh is disabled.
8850 // - Cydia's server is not reachable
8851 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
8852 // If we are cancelling, we need to make sure it knows it's already loaded.
8855 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8857 // We are going to load, so remember that.
8860 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8866 - (void) refreshIfPossible {
8867 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8870 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8871 _profile(reloadDataWithInvocation)
8872 @synchronized (self) {
8873 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8875 [hud setText:UCLocalize("RELOADING_DATA")];
8877 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8881 [essential_ removeAllObjects];
8882 [broken_ removeAllObjects];
8884 _profile(reloadDataWithInvocation$Essential)
8885 NSArray *packages([database_ packages]);
8886 for (Package *package in packages) {
8888 [broken_ addObject:package];
8889 if ([package upgradableAndEssential:YES] && ![package ignored]) {
8890 if ([package essential] && [package installed] != nil)
8891 [essential_ addObject:package];
8897 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8900 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8901 [changesItem setBadgeValue:badge];
8902 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8903 [self setApplicationIconBadgeNumber:changes];
8906 [changesItem setBadgeValue:nil];
8907 [changesItem setAnimatedBadge:NO];
8908 [self setApplicationIconBadgeNumber:0];
8914 [self removeProgressHUD:hud];
8921 - (void) updateData {
8925 - (void) updateDataAndLoad {
8927 if ([database_ progressDelegate] == nil)
8933 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8936 - (void) disemulate {
8937 if (emulated_ == nil)
8940 if ([window_ respondsToSelector:@selector(setRootViewController:)])
8941 [window_ setRootViewController:tabbar_];
8943 [window_ addSubview:[tabbar_ view]];
8944 [[emulated_ view] removeFromSuperview];
8948 [window_ setUserInteractionEnabled:YES];
8951 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8952 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8954 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8956 UIViewController *parent;
8957 if (emulated_ == nil)
8966 [parent presentModalViewController:navigation animated:YES];
8969 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8970 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8972 if (navigation != nil)
8973 [navigation pushViewController:progress animated:YES];
8975 [self presentModalViewController:progress force:YES];
8977 [progress invoke:invocation withTitle:title];
8981 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8982 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8985 - (void) repairWithInvocation:(NSInvocation *)invocation {
8987 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
8991 - (void) repairWithSelector:(SEL)selector {
8992 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8995 - (void) reloadData {
8996 [self reloadDataWithInvocation:nil];
8997 if ([database_ progressDelegate] == nil)
9003 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9006 - (void) addSource:(NSDictionary *) source {
9007 CydiaAddSource(source);
9010 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9011 CydiaAddSource(href, distribution, sections);
9014 - (void) addTrivialSource:(NSString *)href {
9015 CydiaAddSource(href, @"./");
9018 - (void) updateValues {
9023 pkgProblemResolver *resolver = [database_ resolver];
9025 resolver->InstallProtect();
9026 if (!resolver->Resolve(true))
9031 // XXX: this is a really crappy way of doing this.
9032 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9033 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9034 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9035 if ([tabbar_ updating])
9036 [tabbar_ cancelUpdate];
9038 if (![database_ prepare])
9041 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9042 [page setDelegate:self];
9043 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9046 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9047 [tabbar_ presentModalViewController:confirm_ animated:YES];
9053 @synchronized (self) {
9058 - (void) clearPackage:(Package *)package {
9059 @synchronized (self) {
9066 - (void) installPackages:(NSArray *)packages {
9067 @synchronized (self) {
9068 for (Package *package in packages)
9075 - (void) installPackage:(Package *)package {
9076 @synchronized (self) {
9083 - (void) removePackage:(Package *)package {
9084 @synchronized (self) {
9091 - (void) distUpgrade {
9092 @synchronized (self) {
9093 if (![database_ upgrade])
9101 system("su -c /usr/bin/uicache mobile");
9106 UIProgressHUD *hud([self addProgressHUD]);
9107 [hud setText:UCLocalize("LOADING")];
9108 [self yieldToSelector:@selector(_uicache)];
9109 [self removeProgressHUD:hud];
9113 [database_ perform];
9114 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9115 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9118 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9121 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9122 [self unlockSuspend];
9125 - (void) retainNetworkActivityIndicator {
9126 if (activity_++ == 0)
9127 [self setNetworkActivityIndicatorVisible:YES];
9130 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9134 - (void) releaseNetworkActivityIndicator {
9135 if (--activity_ == 0)
9136 [self setNetworkActivityIndicatorVisible:NO];
9139 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9144 - (void) cancelAndClear:(bool)clear {
9145 @synchronized (self) {
9157 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9158 NSString *context([alert context]);
9160 if ([context isEqualToString:@"conffile"]) {
9161 FILE *input = [database_ input];
9162 if (button == [alert cancelButtonIndex])
9163 fprintf(input, "N\n");
9164 else if (button == [alert firstOtherButtonIndex])
9165 fprintf(input, "Y\n");
9168 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9169 } else if ([context isEqualToString:@"fixhalf"]) {
9170 if (button == [alert cancelButtonIndex]) {
9171 @synchronized (self) {
9172 for (Package *broken in (id) broken_) {
9175 NSString *id = [broken id];
9176 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9177 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9178 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9179 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9185 } else if (button == [alert firstOtherButtonIndex]) {
9186 [broken_ removeAllObjects];
9190 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9191 } else if ([context isEqualToString:@"upgrade"]) {
9192 if (button == [alert firstOtherButtonIndex]) {
9193 @synchronized (self) {
9194 for (Package *essential in (id) essential_)
9195 [essential install];
9200 } else if (button == [alert firstOtherButtonIndex] + 1) {
9202 } else if (button == [alert cancelButtonIndex]) {
9206 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9210 - (void) system:(NSString *)command {
9211 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9214 system([command UTF8String]);
9220 - (void) applicationWillSuspend {
9222 [super applicationWillSuspend];
9225 - (BOOL) isSafeToSuspend {
9228 NSLog(@"isSafeToSuspend: locked_ != 0");
9233 // Use external process status API internally.
9234 // This is probably a really bad idea.
9235 // XXX: what is the point of this? does this solve anything at all?
9236 uint64_t status = 0;
9238 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9239 notify_get_state(notify_token, &status);
9240 notify_cancel(notify_token);
9245 NSLog(@"isSafeToSuspend: status != 0");
9251 NSLog(@"isSafeToSuspend: -> true");
9256 - (void) applicationSuspend:(__GSEvent *)event {
9257 if ([self isSafeToSuspend])
9258 [super applicationSuspend:event];
9261 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9262 if ([self isSafeToSuspend])
9263 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9266 - (void) _setSuspended:(BOOL)value {
9267 if ([self isSafeToSuspend])
9268 [super _setSuspended:value];
9271 - (UIProgressHUD *) addProgressHUD {
9272 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9273 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9275 [window_ setUserInteractionEnabled:NO];
9277 UIViewController *target(tabbar_);
9278 if (UIViewController *modal = [target modalViewController])
9281 [hud showInView:[target view]];
9287 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9288 [self unlockSuspend];
9290 [hud removeFromSuperview];
9291 [window_ setUserInteractionEnabled:YES];
9294 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9295 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9298 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9299 NSString *scheme([[url scheme] lowercaseString]);
9300 if ([[url absoluteString] length] <= [scheme length] + 3)
9302 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9303 NSArray *components([path componentsSeparatedByString:@"/"]);
9305 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9306 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9307 if (controller != nil)
9308 [controller setDelegate:self];
9312 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9315 NSString *base([components objectAtIndex:0]);
9317 CyteViewController *controller = nil;
9319 if ([base isEqualToString:@"url"]) {
9320 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9321 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9322 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9323 } else if (!external && [components count] == 1) {
9324 if ([base isEqualToString:@"sources"]) {
9325 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9328 if ([base isEqualToString:@"home"]) {
9329 controller = [[[HomeController alloc] init] autorelease];
9332 if ([base isEqualToString:@"sections"]) {
9333 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9336 if ([base isEqualToString:@"search"]) {
9337 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9340 if ([base isEqualToString:@"changes"]) {
9341 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9344 if ([base isEqualToString:@"installed"]) {
9345 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9347 } else if ([components count] == 2) {
9348 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9350 if ([base isEqualToString:@"package"]) {
9351 controller = [self pageForPackage:argument withReferrer:referrer];
9354 if (!external && [base isEqualToString:@"search"]) {
9355 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9358 if (!external && [base isEqualToString:@"sections"]) {
9359 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9361 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9364 if (!external && [base isEqualToString:@"sources"]) {
9365 if ([argument isEqualToString:@"add"]) {
9366 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9367 [(SourcesController *)controller showAddSourcePrompt];
9369 Source *source([database_ sourceWithKey:argument]);
9370 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9374 if (!external && [base isEqualToString:@"launch"]) {
9375 [self launchApplicationWithIdentifier:argument suspended:NO];
9378 } else if (!external && [components count] == 3) {
9379 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9380 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9382 if ([base isEqualToString:@"package"]) {
9383 if ([arg2 isEqualToString:@"settings"]) {
9384 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9385 } else if ([arg2 isEqualToString:@"files"]) {
9386 if (Package *package = [database_ packageWithName:arg1]) {
9387 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9388 [(FileTable *)controller setPackage:package];
9393 if ([base isEqualToString:@"sections"]) {
9394 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9395 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9396 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9400 [controller setDelegate:self];
9404 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9405 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9408 [tabbar_ setUnselectedViewController:page];
9413 - (void) applicationOpenURL:(NSURL *)url {
9414 [super applicationOpenURL:url];
9419 [self openCydiaURL:url forExternal:YES];
9422 - (void) applicationWillResignActive:(UIApplication *)application {
9423 // Stop refreshing if you get a phone call or lock the device.
9424 if ([tabbar_ updating])
9425 [tabbar_ cancelUpdate];
9427 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9428 [super applicationWillResignActive:application];
9431 - (void) saveState {
9432 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9433 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9434 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9440 - (void) applicationWillTerminate:(UIApplication *)application {
9444 - (void) setConfigurationData:(NSString *)data {
9445 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9447 if (!conffile_r(data)) {
9448 lprintf("E:invalid conffile\n");
9452 NSString *ofile = conffile_r[1];
9453 //NSString *nfile = conffile_r[2];
9455 UIAlertView *alert = [[[UIAlertView alloc]
9456 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9457 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9459 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9461 UCLocalize("ACCEPT_NEW_COPY"),
9462 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9466 [alert setContext:@"conffile"];
9467 [alert setNumberOfRows:2];
9471 - (void) addStashController {
9473 stash_ = [[[StashController alloc] init] autorelease];
9474 [window_ addSubview:[stash_ view]];
9477 - (void) removeStashController {
9478 [[stash_ view] removeFromSuperview];
9480 [self unlockSuspend];
9484 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9485 UpdateExternalStatus(1);
9486 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9487 UpdateExternalStatus(0);
9489 [self removeStashController];
9491 pid_t pid(ExecFork());
9493 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9494 perror("launchctl stop");
9500 - (void) setupViewControllers {
9501 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9503 NSMutableArray *items;
9504 if (kCFCoreFoundationVersionNumber < 800) {
9505 items = [NSMutableArray arrayWithObjects:
9506 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9507 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9508 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9509 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease],
9510 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9513 items = [NSMutableArray arrayWithObjects:
9514 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home7.png"] selectedImage:[UIImage applicationImageNamed:@"home7s.png"]] autorelease],
9515 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install7.png"] selectedImage:[UIImage applicationImageNamed:@"install7s.png"]] autorelease],
9516 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes7.png"] selectedImage:[UIImage applicationImageNamed:@"changes7s.png"]] autorelease],
9517 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage7.png"] selectedImage:[UIImage applicationImageNamed:@"manage7s.png"]] autorelease],
9518 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search7.png"] selectedImage:[UIImage applicationImageNamed:@"search7s.png"]] autorelease],
9522 NSMutableArray *controllers([NSMutableArray array]);
9523 for (UITabBarItem *item in items) {
9524 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9525 [controller setTabBarItem:item];
9526 [controllers addObject:controller];
9528 [tabbar_ setViewControllers:controllers];
9530 [tabbar_ setUpdateDelegate:self];
9533 - (void) _sendMemoryWarningNotification {
9534 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9535 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9537 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9540 - (void) _sendMemoryWarningNotifications {
9542 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9548 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9550 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9553 - (void) applicationDidFinishLaunching:(id)unused {
9554 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9557 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9558 [self setApplicationSupportsShakeToEdit:NO];
9560 @synchronized (HostConfig_) {
9561 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9564 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9565 initWithMemoryCapacity:524288
9566 diskCapacity:10485760
9567 diskPath:[NSString stringWithFormat:@"%@/SDURLCache", Cache_]
9570 [CydiaWebViewController _initialize];
9572 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9574 // this would disallow http{,s} URLs from accessing this data
9575 //[WebView registerURLSchemeAsLocal:@"cydia"];
9577 Font12_ = [UIFont systemFontOfSize:12];
9578 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9579 Font14_ = [UIFont systemFontOfSize:14];
9580 Font18_ = [UIFont systemFontOfSize:18];
9581 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9582 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9584 essential_ = [NSMutableArray arrayWithCapacity:4];
9585 broken_ = [NSMutableArray arrayWithCapacity:4];
9587 // XXX: I really need this thing... like, seriously... I'm sorry
9588 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9590 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9591 [window_ orderFront:self];
9592 [window_ makeKey:self];
9593 [window_ setHidden:NO];
9596 [self addStashController];
9597 // XXX: this would be much cleaner as a yieldToSelector:
9598 // that way the removeStashController could happen right here inline
9599 // we also could no longer require the useless stash_ field anymore
9600 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9605 int error(stat("/", &root));
9606 _assert(error != -1);
9608 #define Stash_(path) do { \
9609 struct stat folder; \
9610 int error(lstat((path), &folder)); \
9611 if (error != -1 && ( \
9612 folder.st_dev == root.st_dev && \
9613 S_ISDIR(folder.st_mode) \
9614 ) || error == -1 && ( \
9615 errno == ENOENT || \
9620 Stash_("/Applications");
9621 Stash_("/Library/Ringtones");
9622 Stash_("/Library/Wallpaper");
9623 //Stash_("/usr/bin");
9624 Stash_("/usr/include");
9625 Stash_("/usr/lib/pam");
9626 Stash_("/usr/share");
9627 //Stash_("/var/lib");
9629 database_ = [Database sharedInstance];
9630 [database_ setDelegate:self];
9632 [window_ setUserInteractionEnabled:NO];
9633 [self setupViewControllers];
9635 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9636 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9637 [window_ setRootViewController:emulated_];
9639 [window_ addSubview:[emulated_ view]];
9641 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9645 - (NSArray *) defaultStartPages {
9646 NSMutableArray *standard = [NSMutableArray array];
9647 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9648 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9649 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9650 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9651 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9657 if ([emulated_ modalViewController] != nil)
9658 [emulated_ dismissModalViewControllerAnimated:YES];
9659 [window_ setUserInteractionEnabled:NO];
9661 [self reloadDataWithInvocation:nil];
9662 [self refreshIfPossible];
9665 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9666 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9667 int standardIndex = 0;
9668 NSArray *standard = [self defaultStartPages];
9675 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9676 if (valid && closed != nil) {
9677 NSTimeInterval interval([closed timeIntervalSinceNow]);
9678 // XXX: Is 30 minutes the optimal time here?
9679 if (interval <= -(30*60))
9683 if (valid && [saved count] != [standard count])
9687 for (unsigned int i = 0; i < [standard count]; i++) {
9688 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9689 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9690 // but it's good enough for now.
9691 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9698 NSArray *items = nil;
9700 [tabbar_ setSelectedIndex:savedIndex];
9703 [tabbar_ setSelectedIndex:standardIndex];
9707 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9708 NSArray *stack = [items objectAtIndex:tab];
9709 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9710 NSMutableArray *current = [NSMutableArray array];
9712 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9713 NSString *addr = [stack objectAtIndex:nav];
9714 NSURL *url = [NSURL URLWithString:addr];
9715 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9717 [current addObject:page];
9720 [navigation setViewControllers:current];
9723 // (Try to) show the startup URL.
9724 if (starturl_ != nil) {
9725 [self openCydiaURL:starturl_ forExternal:NO];
9730 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9731 if (item != nil && IsWildcat_) {
9732 [sheet showFromBarButtonItem:item animated:YES];
9734 [sheet showInView:window_];
9738 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9739 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9740 [progress setTitle:task];
9741 [progress addProgressEvent:event];
9744 - (void) addProgressEventForTask:(NSArray *)data {
9745 CydiaProgressEvent *event([data objectAtIndex:0]);
9746 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9747 [self addProgressEvent:event forTask:task];
9750 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9751 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9757 id Alloc_(id self, SEL selector) {
9758 id object = alloc_(self, selector);
9759 lprintf("[%s]A-%p\n", self->isa->name, object);
9764 id Dealloc_(id self, SEL selector) {
9765 id object = dealloc_(self, selector);
9766 lprintf("[%s]D-%p\n", self->isa->name, object);
9770 static NSSet *MobilizedFiles_;
9772 static NSURL *MobilizeURL(NSURL *url) {
9773 NSString *path([url path]);
9774 if ([path hasPrefix:@"/var/root/"]) {
9775 NSString *file([path substringFromIndex:10]);
9776 if ([MobilizedFiles_ containsObject:file])
9777 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9783 Class $CFXPreferencesPropertyListSource;
9784 @class CFXPreferencesPropertyListSource;
9786 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9787 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9788 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9789 url = MobilizeURL(url);
9790 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9791 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9797 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9798 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9799 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9800 url = MobilizeURL(url);
9801 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9802 //NSLog(@"%@ %@", [url absoluteString], value);
9808 Class $NSURLConnection;
9810 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9811 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
9813 NSURL *url([copy URL]);
9815 NSString *host([url host]);
9816 NSString *scheme([[url scheme] lowercaseString]);
9818 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9820 @synchronized (HostConfig_) {
9821 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9822 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9823 [copy setHTTPShouldUsePipelining:YES];
9825 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9826 if ([control isEqualToString:@"max-age=0"])
9827 if ([CachedURLs_ containsObject:url]) {
9829 NSLog(@"~~~: %@", url);
9832 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9834 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9835 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9836 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9840 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9846 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
9847 CGSize size([[UIScreen mainScreen] bounds].size);
9848 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
9849 if ([$WAKWindow hasLandscapeOrientation])
9850 std::swap(size.width, size.height);*/
9854 Class $NSUserDefaults;
9856 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
9857 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
9858 return [NSString stringWithFormat:@"%@/LocalStorage", Cache_];
9859 return _NSUserDefaults$objectForKey$(self, _cmd, key);
9862 int main(int argc, char *argv[]) {
9863 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9867 UpdateExternalStatus(0);
9869 UIScreen *screen([UIScreen mainScreen]);
9870 if ([screen respondsToSelector:@selector(scale)])
9871 ScreenScale_ = [screen scale];
9875 UIDevice *device([UIDevice currentDevice]);
9876 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
9877 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9878 if (idiom == UIUserInterfaceIdiomPad)
9882 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
9884 Pcre pattern("^([0-9]+\\.[0-9]+)");
9886 if (pattern([device systemVersion]))
9887 Firmware_ = pattern[1];
9888 if (pattern(Cydia_))
9889 Major_ = pattern[1];
9891 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9893 HostConfig_ = [[[NSObject alloc] init] autorelease];
9894 @synchronized (HostConfig_) {
9895 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9896 TokenHosts_ = [NSMutableSet setWithCapacity:4];
9897 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9898 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9899 CachedURLs_ = [NSMutableSet setWithCapacity:32];
9902 NSString *ui(@"ui/ios");
9904 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
9905 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
9908 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9910 MobilizedFiles_ = [NSMutableSet setWithObjects:
9911 @"Library/Preferences/com.apple.Accessibility.plist",
9912 @"Library/Preferences/com.apple.preferences.sounds.plist",
9915 /* Library Hacks {{{ */
9916 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9918 $WAKWindow = objc_getClass("WAKWindow");
9919 if ($WAKWindow != NULL)
9920 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
9921 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
9923 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9925 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9926 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9927 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9928 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9931 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9932 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9933 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9934 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9937 $NSURLConnection = objc_getClass("NSURLConnection");
9938 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9939 if (NSURLConnection$init$ != NULL) {
9940 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9941 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9944 $NSUserDefaults = objc_getClass("NSUserDefaults");
9945 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
9946 if (NSUserDefaults$objectForKey$ != NULL) {
9947 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
9948 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
9951 /* Set Locale {{{ */
9952 Locale_ = CFLocaleCopyCurrent();
9953 Languages_ = [NSLocale preferredLanguages];
9955 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9956 //NSLog(@"%@", [Languages_ description]);
9959 if (Locale_ != NULL)
9960 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9961 else if (Languages_ != nil && [Languages_ count] != 0)
9962 lang = [[Languages_ objectAtIndex:0] UTF8String];
9964 // XXX: consider just setting to C and then falling through?
9968 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
9969 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
9972 NSLog(@"Setting Language: %s", lang);
9975 setenv("LANG", lang, true);
9976 std::setlocale(LC_ALL, lang);
9979 /* Index Collation {{{ */
9980 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) {
9981 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
9982 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
9983 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
9984 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
9985 _H<UILocalizedIndexedCollation> collation([[[UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
9987 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
9989 CollationThumbs_ = [collation sectionIndexTitles];
9990 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
9991 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
9993 CollationTitles_ = [collation sectionTitles];
9994 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
9996 if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
9997 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };
9999 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10001 CollationThumbs_ = [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#",nil];
10002 for (NSInteger offset(0); offset != 28; ++offset)
10003 CollationOffset_.push_back(offset);
10005 CollationTitles_ = [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#",nil];
10006 CollationStarts_ = [NSArray arrayWithObjects:@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j",@"k",@"l",@"m",@"n",@"o",@"p",@"q",@"r",@"s",@"t",@"u",@"v",@"w",@"x",@"y",@"z",@"ʒ",nil];
10010 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10012 /* Parse Arguments {{{ */
10013 bool substrate(false);
10019 for (int argi(1); argi != argc; ++argi)
10020 if (strcmp(argv[argi], "--") == 0) {
10022 argv[argi] = argv[0];
10028 for (int argi(1); argi != arge; ++argi)
10029 if (strcmp(args[argi], "--substrate") == 0)
10032 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10036 App_ = [[NSBundle mainBundle] bundlePath];
10042 if (access("/var/mobile/Library/Keyboard/UserDictionary.sqlite", F_OK) == 0)
10043 system("mkdir -p /var/root/Library/Keyboard; cp -af /var/mobile/Library/Keyboard/UserDictionary.sqlite /var/root/Library/Keyboard/");
10045 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/root"] retain];
10047 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10048 alloc_ = alloc->method_imp;
10049 alloc->method_imp = (IMP) &Alloc_;*/
10051 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10052 dealloc_ = dealloc->method_imp;
10053 dealloc->method_imp = (IMP) &Dealloc_;*/
10055 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10056 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10058 /* System Information {{{ */
10062 size = sizeof(maxproc);
10063 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10064 perror("sysctlbyname(\"kern.maxproc\", ?)");
10065 else if (maxproc < 64) {
10067 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10068 perror("sysctlbyname(\"kern.maxproc\", #)");
10071 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10072 char *osversion = new char[size];
10073 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10074 perror("sysctlbyname(\"kern.osversion\", ?)");
10076 System_ = [NSString stringWithUTF8String:osversion];
10078 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10079 char *machine = new char[size];
10080 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10081 perror("sysctlbyname(\"hw.machine\", ?)");
10083 Machine_ = machine;
10085 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10086 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10087 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10089 UniqueID_ = UniqueIdentifier(device);
10091 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10092 Product_ = [info objectForKey:@"SafariProductVersion"];
10093 Safari_ = [info objectForKey:@"CFBundleVersion"];
10096 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10098 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10099 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10100 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10101 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10102 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10103 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10105 UserAgent_ = agent;
10107 /* Load Database {{{ */
10109 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10111 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10113 if (Metadata_ == NULL)
10114 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10116 Settings_ = [Metadata_ objectForKey:@"Settings"];
10118 Packages_ = [Metadata_ objectForKey:@"Packages"];
10120 Values_ = [Metadata_ objectForKey:@"Values"];
10121 Sections_ = [Metadata_ objectForKey:@"Sections"];
10122 Sources_ = [Metadata_ objectForKey:@"Sources"];
10124 Token_ = [Metadata_ objectForKey:@"Token"];
10126 Version_ = [Metadata_ objectForKey:@"Version"];
10129 if (Values_ == nil) {
10130 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10131 [Metadata_ setObject:Values_ forKey:@"Values"];
10134 if (Sections_ == nil) {
10135 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10136 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10139 if (Sources_ == nil) {
10140 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10141 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10144 if (Version_ == nil) {
10145 Version_ = [NSNumber numberWithUnsignedInt:0];
10146 [Metadata_ setObject:Version_ forKey:@"Version"];
10149 if ([Version_ unsignedIntValue] == 0) {
10150 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10151 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10152 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10153 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10155 Version_ = [NSNumber numberWithUnsignedInt:1];
10156 [Metadata_ setObject:Version_ forKey:@"Version"];
10158 [Metadata_ removeObjectForKey:@"LastUpdate"];
10163 _H<NSMutableArray> broken([NSMutableArray array]);
10164 for (NSString *key in (id) Sources_)
10165 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound)
10166 [broken addObject:key];
10167 if ([broken count] != 0) {
10168 for (NSString *key in (id) broken)
10169 [Sources_ removeObjectForKey:key];
10174 CydiaWriteSources();
10177 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10180 if (Packages_ != nil) {
10182 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10186 [Metadata_ removeObjectForKey:@"Packages"];
10192 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10194 #define MobileSubstrate_(name) \
10195 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10196 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10197 if (handle == NULL) \
10198 NSLog(@"%s", dlerror()); \
10201 MobileSubstrate_(Activator)
10202 MobileSubstrate_(libstatusbar)
10203 MobileSubstrate_(SimulatedKeyEvents)
10204 MobileSubstrate_(WinterBoard)
10206 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10207 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10209 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10211 if (access("/User", F_OK) != 0 || version != 6) {
10213 system("/usr/libexec/cydia/firmware.sh");
10217 _assert([[NSFileManager defaultManager]
10218 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10219 withIntermediateDirectories:YES
10224 if (access("/tmp/cydia.chk", F_OK) == 0) {
10225 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10226 _assert(errno == ENOENT);
10227 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10228 _assert(errno == ENOENT);
10231 /* APT Initialization {{{ */
10232 _assert(pkgInitConfig(*_config));
10233 _assert(pkgInitSystem(*_config, _system));
10236 _config->Set("APT::Acquire::Translation", lang);
10238 // XXX: this timeout might be important :(
10239 //_config->Set("Acquire::http::Timeout", 15);
10241 _config->Set("Acquire::http::MaxParallel", 3);
10243 /* Color Choices {{{ */
10244 space_ = CGColorSpaceCreateDeviceRGB();
10246 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10247 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10248 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10249 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10250 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10251 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10252 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10253 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10254 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10255 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10257 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10258 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10260 /* UIKit Configuration {{{ */
10261 // XXX: I have a feeling this was important
10262 //UIKeyboardDisableAutomaticAppearance();
10265 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10267 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10268 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10269 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10271 PulseInterval_ = fast ? 50000 : 500000;
10273 Colon_ = UCLocalize("COLON_DELIMITED");
10274 Elision_ = UCLocalize("ELISION");
10275 Error_ = UCLocalize("ERROR");
10276 Warning_ = UCLocalize("WARNING");
10279 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10281 CGColorSpaceRelease(space_);
10282 CFRelease(Locale_);