1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "CyteKit/UCPlatform.h"
45 #include "CyteKit/Localize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <QuartzCore/CALayer.h>
71 #include <WebCore/WebCoreThread.h>
78 #include <ext/stdio_filebuf.h>
82 #include <apt-pkg/acquire.h>
83 #include <apt-pkg/acquire-item.h>
84 #include <apt-pkg/algorithms.h>
85 #include <apt-pkg/cachefile.h>
86 #include <apt-pkg/clean.h>
87 #include <apt-pkg/configuration.h>
88 #include <apt-pkg/debindexfile.h>
89 #include <apt-pkg/debmetaindex.h>
90 #include <apt-pkg/error.h>
91 #include <apt-pkg/init.h>
92 #include <apt-pkg/mmap.h>
93 #include <apt-pkg/pkgrecords.h>
94 #include <apt-pkg/sha1.h>
95 #include <apt-pkg/sourcelist.h>
96 #include <apt-pkg/sptr.h>
97 #include <apt-pkg/strutl.h>
98 #include <apt-pkg/tagfile.h>
100 #include <apr-1/apr_pools.h>
102 #include <sys/types.h>
103 #include <sys/stat.h>
104 #include <sys/sysctl.h>
105 #include <sys/param.h>
106 #include <sys/mount.h>
107 #include <sys/reboot.h>
114 #include <mach-o/nlist.h>
123 #include <Cytore.hpp>
126 #include <CydiaSubstrate/CydiaSubstrate.h>
127 #include "Menes/Menes.h"
129 #include "CyteKit/IndirectDelegate.h"
130 #include "CyteKit/PerlCompatibleRegEx.hpp"
131 #include "CyteKit/TableViewCell.h"
132 #include "CyteKit/WebScriptObject-Cyte.h"
133 #include "CyteKit/WebViewController.h"
134 #include "CyteKit/WebViewTableViewCell.h"
135 #include "CyteKit/stringWithUTF8Bytes.h"
137 #include "Cydia/MIMEAddress.h"
138 #include "Cydia/LoadingViewController.h"
139 #include "Cydia/ProgressEvent.h"
141 #include "SDURLCache/SDURLCache.h"
148 #define _timestamp ({ \
150 gettimeofday(&tv, NULL); \
151 tv.tv_sec * 1000000 + tv.tv_usec; \
154 typedef std::vector<class ProfileTime *> TimeList;
164 ProfileTime(const char *name) :
168 times_.push_back(this);
171 void AddTime(uint64_t time) {
178 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
190 ProfileTimer(ProfileTime &time) :
197 time_.AddTime(_timestamp - start_);
202 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
204 std::cerr << "========" << std::endl;
207 #define _profile(name) { \
208 static ProfileTime name(#name); \
209 ProfileTimer _ ## name(name);
214 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
215 #define synchronized(lock) \
216 synchronized(static_cast<NSObject *>(lock))
218 extern NSString *Cydia_;
220 #define lprintf(args...) fprintf(stderr, args)
223 #define TraceLogging (1 && !ForRelease)
224 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
225 #define ProfileTimes (0 && !ForRelease)
226 #define ForSaurik (0 && !ForRelease)
227 #define LogBrowser (0 && !ForRelease)
228 #define TrackResize (0 && !ForRelease)
229 #define ManualRefresh (1 && !ForRelease)
230 #define ShowInternals (0 && !ForRelease)
231 #define AlwaysReload (0 && !ForRelease)
232 #define TryIndexedCollation (0 && !ForRelease)
236 #define _trace(args...)
241 #define _profile(name) {
244 #define PrintTimes() do {} while (false)
247 // Hash Functions/Structures {{{
248 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
256 static bool ShowPromoted_;
258 static NSString *Colon_;
260 static NSString *Error_;
261 static NSString *Warning_;
263 static bool AprilFools_;
265 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
267 static bool IsReachable(const char *name) {
268 SCNetworkReachabilityFlags flags; {
269 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
270 SCNetworkReachabilityGetFlags(reachability, &flags);
271 CFRelease(reachability);
274 // XXX: this elaborate mess is what Apple is using to determine this? :(
275 // XXX: do we care if the user has to intervene? maybe that's ok?
277 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
278 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
279 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
280 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
281 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
282 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
287 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
289 static _finline NSString *CydiaURL(NSString *path) {
291 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
292 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
293 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
294 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
295 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
297 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
300 static void ReapZombie(pid_t pid) {
303 if (waitpid(pid, &status, 0) == -1)
309 static _finline void UpdateExternalStatus(uint64_t newStatus) {
311 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
312 notify_set_state(notify_token, newStatus);
313 notify_cancel(notify_token);
315 notify_post("com.saurik.Cydia.status");
318 static CGFloat CYStatusBarHeight() {
319 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
320 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
323 /* NSForcedOrderingSearch doesn't work on the iPhone */
324 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
325 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
326 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
328 /* Insertion Sort {{{ */
330 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
331 const char *ptr = (const char *)list;
333 CFIndex half = count / 2;
334 const char *probe = ptr + elementSize * half;
335 CFComparisonResult cr = comparator(element, probe, context);
336 if (0 == cr) return (probe - (const char *)list) / elementSize;
337 ptr = (cr < 0) ? ptr : probe + elementSize;
338 count = (cr < 0) ? half : (half + (count & 1) - 1);
340 return (ptr - (const char *)list) / elementSize;
343 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
344 const char *ptr = (const char *)list;
346 CFIndex half = count / 2;
347 const char *probe = ptr + elementSize * half;
348 CFComparisonResult cr = comparator(element, probe, context);
349 if (0 == cr) return (probe - (const char *)list) / elementSize;
350 ptr = (cr < 0) ? ptr : probe + elementSize;
351 count = (cr < 0) ? half : (half + (count & 1) - 1);
353 return (ptr - (const char *)list) / elementSize;
356 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
357 if (range.length == 0)
359 const void **values(new const void *[range.length]);
360 CFArrayGetValues(array, range, values);
362 #if HistogramInsertionSort > 0
363 uint32_t total(0), *offsets(new uint32_t[range.length]);
366 for (CFIndex index(1); index != range.length; ++index) {
367 const void *value(values[index]);
368 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
369 CFIndex correct(index);
370 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
371 #if HistogramInsertionSort > 1
372 NSLog(@"%@ < %@", value, values[correct - 1]);
377 if (correct != index) {
378 size_t offset(index - correct);
379 #if HistogramInsertionSort
383 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
385 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
386 values[correct] = value;
390 CFArrayReplaceValues(array, range, values, range.length);
393 #if HistogramInsertionSort > 0
394 for (CFIndex index(0); index != range.length; ++index)
395 if (offsets[index] != 0)
396 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
397 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
404 /* Apple Bug Fixes {{{ */
405 @implementation UIWebDocumentView (Cydia)
407 - (void) _setScrollerOffset:(CGPoint)offset {
408 UIScroller *scroller([self _scroller]);
410 CGSize size([scroller contentSize]);
411 CGSize bounds([scroller bounds].size);
414 max.x = size.width - bounds.width;
415 max.y = size.height - bounds.height;
423 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
424 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
426 [scroller setOffset:offset];
432 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
433 size_t length([self length] - state->state);
436 else if (length > count)
438 for (size_t i(0); i != length; ++i)
439 objects[i] = [self item:state->state++];
440 state->itemsPtr = objects;
441 state->mutationsPtr = (unsigned long *) self;
445 /* Cydia NSString Additions {{{ */
446 @interface NSString (Cydia)
447 - (NSComparisonResult) compareByPath:(NSString *)other;
448 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
451 @implementation NSString (Cydia)
453 - (NSComparisonResult) compareByPath:(NSString *)other {
454 NSString *prefix = [self commonPrefixWithString:other options:0];
455 size_t length = [prefix length];
457 NSRange lrange = NSMakeRange(length, [self length] - length);
458 NSRange rrange = NSMakeRange(length, [other length] - length);
460 lrange = [self rangeOfString:@"/" options:0 range:lrange];
461 rrange = [other rangeOfString:@"/" options:0 range:rrange];
463 NSComparisonResult value;
465 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
466 value = NSOrderedSame;
467 else if (lrange.location == NSNotFound)
468 value = NSOrderedAscending;
469 else if (rrange.location == NSNotFound)
470 value = NSOrderedDescending;
472 value = NSOrderedSame;
474 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
475 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
476 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
477 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
479 NSComparisonResult result = [lpath compare:rpath];
480 return result == NSOrderedSame ? value : result;
483 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
484 return [(id)CFURLCreateStringByAddingPercentEscapes(
489 kCFStringEncodingUTF8
496 /* C++ NSString Wrapper Cache {{{ */
497 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
498 return size == 0 ? NULL :
499 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
500 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
503 static _finline CFStringRef CYStringCreate(const char *data) {
504 return CYStringCreate(data, strlen(data));
513 _finline void clear_() {
514 if (cache_ != NULL) {
521 _finline bool empty() const {
525 _finline size_t size() const {
529 _finline char *data() const {
533 _finline void clear() {
538 _finline CYString() :
545 _finline ~CYString() {
549 void operator =(const CYString &rhs) {
553 if (rhs.cache_ == nil)
556 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
559 void copy(apr_pool_t *pool) {
560 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
561 memcpy(temp, data_, size_);
566 void set(apr_pool_t *pool, const char *data, size_t size) {
572 data_ = const_cast<char *>(data);
580 _finline void set(apr_pool_t *pool, const char *data) {
581 set(pool, data, data == NULL ? 0 : strlen(data));
584 _finline void set(apr_pool_t *pool, const std::string &rhs) {
585 set(pool, rhs.data(), rhs.size());
588 bool operator ==(const CYString &rhs) const {
589 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
592 _finline operator CFStringRef() {
594 cache_ = CYStringCreate(data_, size_);
598 _finline operator id() {
599 return (NSString *) static_cast<CFStringRef>(*this);
602 _finline operator const char *() {
603 return reinterpret_cast<const char *>(data_);
607 /* C++ NSString Algorithm Adapters {{{ */
609 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
612 struct NSStringMapHash :
613 std::unary_function<NSString *, size_t>
615 _finline size_t operator ()(NSString *value) const {
616 return CFStringHashNSString((CFStringRef) value);
620 struct NSStringMapLess :
621 std::binary_function<NSString *, NSString *, bool>
623 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
624 return [lhs compare:rhs] == NSOrderedAscending;
628 struct NSStringMapEqual :
629 std::binary_function<NSString *, NSString *, bool>
631 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
632 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
633 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
634 //[lhs isEqualToString:rhs];
639 /* CoreGraphics Primitives {{{ */
644 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
645 CGFloat color[] = {red, green, blue, alpha};
646 return CGColorCreate(space, color);
655 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
656 color_(Create_(space, red, green, blue, alpha))
658 Set(space, red, green, blue, alpha);
663 CGColorRelease(color_);
670 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
672 color_ = Create_(space, red, green, blue, alpha);
675 operator CGColorRef() {
681 /* Random Global Variables {{{ */
682 static int PulseInterval_ = 500000;
684 static const NSString *UI_;
687 static bool RestartSubstrate_;
688 static NSArray *Finishes_;
690 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
691 #define NotifyConfig_ "/etc/notify.conf"
693 static bool Queuing_;
695 static CYColor Blue_;
696 static CYColor Blueish_;
697 static CYColor Black_;
699 static CYColor White_;
700 static CYColor Gray_;
701 static CYColor Green_;
702 static CYColor Purple_;
703 static CYColor Purplish_;
705 static UIColor *InstallingColor_;
706 static UIColor *RemovingColor_;
708 static NSString *App_;
710 static BOOL Advanced_;
711 static BOOL Ignored_;
713 static _H<UIFont> Font12_;
714 static _H<UIFont> Font12Bold_;
715 static _H<UIFont> Font14_;
716 static _H<UIFont> Font18Bold_;
717 static _H<UIFont> Font22Bold_;
719 static const char *Machine_ = NULL;
720 static _H<NSString> System_;
721 static NSString *SerialNumber_ = nil;
722 static NSString *ChipID_ = nil;
723 static NSString *BBSNum_ = nil;
724 static _H<NSString> Token_;
725 static NSString *UniqueID_ = nil;
726 static _H<NSString> UserAgent_;
727 static _H<NSString> Product_;
728 static _H<NSString> Safari_;
730 static CFLocaleRef Locale_;
731 static NSArray *Languages_;
732 static CGColorSpaceRef space_;
734 static NSDictionary *SectionMap_;
735 static NSMutableDictionary *Metadata_;
736 static _transient NSMutableDictionary *Settings_;
737 static _transient NSString *Role_;
738 static _transient NSMutableDictionary *Packages_;
739 static _transient NSMutableDictionary *Values_;
740 static _transient NSMutableDictionary *Sections_;
741 _H<NSMutableDictionary> Sources_;
742 static _transient NSNumber *Version_;
747 static CGFloat ScreenScale_;
748 static NSString *Idiom_;
749 static _H<NSString> Firmware_;
750 static NSString *Major_;
752 static _H<NSMutableDictionary> SessionData_;
753 static _H<NSObject> HostConfig_;
754 static _H<NSMutableSet> BridgedHosts_;
755 static _H<NSMutableSet> TokenHosts_;
756 static _H<NSMutableSet> InsecureHosts_;
757 static _H<NSMutableSet> PipelinedHosts_;
758 static _H<NSMutableSet> CachedURLs_;
760 static NSString *kCydiaProgressEventTypeError = @"Error";
761 static NSString *kCydiaProgressEventTypeInformation = @"Information";
762 static NSString *kCydiaProgressEventTypeStatus = @"Status";
763 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
766 /* Display Helpers {{{ */
767 inline float Interpolate(float begin, float end, float fraction) {
768 return (end - begin) * fraction + begin;
771 static _finline const char *StripVersion_(const char *version) {
772 const char *colon(strchr(version, ':'));
773 return colon == NULL ? version : colon + 1;
776 NSString *LocalizeSection(NSString *section) {
777 static Pcre title_r("^(.*?) \\((.*)\\)$");
778 if (title_r(section)) {
779 NSString *parent(title_r[1]);
780 NSString *child(title_r[2]);
782 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
783 LocalizeSection(parent),
784 LocalizeSection(child)
788 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
791 NSString *Simplify(NSString *title) {
792 const char *data = [title UTF8String];
793 size_t size = [title length];
795 static Pcre square_r("^\\[(.*)\\]$");
796 if (square_r(data, size))
797 return Simplify(square_r[1]);
799 static Pcre paren_r("^\\((.*)\\)$");
800 if (paren_r(data, size))
801 return Simplify(paren_r[1]);
803 static Pcre title_r("^(.*?) \\((.*)\\)$");
804 if (title_r(data, size))
805 return Simplify(title_r[1]);
811 NSString *GetLastUpdate() {
812 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
815 return UCLocalize("NEVER_OR_UNKNOWN");
817 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
818 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
820 CFRelease(formatter);
822 return [(NSString *) formatted autorelease];
825 bool isSectionVisible(NSString *section) {
826 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
827 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
828 return hidden == nil || ![hidden boolValue];
831 static NSObject *CYIOGetValue(const char *path, NSString *property) {
832 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
833 if (entry == MACH_PORT_NULL)
836 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
837 IOObjectRelease(entry);
841 return [(id) value autorelease];
844 static NSString *CYHex(NSData *data, bool reverse = false) {
848 size_t length([data length]);
849 uint8_t bytes[length];
850 [data getBytes:bytes];
852 char string[length * 2 + 1];
853 for (size_t i(0); i != length; ++i)
854 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
856 return [NSString stringWithUTF8String:string];
861 /* Delegate Prototypes {{{ */
864 @class CydiaProgressEvent;
866 @protocol DatabaseDelegate
867 - (void) repairWithSelector:(SEL)selector;
868 - (void) setConfigurationData:(NSString *)data;
869 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
872 @class CYPackageController;
874 @protocol CydiaDelegate
875 - (void) returnToCydia;
877 - (void) retainNetworkActivityIndicator;
878 - (void) releaseNetworkActivityIndicator;
879 - (void) clearPackage:(Package *)package;
880 - (void) installPackage:(Package *)package;
881 - (void) installPackages:(NSArray *)packages;
882 - (void) removePackage:(Package *)package;
883 - (void) beginUpdate;
885 - (void) distUpgrade;
888 - (void) _saveConfig;
890 - (void) addSource:(NSDictionary *)source;
891 - (void) addTrivialSource:(NSString *)href;
892 - (void) showSettings;
893 - (UIProgressHUD *) addProgressHUD;
894 - (void) removeProgressHUD:(UIProgressHUD *)hud;
895 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
896 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
900 /* Status Delegation {{{ */
902 public pkgAcquireStatus
905 _transient NSObject<ProgressDelegate> *delegate_;
915 void setDelegate(NSObject<ProgressDelegate> *delegate) {
916 delegate_ = delegate;
919 NSObject<ProgressDelegate> *getDelegate() const {
923 virtual bool MediaChange(std::string media, std::string drive) {
927 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
931 virtual void Fetch(pkgAcquire::ItemDesc &item) {
932 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
933 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
934 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
937 virtual void Done(pkgAcquire::ItemDesc &item) {
938 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
939 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
940 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
943 virtual void Fail(pkgAcquire::ItemDesc &item) {
945 item.Owner->Status == pkgAcquire::Item::StatIdle ||
946 item.Owner->Status == pkgAcquire::Item::StatDone
950 std::string &error(item.Owner->ErrorText);
954 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
955 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
958 virtual bool Pulse(pkgAcquire *Owner) {
959 bool value = pkgAcquireStatus::Pulse(Owner);
962 double(CurrentBytes + CurrentItems) /
963 double(TotalBytes + TotalItems)
966 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
967 [NSNumber numberWithDouble:percent], @"Percent",
969 [NSNumber numberWithDouble:CurrentBytes], @"Current",
970 [NSNumber numberWithDouble:TotalBytes], @"Total",
971 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
972 nil] waitUntilDone:YES];
974 if (value && ![delegate_ isProgressCancelled])
982 _finline bool WasCancelled() const {
986 virtual void Start() {
987 pkgAcquireStatus::Start();
988 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
991 virtual void Stop() {
992 pkgAcquireStatus::Stop();
993 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
994 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
998 /* Database Interface {{{ */
999 typedef std::map< unsigned long, _H<Source> > SourceMap;
1001 @interface Database : NSObject {
1007 pkgCacheFile cache_;
1008 pkgDepCache::Policy *policy_;
1009 pkgRecords *records_;
1010 pkgProblemResolver *resolver_;
1011 pkgAcquire *fetcher_;
1013 SPtr<pkgPackageManager> manager_;
1014 pkgSourceList *list_;
1016 SourceMap sourceMap_;
1017 _H<NSMutableArray> sourceList_;
1019 CFMutableArrayRef packages_;
1021 _transient NSObject<DatabaseDelegate> *delegate_;
1022 _transient NSObject<ProgressDelegate> *progress_;
1030 std::map<const char *, _H<NSString> > sections_;
1033 + (Database *) sharedInstance;
1036 - (void) _readCydia:(NSNumber *)fd;
1037 - (void) _readStatus:(NSNumber *)fd;
1038 - (void) _readOutput:(NSNumber *)fd;
1042 - (Package *) packageWithName:(NSString *)name;
1044 - (pkgCacheFile &) cache;
1045 - (pkgDepCache::Policy *) policy;
1046 - (pkgRecords *) records;
1047 - (pkgProblemResolver *) resolver;
1048 - (pkgAcquire &) fetcher;
1049 - (pkgSourceList &) list;
1050 - (NSArray *) packages;
1051 - (NSArray *) sources;
1052 - (Source *) sourceWithKey:(NSString *)key;
1053 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1061 - (void) updateWithStatus:(Status &)status;
1063 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1065 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1066 - (NSObject<ProgressDelegate> *) progressDelegate;
1068 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1070 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1074 /* ProgressEvent Implementation {{{ */
1075 @implementation CydiaProgressEvent
1077 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1078 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1081 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1082 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1083 [event setPackage:package];
1087 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1088 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1090 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1091 NSArray *fields([description componentsSeparatedByString:@" "]);
1092 [event setItem:fields];
1094 if ([fields count] > 3) {
1095 [event setPackage:[fields objectAtIndex:2]];
1096 [event setVersion:[fields objectAtIndex:3]];
1099 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1104 + (NSArray *) _attributeKeys {
1105 return [NSArray arrayWithObjects:
1115 - (NSArray *) attributeKeys {
1116 return [[self class] _attributeKeys];
1119 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1120 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1123 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1124 if ((self = [super init]) != nil) {
1130 - (NSString *) message {
1134 - (NSString *) type {
1138 - (NSArray *) item {
1139 return (id) item_ ?: [NSNull null];
1142 - (void) setItem:(NSArray *)item {
1146 - (NSString *) package {
1147 return (id) package_ ?: [NSNull null];
1150 - (void) setPackage:(NSString *)package {
1154 - (NSString *) url {
1155 return (id) url_ ?: [NSNull null];
1158 - (void) setURL:(NSString *)url {
1162 - (void) setVersion:(NSString *)version {
1166 - (NSString *) version {
1167 return (id) version_ ?: [NSNull null];
1170 - (NSString *) compound:(NSString *)value {
1172 NSString *mode(nil); {
1173 NSString *type([self type]);
1174 if ([type isEqualToString:kCydiaProgressEventTypeError])
1175 mode = UCLocalize("ERROR");
1176 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1177 mode = UCLocalize("WARNING");
1181 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1187 - (NSString *) compoundMessage {
1188 return [self compound:[self message]];
1191 - (NSString *) compoundTitle {
1194 if (package_ == nil)
1196 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1197 title = [package name];
1201 return [self compound:title];
1207 // Cytore Definitions {{{
1208 struct PackageValue :
1211 Cytore::Offset<PackageValue> next_;
1213 uint32_t index_ : 23;
1214 uint32_t subscribed_ : 1;
1231 Cytore::Offset<PackageValue> packages_[1 << 16];
1234 static Cytore::File<MetaValue> MetaFile_;
1236 // Cytore Helper Functions {{{
1237 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1238 SplitHash nhash = { hashlittle(name, length) };
1240 PackageValue *metadata;
1242 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1243 offset: if (offset->IsNull()) {
1244 *offset = MetaFile_.New<PackageValue>(length + 1);
1245 metadata = &MetaFile_.Get(*offset);
1247 if (metadata == NULL) {
1251 metadata = new PackageValue();
1252 memset(metadata, 0, sizeof(*metadata));
1255 memcpy(metadata->name_, name, length + 1);
1256 metadata->nhash_ = nhash.u16[1];
1258 metadata = &MetaFile_.Get(*offset);
1260 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1261 offset = &metadata->next_;
1269 static void PackageImport(const void *key, const void *value, void *context) {
1270 bool &fail(*reinterpret_cast<bool *>(context));
1273 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1274 NSLog(@"failed to import package %@", key);
1278 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1279 NSDictionary *package((NSDictionary *) value);
1281 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1282 if ([subscribed boolValue] && !metadata->subscribed_)
1283 metadata->subscribed_ = true;
1285 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1286 time_t time([date timeIntervalSince1970]);
1287 if (metadata->first_ > time || metadata->first_ == 0)
1288 metadata->first_ = time;
1291 NSDate *date([package objectForKey:@"LastSeen"]);
1292 NSString *version([package objectForKey:@"LastVersion"]);
1294 if (date != nil && version != nil) {
1295 time_t time([date timeIntervalSince1970]);
1296 if (metadata->last_ < time || metadata->last_ == 0)
1297 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1298 size_t length(strlen(buffer));
1299 uint16_t vhash(hashlittle(buffer, length));
1301 size_t capped(std::min<size_t>(8, length));
1302 char *latest(buffer + length - capped);
1304 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1305 metadata->vhash_ = vhash;
1307 metadata->last_ = time;
1313 /* Source Class {{{ */
1314 @interface Source : NSObject {
1316 Database *database_;
1319 CYString depiction_;
1320 CYString description_;
1326 CYString distribution_;
1332 _H<NSString> authority_;
1334 CYString defaultIcon_;
1336 _H<NSMutableDictionary> record_;
1340 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1342 - (NSComparisonResult) compareByName:(Source *)source;
1344 - (NSString *) depictionForPackage:(NSString *)package;
1345 - (NSString *) supportForPackage:(NSString *)package;
1347 - (metaIndex *) metaIndex;
1348 - (NSDictionary *) record;
1351 - (NSString *) rooturi;
1352 - (NSString *) distribution;
1353 - (NSString *) type;
1356 - (NSString *) host;
1358 - (NSString *) name;
1359 - (NSString *) shortDescription;
1360 - (NSString *) label;
1361 - (NSString *) origin;
1362 - (NSString *) version;
1364 - (NSString *) defaultIcon;
1365 - (NSURL *) iconURL;
1369 @implementation Source
1373 distribution_.clear();
1378 description_.clear();
1384 defaultIcon_.clear();
1391 + (NSString *) webScriptNameForSelector:(SEL)selector {
1393 else if (selector == @selector(addSection:))
1394 return @"addSection";
1395 else if (selector == @selector(getField:))
1397 else if (selector == @selector(removeSection:))
1398 return @"removeSection";
1399 else if (selector == @selector(remove))
1405 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1406 return [self webScriptNameForSelector:selector] == nil;
1409 + (NSArray *) _attributeKeys {
1410 return [NSArray arrayWithObjects:
1421 @"shortDescription",
1428 - (NSArray *) attributeKeys {
1429 return [[self class] _attributeKeys];
1432 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1433 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1436 - (metaIndex *) metaIndex {
1440 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1443 trusted_ = index->IsTrusted();
1445 uri_.set(pool, index->GetURI());
1446 distribution_.set(pool, index->GetDist());
1447 type_.set(pool, index->GetType());
1449 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1450 if (dindex != NULL) {
1451 base_.set(pool, dindex->MetaIndexURI(""));
1454 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1457 pkgTagFile tags(&fd);
1459 pkgTagSection section;
1466 {"default-icon", &defaultIcon_},
1467 {"depiction", &depiction_},
1468 {"description", &description_},
1470 {"origin", &origin_},
1471 {"support", &support_},
1472 {"version", &version_},
1475 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1476 const char *start, *end;
1478 if (section.Find(names[i].name_, start, end)) {
1479 CYString &value(*names[i].value_);
1480 value.set(pool, start, end - start);
1486 record_ = [Sources_ objectForKey:[self key]];
1488 NSURL *url([NSURL URLWithString:uri_]);
1492 host_ = [host_ lowercaseString];
1497 authority_ = [url path];
1500 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1501 if ((self = [super init]) != nil) {
1502 era_ = [database era];
1503 database_ = database;
1506 [self setMetaIndex:index inPool:pool];
1510 - (NSString *) getField:(NSString *)name {
1511 @synchronized (database_) {
1512 if ([database_ era] != era_ || index_ == NULL)
1515 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1520 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1525 pkgTagFile tags(&fd);
1527 pkgTagSection section;
1530 const char *start, *end;
1531 if (!section.Find([name UTF8String], start, end))
1532 return (NSString *) [NSNull null];
1534 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1537 - (NSComparisonResult) compareByName:(Source *)source {
1538 NSString *lhs = [self name];
1539 NSString *rhs = [source name];
1541 if ([lhs length] != 0 && [rhs length] != 0) {
1542 unichar lhc = [lhs characterAtIndex:0];
1543 unichar rhc = [rhs characterAtIndex:0];
1545 if (isalpha(lhc) && !isalpha(rhc))
1546 return NSOrderedAscending;
1547 else if (!isalpha(lhc) && isalpha(rhc))
1548 return NSOrderedDescending;
1551 return [lhs compare:rhs options:LaxCompareOptions_];
1554 - (NSString *) depictionForPackage:(NSString *)package {
1555 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1558 - (NSString *) supportForPackage:(NSString *)package {
1559 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1562 - (NSArray *) sections {
1563 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1566 - (void) _addSection:(NSString *)section {
1569 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1570 if (![sections containsObject:section]) {
1571 [sections addObject:section];
1575 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1580 - (bool) addSection:(NSString *)section {
1584 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1588 - (void) _removeSection:(NSString *)section {
1592 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1593 if ([sections containsObject:section]) {
1594 [sections removeObject:section];
1599 - (bool) removeSection:(NSString *)section {
1603 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1608 [Sources_ removeObjectForKey:[self key]];
1613 bool value(record_ != nil);
1614 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1618 - (NSDictionary *) record {
1626 - (NSString *) rooturi {
1630 - (NSString *) distribution {
1631 return distribution_;
1634 - (NSString *) type {
1638 - (NSString *) baseuri {
1639 return base_.empty() ? nil : (id) base_;
1642 - (NSString *) iconuri {
1643 if (NSString *base = [self baseuri])
1644 return [base stringByAppendingString:@"CydiaIcon.png"];
1649 - (NSURL *) iconURL {
1650 if (NSString *uri = [self iconuri])
1651 return [NSURL URLWithString:uri];
1655 - (NSString *) key {
1656 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1659 - (NSString *) host {
1663 - (NSString *) name {
1664 return origin_.empty() ? (id) authority_ : origin_;
1667 - (NSString *) shortDescription {
1668 return description_;
1671 - (NSString *) label {
1672 return label_.empty() ? (id) authority_ : label_;
1675 - (NSString *) origin {
1679 - (NSString *) version {
1683 - (NSString *) defaultIcon {
1684 return defaultIcon_;
1689 /* CydiaOperation Class {{{ */
1690 @interface CydiaOperation : NSObject {
1691 _H<NSString> operator_;
1692 _H<NSString> value_;
1695 - (NSString *) operator;
1696 - (NSString *) value;
1700 @implementation CydiaOperation
1702 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1703 if ((self = [super init]) != nil) {
1704 operator_ = [NSString stringWithUTF8String:_operator];
1705 value_ = [NSString stringWithUTF8String:value];
1709 + (NSArray *) _attributeKeys {
1710 return [NSArray arrayWithObjects:
1716 - (NSArray *) attributeKeys {
1717 return [[self class] _attributeKeys];
1720 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1721 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1724 - (NSString *) operator {
1728 - (NSString *) value {
1734 /* CydiaClause Class {{{ */
1735 @interface CydiaClause : NSObject {
1736 _H<NSString> package_;
1737 _H<CydiaOperation> version_;
1740 - (NSString *) package;
1741 - (CydiaOperation *) version;
1745 @implementation CydiaClause
1747 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1748 if ((self = [super init]) != nil) {
1749 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1751 if (const char *version = dep.TargetVer())
1752 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1754 version_ = (id) [NSNull null];
1758 + (NSArray *) _attributeKeys {
1759 return [NSArray arrayWithObjects:
1765 - (NSArray *) attributeKeys {
1766 return [[self class] _attributeKeys];
1769 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1770 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1773 - (NSString *) package {
1777 - (CydiaOperation *) version {
1783 /* CydiaRelation Class {{{ */
1784 @interface CydiaRelation : NSObject {
1785 _H<NSString> relationship_;
1786 _H<NSMutableArray> clauses_;
1789 - (NSString *) relationship;
1790 - (NSArray *) clauses;
1794 @implementation CydiaRelation
1796 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1797 if ((self = [super init]) != nil) {
1798 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1799 clauses_ = [NSMutableArray arrayWithCapacity:8];
1801 pkgCache::DepIterator start;
1802 pkgCache::DepIterator end;
1803 dep.GlobOr(start, end); // ++dep
1806 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1808 // yes, seriously. (wtf?)
1816 + (NSArray *) _attributeKeys {
1817 return [NSArray arrayWithObjects:
1823 - (NSArray *) attributeKeys {
1824 return [[self class] _attributeKeys];
1827 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1828 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1831 - (NSString *) relationship {
1832 return relationship_;
1835 - (NSArray *) clauses {
1839 - (void) addClause:(CydiaClause *)clause {
1840 [clauses_ addObject:clause];
1845 /* Package Class {{{ */
1846 struct ParsedPackage {
1850 CYString architecture_;
1853 CYString depiction_;
1863 @interface Package : NSObject {
1866 uint32_t essential_ : 1;
1867 uint32_t obsolete_ : 1;
1868 uint32_t ignored_ : 1;
1869 uint32_t pooled_ : 1;
1875 _transient Database *database_;
1877 pkgCache::VerIterator version_;
1878 pkgCache::PkgIterator iterator_;
1879 pkgCache::VerFileIterator file_;
1885 CYString installed_;
1887 const char *section_;
1888 _transient NSString *section$_;
1892 PackageValue *metadata_;
1893 ParsedPackage *parsed_;
1895 _H<NSMutableArray> tags_;
1898 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1899 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1901 - (pkgCache::PkgIterator) iterator;
1904 - (NSString *) section;
1905 - (NSString *) simpleSection;
1907 - (NSString *) longSection;
1908 - (NSString *) shortSection;
1912 - (MIMEAddress *) maintainer;
1914 - (NSString *) longDescription;
1915 - (NSString *) shortDescription;
1918 - (PackageValue *) metadata;
1921 - (bool) subscribed;
1922 - (bool) setSubscribed:(bool)subscribed;
1926 - (NSString *) latest;
1927 - (NSString *) installed;
1928 - (BOOL) uninstalled;
1931 - (BOOL) upgradableAndEssential:(BOOL)essential;
1934 - (BOOL) unfiltered;
1938 - (BOOL) halfConfigured;
1939 - (BOOL) halfInstalled;
1941 - (NSString *) mode;
1944 - (NSString *) name;
1946 - (NSString *) homepage;
1947 - (NSString *) depiction;
1948 - (MIMEAddress *) author;
1950 - (NSString *) support;
1952 - (NSArray *) files;
1953 - (NSArray *) warnings;
1954 - (NSArray *) applications;
1956 - (Source *) source;
1959 - (BOOL) matches:(NSArray *)query;
1961 - (bool) hasSupportingRole;
1962 - (BOOL) hasTag:(NSString *)tag;
1963 - (NSString *) primaryPurpose;
1964 - (NSArray *) purposes;
1965 - (bool) isCommercial;
1967 - (void) setIndex:(size_t)index;
1969 - (CYString &) cyname;
1971 - (uint32_t) compareBySection:(NSArray *)sections;
1976 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1977 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1978 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1979 - (bool) isVisibleInSection:(NSString *)section;
1980 - (bool) isVisibleInSource:(Source *)source;
1984 uint32_t PackageChangesRadix(Package *self, void *) {
1989 uint32_t timestamp : 30;
1990 uint32_t ignored : 1;
1991 uint32_t upgradable : 1;
1995 bool upgradable([self upgradableAndEssential:YES]);
1996 value.bits.upgradable = upgradable ? 1 : 0;
1999 value.bits.timestamp = 0;
2000 value.bits.ignored = [self ignored] ? 0 : 1;
2001 value.bits.upgradable = 1;
2003 value.bits.timestamp = [self seen] >> 2;
2004 value.bits.ignored = 0;
2005 value.bits.upgradable = 0;
2008 return _not(uint32_t) - value.key;
2011 uint32_t PackagePrefixRadix(Package *self, void *context) {
2012 size_t offset(reinterpret_cast<size_t>(context));
2013 CYString &name([self cyname]);
2015 size_t size(name.size());
2018 char *text(name.data());
2021 if (!isdigit(text[0]))
2025 while (size != digits && isdigit(text[digits]))
2033 if (offset == 0 && zeros != 0) {
2034 memset(data, '0', zeros);
2035 memcpy(data + zeros, text, 4 - zeros);
2037 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2038 if (size <= offset - zeros)
2041 text += offset - zeros;
2042 size -= offset - zeros;
2045 memcpy(data, text, 4);
2047 memcpy(data, text, size);
2048 memset(data + size, 0, 4 - size);
2051 for (size_t i(0); i != 4; ++i)
2052 if (isalpha(data[i]))
2060 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2062 /* XXX: ntohl may be more honest */
2063 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2066 CYString &(*PackageName)(Package *self, SEL sel);
2068 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2069 _profile(PackageNameCompare)
2070 CYString &lhi(PackageName(lhs, @selector(cyname)));
2071 CYString &rhi(PackageName(rhs, @selector(cyname)));
2072 CFStringRef lhn(lhi), rhn(rhi);
2075 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2076 else if (rhn == NULL)
2077 return NSOrderedDescending;
2079 _profile(PackageNameCompare$NumbersLast)
2080 if (!lhi.empty() && !rhi.empty()) {
2081 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2082 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2083 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2084 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2085 return lha ? NSOrderedAscending : NSOrderedDescending;
2089 CFIndex length = CFStringGetLength(lhn);
2091 _profile(PackageNameCompare$Compare)
2092 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2097 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2098 return PackageNameCompare(*lhs, *rhs, context);
2101 struct PackageNameOrdering :
2102 std::binary_function<Package *, Package *, bool>
2104 _finline bool operator ()(Package *lhs, Package *rhs) const {
2105 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2109 @implementation Package
2111 - (NSString *) description {
2112 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2117 apr_pool_destroy(pool_);
2118 if (parsed_ != NULL)
2123 + (NSString *) webScriptNameForSelector:(SEL)selector {
2125 else if (selector == @selector(clear))
2127 else if (selector == @selector(getField:))
2129 else if (selector == @selector(hasTag:))
2131 else if (selector == @selector(install))
2133 else if (selector == @selector(remove))
2139 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2140 return [self webScriptNameForSelector:selector] == nil;
2143 + (NSArray *) _attributeKeys {
2144 return [NSArray arrayWithObjects:
2165 @"shortDescription",
2178 - (NSArray *) attributeKeys {
2179 return [[self class] _attributeKeys];
2182 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2183 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2186 - (NSArray *) relations {
2187 @synchronized (database_) {
2188 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2189 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2190 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2194 - (NSString *) architecture {
2196 @synchronized (database_) {
2197 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2200 - (NSString *) getField:(NSString *)name {
2201 @synchronized (database_) {
2202 if ([database_ era] != era_ || file_.end())
2205 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2207 const char *start, *end;
2208 if (!parser.Find([name UTF8String], start, end))
2209 return (NSString *) [NSNull null];
2211 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2215 if (parsed_ != NULL)
2217 @synchronized (database_) {
2218 if ([database_ era] != era_ || file_.end())
2221 ParsedPackage *parsed(new ParsedPackage);
2224 _profile(Package$parse)
2225 pkgRecords::Parser *parser;
2227 _profile(Package$parse$Lookup)
2228 parser = &[database_ records]->Lookup(file_);
2233 _profile(Package$parse$Find)
2238 {"architecture", &parsed->architecture_},
2239 {"icon", &parsed->icon_},
2240 {"depiction", &parsed->depiction_},
2241 {"homepage", &parsed->homepage_},
2242 {"website", &website},
2243 {"bugs", &parsed->bugs_},
2244 {"support", &parsed->support_},
2245 {"sponsor", &parsed->sponsor_},
2246 {"author", &parsed->author_},
2247 {"md5sum", &parsed->md5sum_},
2250 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2251 const char *start, *end;
2253 if (parser->Find(names[i].name_, start, end)) {
2254 CYString &value(*names[i].value_);
2255 _profile(Package$parse$Value)
2256 value.set(pool_, start, end - start);
2262 _profile(Package$parse$Tagline)
2263 const char *start, *end;
2264 if (parser->ShortDesc(start, end)) {
2265 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2268 while (stop != start && stop[-1] == '\r')
2270 parsed->tagline_.set(pool_, start, stop - start);
2274 _profile(Package$parse$Retain)
2275 if (parsed->homepage_.empty())
2276 parsed->homepage_ = website;
2277 if (parsed->homepage_ == parsed->depiction_)
2278 parsed->homepage_.clear();
2283 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2284 if ((self = [super init]) != nil) {
2285 _profile(Package$initWithVersion)
2287 apr_pool_create(&pool_, NULL);
2293 database_ = database;
2294 era_ = [database era];
2298 pkgCache::PkgIterator iterator(version.ParentPkg());
2299 iterator_ = iterator;
2301 _profile(Package$initWithVersion$Version)
2302 if (!version_.end())
2303 file_ = version_.FileList();
2305 pkgCache &cache([database_ cache]);
2306 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2310 _profile(Package$initWithVersion$Cache)
2311 name_.set(NULL, iterator.Display());
2313 latest_.set(NULL, StripVersion_(version_.VerStr()));
2315 pkgCache::VerIterator current(iterator.CurrentVer());
2317 installed_.set(NULL, StripVersion_(current.VerStr()));
2320 _profile(Package$initWithVersion$Tags)
2321 pkgCache::TagIterator tag(iterator.TagList());
2323 tags_ = [NSMutableArray arrayWithCapacity:8];
2325 const char *name(tag.Name());
2326 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2328 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2329 if (strcmp(name + 6, "enduser") == 0)
2331 else if (strcmp(name + 6, "hacker") == 0)
2333 else if (strcmp(name + 6, "developer") == 0)
2335 else if (strcmp(name + 6, "cydia") == 0)
2341 if (strncmp(name, "cydia::", 7) == 0) {
2342 if (strcmp(name + 7, "essential") == 0)
2344 else if (strcmp(name + 7, "obsolete") == 0)
2349 } while (!tag.end());
2353 _profile(Package$initWithVersion$Metadata)
2354 const char *mixed(iterator.Name());
2355 size_t size(strlen(mixed));
2356 char lower[size + 1];
2358 for (size_t i(0); i != size; ++i)
2359 lower[i] = mixed[i] | 0x20;
2362 PackageValue *metadata(PackageFind(lower, size));
2363 metadata_ = metadata;
2365 id_.set(NULL, metadata->name_, size);
2367 const char *latest(version_.VerStr());
2368 size_t length(strlen(latest));
2370 uint16_t vhash(hashlittle(latest, length));
2372 size_t capped(std::min<size_t>(8, length));
2373 latest = latest + length - capped;
2375 if (metadata->first_ == 0)
2376 metadata->first_ = now_;
2378 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2379 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2380 metadata->vhash_ = vhash;
2381 metadata->last_ = now_;
2382 } else if (metadata->last_ == 0)
2383 metadata->last_ = metadata->first_;
2386 _profile(Package$initWithVersion$Section)
2387 section_ = version_.Section();
2390 _profile(Package$initWithVersion$Flags)
2391 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2392 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2397 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2398 pkgCache::VerIterator version;
2400 _profile(Package$packageWithIterator$GetCandidateVer)
2401 version = [database policy]->GetCandidateVer(iterator);
2409 _profile(Package$packageWithIterator$Allocate)
2410 package = [Package allocWithZone:zone];
2413 _profile(Package$packageWithIterator$Initialize)
2415 initWithVersion:version
2422 _profile(Package$packageWithIterator$Autorelease)
2423 package = [package autorelease];
2429 - (pkgCache::PkgIterator) iterator {
2433 - (NSString *) section {
2434 if (section$_ == nil) {
2435 if (section_ == NULL)
2438 _profile(Package$section$mappedSectionForPointer)
2439 section$_ = [database_ mappedSectionForPointer:section_];
2444 - (NSString *) simpleSection {
2445 if (NSString *section = [self section])
2446 return Simplify(section);
2451 - (NSString *) longSection {
2452 return LocalizeSection([self section]);
2455 - (NSString *) shortSection {
2456 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2459 - (NSString *) uri {
2462 pkgIndexFile *index;
2463 pkgCache::PkgFileIterator file(file_.File());
2464 if (![database_ list].FindIndex(file, index))
2466 return [NSString stringWithUTF8String:iterator_->Path];
2467 //return [NSString stringWithUTF8String:file.Site()];
2468 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2472 - (MIMEAddress *) maintainer {
2473 @synchronized (database_) {
2474 if ([database_ era] != era_ || file_.end())
2477 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2478 const std::string &maintainer(parser->Maintainer());
2479 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2482 - (NSString *) md5sum {
2483 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2487 @synchronized (database_) {
2488 if ([database_ era] != era_ || version_.end())
2491 return version_->InstalledSize;
2494 - (NSString *) longDescription {
2495 @synchronized (database_) {
2496 if ([database_ era] != era_ || file_.end())
2499 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2500 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2502 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2503 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2504 if ([lines count] < 2)
2507 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2508 for (size_t i(1), e([lines count]); i != e; ++i) {
2509 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2510 [trimmed addObject:trim];
2513 return [trimmed componentsJoinedByString:@"\n"];
2516 - (NSString *) shortDescription {
2517 if (parsed_ != NULL)
2518 return static_cast<NSString *>(parsed_->tagline_);
2520 @synchronized (database_) {
2521 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2523 const char *start, *end;
2524 if (!parser.ShortDesc(start, end))
2527 if (end - start > 200)
2531 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2534 while (end != start && end[-1] == '\r')
2538 return [(id) CYStringCreate(start, end - start) autorelease];
2542 _profile(Package$index)
2543 CFStringRef name((CFStringRef) [self name]);
2544 if (CFStringGetLength(name) == 0)
2546 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2547 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2549 return toupper(character);
2553 - (PackageValue *) metadata {
2558 PackageValue *metadata([self metadata]);
2559 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2562 - (bool) subscribed {
2563 return [self metadata]->subscribed_;
2566 - (bool) setSubscribed:(bool)subscribed {
2567 PackageValue *metadata([self metadata]);
2568 if (metadata->subscribed_ == subscribed)
2570 metadata->subscribed_ = subscribed;
2578 - (NSString *) latest {
2582 - (NSString *) installed {
2586 - (BOOL) uninstalled {
2587 return installed_.empty();
2591 return !version_.end();
2594 - (BOOL) upgradableAndEssential:(BOOL)essential {
2595 _profile(Package$upgradableAndEssential)
2596 pkgCache::VerIterator current(iterator_.CurrentVer());
2598 return essential && essential_;
2600 return !version_.end() && version_ != current;
2604 - (BOOL) essential {
2609 return [database_ cache][iterator_].InstBroken();
2612 - (BOOL) unfiltered {
2613 _profile(Package$unfiltered$obsolete)
2614 if (_unlikely(obsolete_))
2618 _profile(Package$unfiltered$hasSupportingRole)
2619 if (_unlikely(![self hasSupportingRole]))
2627 if (![self unfiltered])
2632 _profile(Package$visible$section)
2633 section = [self section];
2636 _profile(Package$visible$isSectionVisible)
2637 if (!isSectionVisible(section))
2645 unsigned char current(iterator_->CurrentState);
2646 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2649 - (BOOL) halfConfigured {
2650 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2653 - (BOOL) halfInstalled {
2654 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2658 @synchronized (database_) {
2659 if ([database_ era] != era_ || iterator_.end())
2662 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2663 return state.Mode != pkgDepCache::ModeKeep;
2666 - (NSString *) mode {
2667 @synchronized (database_) {
2668 if ([database_ era] != era_ || iterator_.end())
2671 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2673 switch (state.Mode) {
2674 case pkgDepCache::ModeDelete:
2675 if ((state.iFlags & pkgDepCache::Purge) != 0)
2679 case pkgDepCache::ModeKeep:
2680 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2681 return @"REINSTALL";
2682 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2686 case pkgDepCache::ModeInstall:
2687 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2688 return @"REINSTALL";
2689 else*/ switch (state.Status) {
2691 return @"DOWNGRADE";
2697 return @"NEW_INSTALL";
2708 - (NSString *) name {
2709 return name_.empty() ? id_ : name_;
2712 - (UIImage *) icon {
2713 NSString *section = [self simpleSection];
2716 if (parsed_ != NULL)
2717 if (NSString *href = parsed_->icon_)
2718 if ([href hasPrefix:@"file:///"])
2719 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2720 if (icon == nil) if (section != nil)
2721 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2722 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2723 if ([dicon hasPrefix:@"file:///"])
2724 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2726 icon = [UIImage applicationImageNamed:@"unknown.png"];
2730 - (NSString *) homepage {
2731 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2734 - (NSString *) depiction {
2735 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2738 - (MIMEAddress *) sponsor {
2739 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2742 - (MIMEAddress *) author {
2743 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2746 - (NSString *) support {
2747 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2750 - (NSArray *) files {
2751 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2752 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2755 fin.open([path UTF8String]);
2760 while (std::getline(fin, line))
2761 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2766 - (NSString *) state {
2767 @synchronized (database_) {
2768 if ([database_ era] != era_ || file_.end())
2771 switch (iterator_->CurrentState) {
2772 case pkgCache::State::NotInstalled:
2773 return @"NotInstalled";
2774 case pkgCache::State::UnPacked:
2776 case pkgCache::State::HalfConfigured:
2777 return @"HalfConfigured";
2778 case pkgCache::State::HalfInstalled:
2779 return @"HalfInstalled";
2780 case pkgCache::State::ConfigFiles:
2781 return @"ConfigFiles";
2782 case pkgCache::State::Installed:
2783 return @"Installed";
2784 case pkgCache::State::TriggersAwaited:
2785 return @"TriggersAwaited";
2786 case pkgCache::State::TriggersPending:
2787 return @"TriggersPending";
2790 return (NSString *) [NSNull null];
2793 - (NSString *) selection {
2794 @synchronized (database_) {
2795 if ([database_ era] != era_ || file_.end())
2798 switch (iterator_->SelectedState) {
2799 case pkgCache::State::Unknown:
2801 case pkgCache::State::Install:
2803 case pkgCache::State::Hold:
2805 case pkgCache::State::DeInstall:
2806 return @"DeInstall";
2807 case pkgCache::State::Purge:
2811 return (NSString *) [NSNull null];
2814 - (NSArray *) warnings {
2815 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2816 const char *name(iterator_.Name());
2818 size_t length(strlen(name));
2819 if (length < 2) invalid:
2820 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2821 else for (size_t i(0); i != length; ++i)
2823 /* XXX: technically this is not allowed */
2824 (name[i] < 'A' || name[i] > 'Z') &&
2825 (name[i] < 'a' || name[i] > 'z') &&
2826 (name[i] < '0' || name[i] > '9') &&
2827 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2830 if (strcmp(name, "cydia") != 0) {
2833 bool _private = false;
2836 bool repository = [[self section] isEqualToString:@"Repositories"];
2838 if (NSArray *files = [self files])
2839 for (NSString *file in files)
2840 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2842 else if (!user && [file isEqualToString:@"/User"])
2844 else if (!_private && [file isEqualToString:@"/private"])
2846 else if (!stash && [file isEqualToString:@"/var/stash"])
2849 /* XXX: this is not sensitive enough. only some folders are valid. */
2850 if (cydia && !repository)
2851 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2853 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2855 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2857 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2860 return [warnings count] == 0 ? nil : warnings;
2863 - (NSArray *) applications {
2864 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2866 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2868 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2869 if (NSArray *files = [self files])
2870 for (NSString *file in files)
2871 if (application_r(file)) {
2872 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2873 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2874 if ([id isEqualToString:me])
2877 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2879 display = application_r[1];
2881 NSString *bundle([file stringByDeletingLastPathComponent]);
2882 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2883 if (icon == nil || [icon length] == 0)
2885 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2887 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2888 [applications addObject:application];
2890 [application addObject:id];
2891 [application addObject:display];
2892 [application addObject:url];
2895 return [applications count] == 0 ? nil : applications;
2898 - (Source *) source {
2899 if (source_ == nil) {
2900 @synchronized (database_) {
2901 if ([database_ era] != era_ || file_.end())
2902 source_ = (Source *) [NSNull null];
2904 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2908 return source_ == (Source *) [NSNull null] ? nil : source_;
2915 - (BOOL) matches:(NSArray *)query {
2916 if (query == nil || [query count] == 0)
2925 string = [self name];
2926 length = [string length];
2928 for (NSString *term in query) {
2929 range = [string rangeOfString:term options:MatchCompareOptions_];
2930 if (range.location != NSNotFound)
2931 rank_ -= 6 * 1000000 / length;
2936 length = [string length];
2938 for (NSString *term in query) {
2939 range = [string rangeOfString:term options:MatchCompareOptions_];
2940 if (range.location != NSNotFound)
2941 rank_ -= 6 * 1000000 / length;
2945 string = [self shortDescription];
2946 length = [string length];
2947 NSUInteger stop(std::min<NSUInteger>(length, 200));
2949 for (NSString *term in query) {
2950 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2951 if (range.location != NSNotFound)
2952 rank_ -= 2 * 100000;
2958 - (bool) hasSupportingRole {
2963 if ([Role_ isEqualToString:@"User"])
2967 if ([Role_ isEqualToString:@"Hacker"])
2971 if ([Role_ isEqualToString:@"Developer"])
2976 - (NSArray *) tags {
2980 - (BOOL) hasTag:(NSString *)tag {
2981 return tags_ == nil ? NO : [tags_ containsObject:tag];
2984 - (NSString *) primaryPurpose {
2985 for (NSString *tag in (NSArray *) tags_)
2986 if ([tag hasPrefix:@"purpose::"])
2987 return [tag substringFromIndex:9];
2991 - (NSArray *) purposes {
2992 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2993 for (NSString *tag in (NSArray *) tags_)
2994 if ([tag hasPrefix:@"purpose::"])
2995 [purposes addObject:[tag substringFromIndex:9]];
2996 return [purposes count] == 0 ? nil : purposes;
2999 - (bool) isCommercial {
3000 return [self hasTag:@"cydia::commercial"];
3003 - (void) setIndex:(size_t)index {
3004 if (metadata_->index_ != index)
3005 metadata_->index_ = index;
3008 - (CYString &) cyname {
3009 return name_.empty() ? id_ : name_;
3012 - (uint32_t) compareBySection:(NSArray *)sections {
3013 NSString *section([self section]);
3014 for (size_t i(0), e([sections count]); i != e; ++i) {
3015 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3019 return _not(uint32_t);
3023 @synchronized (database_) {
3024 pkgProblemResolver *resolver = [database_ resolver];
3025 resolver->Clear(iterator_);
3027 pkgCacheFile &cache([database_ cache]);
3028 cache->SetReInstall(iterator_, false);
3029 cache->MarkKeep(iterator_, false);
3033 @synchronized (database_) {
3034 pkgProblemResolver *resolver = [database_ resolver];
3035 resolver->Clear(iterator_);
3036 resolver->Protect(iterator_);
3038 pkgCacheFile &cache([database_ cache]);
3039 cache->SetReInstall(iterator_, false);
3040 cache->MarkInstall(iterator_, false);
3042 pkgDepCache::StateCache &state((*cache)[iterator_]);
3043 if (!state.Install())
3044 cache->SetReInstall(iterator_, true);
3048 @synchronized (database_) {
3049 pkgProblemResolver *resolver = [database_ resolver];
3050 resolver->Clear(iterator_);
3051 resolver->Remove(iterator_);
3052 resolver->Protect(iterator_);
3054 pkgCacheFile &cache([database_ cache]);
3055 cache->SetReInstall(iterator_, false);
3056 cache->MarkDelete(iterator_, true);
3059 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3060 _profile(Package$isUnfilteredAndSearchedForBy)
3063 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3064 value &= [self unfiltered];
3067 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3068 value &= [self matches:query];
3075 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3076 if ([search length] == 0)
3079 _profile(Package$isUnfilteredAndSelectedForBy)
3082 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3083 value &= [self unfiltered];
3086 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3087 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3094 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3095 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3098 - (bool) isVisibleInSection:(NSString *)name {
3099 NSString *section([self section]);
3103 section == nil && [name length] == 0 ||
3104 [name isEqualToString:section]
3105 ) && [self visible];
3108 - (bool) isVisibleInSource:(Source *)source {
3109 return [self source] == source && [self visible];
3114 /* Section Class {{{ */
3115 @interface Section : NSObject {
3120 _H<NSString> localized_;
3123 - (NSComparisonResult) compareByLocalized:(Section *)section;
3124 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3125 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3126 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3127 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3128 - (NSString *) name;
3135 - (void) addToCount;
3137 - (void) setCount:(size_t)count;
3138 - (NSString *) localized;
3142 @implementation Section
3144 - (NSComparisonResult) compareByLocalized:(Section *)section {
3145 NSString *lhs(localized_);
3146 NSString *rhs([section localized]);
3148 /*if ([lhs length] != 0 && [rhs length] != 0) {
3149 unichar lhc = [lhs characterAtIndex:0];
3150 unichar rhc = [rhs characterAtIndex:0];
3152 if (isalpha(lhc) && !isalpha(rhc))
3153 return NSOrderedAscending;
3154 else if (!isalpha(lhc) && isalpha(rhc))
3155 return NSOrderedDescending;
3158 return [lhs compare:rhs options:LaxCompareOptions_];
3161 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3162 if ((self = [self initWithName:name localize:NO]) != nil) {
3163 if (localized != nil)
3164 localized_ = localized;
3168 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3169 return [self initWithName:name row:0 localize:localize];
3172 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3173 if ((self = [super init]) != nil) {
3178 localized_ = LocalizeSection(name_);
3182 /* XXX: localize the index thingees */
3183 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3184 if ((self = [super init]) != nil) {
3185 name_ = [NSString stringWithCharacters:&index length:1];
3191 - (NSString *) name {
3211 - (void) addToCount {
3215 - (void) setCount:(size_t)count {
3219 - (NSString *) localized {
3226 class CydiaLogCleaner :
3227 public pkgArchiveCleaner
3230 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3235 /* Database Implementation {{{ */
3236 @implementation Database
3238 + (Database *) sharedInstance {
3239 static _H<Database> instance;
3240 if (instance == nil)
3241 instance = [[[Database alloc] init] autorelease];
3249 - (void) releasePackages {
3250 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3251 CFArrayRemoveAllValues(packages_);
3255 // XXX: actually implement this thing
3257 [self releasePackages];
3258 apr_pool_destroy(pool_);
3259 NSRecycleZone(zone_);
3263 - (void) _readCydia:(NSNumber *)fd {
3264 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3265 std::istream is(&ib);
3268 static Pcre finish_r("^finish:([^:]*)$");
3270 while (std::getline(is, line)) {
3271 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3273 const char *data(line.c_str());
3274 size_t size = line.size();
3275 lprintf("C:%s\n", data);
3277 if (finish_r(data, size)) {
3278 NSString *finish = finish_r[1];
3279 int index = [Finishes_ indexOfObject:finish];
3280 if (index != INT_MAX && index > Finish_)
3290 - (void) _readStatus:(NSNumber *)fd {
3291 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3292 std::istream is(&ib);
3295 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3296 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3298 while (std::getline(is, line)) {
3299 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3301 const char *data(line.c_str());
3302 size_t size(line.size());
3303 lprintf("S:%s\n", data);
3305 if (conffile_r(data, size)) {
3306 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3307 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3308 } else if (strncmp(data, "status: ", 8) == 0) {
3309 // status: <package>: {unpacked,half-configured,installed}
3310 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3311 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3312 } else if (strncmp(data, "processing: ", 12) == 0) {
3313 // processing: configure: config-test
3314 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3315 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3316 } else if (pmstatus_r(data, size)) {
3317 std::string type([pmstatus_r[1] UTF8String]);
3319 NSString *package = pmstatus_r[2];
3320 if ([package isEqualToString:@"dpkg-exec"])
3323 float percent([pmstatus_r[3] floatValue]);
3324 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3326 NSString *string = pmstatus_r[4];
3328 if (type == "pmerror") {
3329 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3330 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3331 } else if (type == "pmstatus") {
3332 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3333 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3334 } else if (type == "pmconffile")
3335 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3337 lprintf("E:unknown pmstatus\n");
3339 lprintf("E:unknown status\n");
3347 - (void) _readOutput:(NSNumber *)fd {
3348 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3349 std::istream is(&ib);
3352 while (std::getline(is, line)) {
3353 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3355 lprintf("O:%s\n", line.c_str());
3357 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3358 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3370 - (Package *) packageWithName:(NSString *)name {
3373 @synchronized (self) {
3374 if (static_cast<pkgDepCache *>(cache_) == NULL)
3376 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3377 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3381 if ((self = [super init]) != nil) {
3388 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3389 apr_pool_create(&pool_, NULL);
3391 size_t capacity(MetaFile_->active_);
3397 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3398 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3402 _assert(pipe(fds) != -1);
3405 _config->Set("APT::Keep-Fds::", cydiafd_);
3406 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3409 detachNewThreadSelector:@selector(_readCydia:)
3411 withObject:[NSNumber numberWithInt:fds[0]]
3414 _assert(pipe(fds) != -1);
3418 detachNewThreadSelector:@selector(_readStatus:)
3420 withObject:[NSNumber numberWithInt:fds[0]]
3423 _assert(pipe(fds) != -1);
3424 _assert(dup2(fds[0], 0) != -1);
3425 _assert(close(fds[0]) != -1);
3427 input_ = fdopen(fds[1], "a");
3429 _assert(pipe(fds) != -1);
3430 _assert(dup2(fds[1], 1) != -1);
3431 _assert(close(fds[1]) != -1);
3434 detachNewThreadSelector:@selector(_readOutput:)
3436 withObject:[NSNumber numberWithInt:fds[0]]
3441 - (pkgCacheFile &) cache {
3445 - (pkgDepCache::Policy *) policy {
3449 - (pkgRecords *) records {
3453 - (pkgProblemResolver *) resolver {
3457 - (pkgAcquire &) fetcher {
3461 - (pkgSourceList &) list {
3465 - (NSArray *) packages {
3466 return (NSArray *) packages_;
3469 - (NSArray *) sources {
3473 - (Source *) sourceWithKey:(NSString *)key {
3474 for (Source *source in [self sources]) {
3475 if ([[source key] isEqualToString:key])
3480 - (bool) popErrorWithTitle:(NSString *)title {
3483 while (!_error->empty()) {
3485 bool warning(!_error->PopMessage(error));
3490 size_t size(error.size());
3491 if (size == 0 || error[size - 1] != '\n')
3493 error.resize(size - 1);
3496 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3498 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3499 if (warning && no_pubkey(error.c_str()))
3502 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3508 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3509 return [self popErrorWithTitle:title] || !success;
3512 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3513 @synchronized (self) {
3516 [self releasePackages];
3519 [sourceList_ removeAllObjects];
3539 apr_pool_clear(pool_);
3541 NSRecycleZone(zone_);
3542 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3544 int chk(creat("/tmp/cydia.chk", 0644));
3548 if (invocation != nil)
3549 [invocation invoke];
3551 NSString *title(UCLocalize("DATABASE"));
3553 list_ = new pkgSourceList();
3554 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3557 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3558 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3559 [sourceList_ addObject:object];
3563 OpProgress progress;
3565 if (!cache_.Open(progress, true)) {
3566 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3567 while (!_error->empty()) {
3569 bool warning(!_error->PopMessage(error));
3571 lprintf("cache_.Open():[%s]\n", error.c_str());
3573 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3577 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3578 repair = @selector(configure);
3579 //else if (error == "The package lists or status file could not be parsed or opened.")
3580 // repair = @selector(update);
3581 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3582 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3583 // else if (error == "Malformed Status line")
3584 // else if (error == "The list of sources could not be read.")
3586 if (repair != NULL) {
3588 [delegate_ repairWithSelector:repair];
3597 unlink("/tmp/cydia.chk");
3599 now_ = [[NSDate date] timeIntervalSince1970];
3601 policy_ = new pkgDepCache::Policy();
3602 records_ = new pkgRecords(cache_);
3603 resolver_ = new pkgProblemResolver(cache_);
3604 fetcher_ = new pkgAcquire(&status_);
3607 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3608 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3612 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3615 if (cache_->BrokenCount() != 0) {
3616 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3619 if (cache_->BrokenCount() != 0) {
3620 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3624 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3628 for (Source *object in (id) sourceList_) {
3629 metaIndex *source([object metaIndex]);
3630 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3631 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3632 // XXX: this could be more intelligent
3633 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3634 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3636 sourceMap_[cached->ID] = object;
3641 /*std::vector<Package *> packages;
3642 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3647 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3648 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3649 //packages.push_back(package);
3650 CFArrayAppendValue(packages_, CFRetain(package));
3654 /*if (packages.empty())
3655 packages_ = [[NSArray alloc] init];
3657 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3660 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3661 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3662 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3670 /*if (!packages.empty())
3671 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3672 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3674 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3676 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3678 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3682 size_t count(CFArrayGetCount(packages_));
3683 MetaFile_->active_ = count;
3685 for (size_t index(0); index != count; ++index)
3686 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3693 @synchronized (self) {
3695 resolver_ = new pkgProblemResolver(cache_);
3697 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3698 if (!cache_[iterator].Keep())
3699 cache_->MarkKeep(iterator, false);
3700 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3701 cache_->SetReInstall(iterator, false);
3704 - (void) configure {
3705 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3707 system([dpkg UTF8String]);
3712 @synchronized (self) {
3713 // XXX: I don't remember this condition
3718 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3720 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3722 if ([self popErrorWithTitle:title])
3726 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3728 CydiaLogCleaner cleaner;
3729 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3736 fetcher_->Shutdown();
3738 pkgRecords records(cache_);
3740 lock_ = new FileFd();
3741 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3743 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3745 if ([self popErrorWithTitle:title])
3749 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3752 manager_ = (_system->CreatePM(cache_));
3753 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3760 bool substrate(RestartSubstrate_);
3761 RestartSubstrate_ = false;
3763 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3765 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3767 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3769 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3770 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3773 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3775 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3777 [self popErrorWithTitle:title];
3781 bool failed = false;
3782 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3783 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3785 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3788 std::string uri = (*item)->DescURI();
3789 std::string error = (*item)->ErrorText;
3791 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3794 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3795 [delegate_ addProgressEventOnMainThread:event forTask:title];
3798 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3806 RestartSubstrate_ = true;
3809 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3810 if ([self popErrorWithTitle:title])
3813 if (result == pkgPackageManager::Failed) {
3818 if (result != pkgPackageManager::Completed) {
3823 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3825 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3827 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3828 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3831 if (![before isEqualToArray:after])
3836 NSString *title(UCLocalize("UPGRADE"));
3837 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3843 [self updateWithStatus:status_];
3846 - (void) updateWithStatus:(Status &)status {
3847 NSString *title(UCLocalize("REFRESHING_DATA"));
3850 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3854 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3855 if ([self popErrorWithTitle:title])
3858 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3860 bool success(ListUpdate(status, list, PulseInterval_));
3861 if (status.WasCancelled())
3864 [self popErrorWithTitle:title forOperation:success];
3865 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3869 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3872 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3873 delegate_ = delegate;
3876 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3877 progress_ = delegate;
3878 status_.setDelegate(delegate);
3881 - (NSObject<ProgressDelegate> *) progressDelegate {
3885 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3886 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3887 return i == sourceMap_.end() ? nil : i->second;
3890 - (NSString *) mappedSectionForPointer:(const char *)section {
3891 _H<NSString> *mapped;
3893 _profile(Database$mappedSectionForPointer$Cache)
3894 mapped = §ions_[section];
3897 if (*mapped == NULL) {
3898 size_t length(strlen(section));
3899 char spaced[length + 1];
3901 _profile(Database$mappedSectionForPointer$Replace)
3902 for (size_t index(0); index != length; ++index)
3903 spaced[index] = section[index] == '_' ? ' ' : section[index];
3904 spaced[length] = '\0';
3909 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3910 string = [NSString stringWithUTF8String:spaced];
3913 _profile(Database$mappedSectionForPointer$Map)
3914 string = [SectionMap_ objectForKey:string] ?: string;
3924 static _H<NSMutableSet> Diversions_;
3926 @interface Diversion : NSObject {
3929 _H<NSString> format_;
3934 @implementation Diversion
3936 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3937 if ((self = [super init]) != nil) {
3938 pattern_ = [from UTF8String];
3944 - (NSString *) divert:(NSString *)url {
3945 return !pattern_(url) ? nil : pattern_->*format_;
3948 + (NSURL *) divertURL:(NSURL *)url {
3950 NSString *href([url absoluteString]);
3952 for (Diversion *diversion in (id) Diversions_)
3953 if (NSString *diverted = [diversion divert:href]) {
3955 NSLog(@"div: %@", diverted);
3957 url = [NSURL URLWithString:diverted];
3964 - (NSString *) key {
3968 - (NSUInteger) hash {
3972 - (BOOL) isEqual:(Diversion *)object {
3973 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3978 @interface CydiaObject : NSObject {
3979 _H<CyteWebViewController> indirect_;
3980 _transient id delegate_;
3983 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3989 @interface CydiaWebViewController : CyteWebViewController {
3990 _H<CydiaObject> cydia_;
3993 + (void) addDiversion:(Diversion *)diversion;
3994 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
3995 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
3996 - (void) setDelegate:(id)delegate;
4000 /* Web Scripting {{{ */
4001 @implementation CydiaObject
4003 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4004 if ((self = [super init]) != nil) {
4005 indirect_ = (CyteWebViewController *) indirect;
4009 - (void) setDelegate:(id)delegate {
4010 delegate_ = delegate;
4013 + (NSArray *) _attributeKeys {
4014 return [NSArray arrayWithObjects:
4017 @"coreFoundationVersionNumber",
4034 - (NSArray *) attributeKeys {
4035 return [[self class] _attributeKeys];
4038 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4039 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4042 - (NSString *) version {
4046 - (NSString *) build {
4050 - (NSString *) coreFoundationVersionNumber {
4051 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4054 - (NSString *) device {
4055 return [[UIDevice currentDevice] uniqueIdentifier];
4058 - (NSString *) firmware {
4059 return [[UIDevice currentDevice] systemVersion];
4062 - (NSString *) hostname {
4063 return [[UIDevice currentDevice] name];
4066 - (NSString *) idiom {
4067 return (id) Idiom_ ?: [NSNull null];
4070 - (NSString *) mcc {
4071 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4072 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4076 - (NSString *) mnc {
4077 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4078 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4082 - (NSString *) operator {
4083 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4084 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4088 - (NSString *) bbsnum {
4089 return (id) BBSNum_ ?: [NSNull null];
4092 - (NSString *) ecid {
4093 return (id) ChipID_ ?: [NSNull null];
4096 - (NSString *) serial {
4097 return SerialNumber_;
4100 - (NSString *) role {
4101 return (id) Role_ ?: [NSNull null];
4104 - (NSString *) model {
4105 return [NSString stringWithUTF8String:Machine_];
4108 - (NSString *) token {
4109 return (id) Token_ ?: [NSNull null];
4112 + (NSString *) webScriptNameForSelector:(SEL)selector {
4114 else if (selector == @selector(addBridgedHost:))
4115 return @"addBridgedHost";
4116 else if (selector == @selector(addInsecureHost:))
4117 return @"addInsecureHost";
4118 else if (selector == @selector(addInternalRedirect::))
4119 return @"addInternalRedirect";
4120 else if (selector == @selector(addPipelinedHost:scheme:))
4121 return @"addPipelinedHost";
4122 else if (selector == @selector(addSource:::))
4123 return @"addSource";
4124 else if (selector == @selector(addTokenHost:))
4125 return @"addTokenHost";
4126 else if (selector == @selector(addTrivialSource:))
4127 return @"addTrivialSource";
4128 else if (selector == @selector(close))
4130 else if (selector == @selector(du:))
4132 else if (selector == @selector(stringWithFormat:arguments:))
4134 else if (selector == @selector(getAllSources))
4135 return @"getAllSourcs";
4136 else if (selector == @selector(getKernelNumber:))
4137 return @"getKernelNumber";
4138 else if (selector == @selector(getKernelString:))
4139 return @"getKernelString";
4140 else if (selector == @selector(getInstalledPackages))
4141 return @"getInstalledPackages";
4142 else if (selector == @selector(getIORegistryEntry::))
4143 return @"getIORegistryEntry";
4144 else if (selector == @selector(getLocaleIdentifier))
4145 return @"getLocaleIdentifier";
4146 else if (selector == @selector(getPreferredLanguages))
4147 return @"getPreferredLanguages";
4148 else if (selector == @selector(getPackageById:))
4149 return @"getPackageById";
4150 else if (selector == @selector(getMetadataKeys))
4151 return @"getMetadataKeys";
4152 else if (selector == @selector(getMetadataValue:))
4153 return @"getMetadataValue";
4154 else if (selector == @selector(getSessionValue:))
4155 return @"getSessionValue";
4156 else if (selector == @selector(installPackages:))
4157 return @"installPackages";
4158 else if (selector == @selector(isReachable:))
4159 return @"isReachable";
4160 else if (selector == @selector(localizedStringForKey:value:table:))
4162 else if (selector == @selector(popViewController:))
4163 return @"popViewController";
4164 else if (selector == @selector(refreshSources))
4165 return @"refreshSources";
4166 else if (selector == @selector(removeButton))
4167 return @"removeButton";
4168 else if (selector == @selector(saveConfig))
4169 return @"saveConfig";
4170 else if (selector == @selector(setMetadataValue::))
4171 return @"setMetadataValue";
4172 else if (selector == @selector(setSessionValue::))
4173 return @"setSessionValue";
4174 else if (selector == @selector(setShowPromoted:))
4175 return @"setShowPromoted";
4176 else if (selector == @selector(substitutePackageNames:))
4177 return @"substitutePackageNames";
4178 else if (selector == @selector(scrollToBottom:))
4179 return @"scrollToBottom";
4180 else if (selector == @selector(setAllowsNavigationAction:))
4181 return @"setAllowsNavigationAction";
4182 else if (selector == @selector(setBadgeValue:))
4183 return @"setBadgeValue";
4184 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4185 return @"setButtonImage";
4186 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4187 return @"setButtonTitle";
4188 else if (selector == @selector(setHidesBackButton:))
4189 return @"setHidesBackButton";
4190 else if (selector == @selector(setHidesNavigationBar:))
4191 return @"setHidesNavigationBar";
4192 else if (selector == @selector(setNavigationBarStyle:))
4193 return @"setNavigationBarStyle";
4194 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4195 return @"setNavigationBarTintColor";
4196 else if (selector == @selector(setPasteboardString:))
4197 return @"setPasteboardString";
4198 else if (selector == @selector(setPasteboardURL:))
4199 return @"setPasteboardURL";
4200 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4201 return @"setScrollAlwaysBounceVertical";
4202 else if (selector == @selector(setScrollIndicatorStyle:))
4203 return @"setScrollIndicatorStyle";
4204 else if (selector == @selector(setToken:))
4206 else if (selector == @selector(setViewportWidth:))
4207 return @"setViewportWidth";
4208 else if (selector == @selector(statfs:))
4210 else if (selector == @selector(supports:))
4212 else if (selector == @selector(unload))
4218 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4219 return [self webScriptNameForSelector:selector] == nil;
4222 - (BOOL) supports:(NSString *)feature {
4223 return [feature isEqualToString:@"window.open"];
4227 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4230 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4231 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4234 - (void) setScrollIndicatorStyle:(NSString *)style {
4235 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4238 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4239 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4242 - (NSNumber *) getKernelNumber:(NSString *)name {
4243 const char *string([name UTF8String]);
4246 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4247 return (id) [NSNull null];
4249 if (size != sizeof(int))
4250 return (id) [NSNull null];
4253 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4254 return (id) [NSNull null];
4256 return [NSNumber numberWithInt:value];
4259 - (NSString *) getKernelString:(NSString *)name {
4260 const char *string([name UTF8String]);
4263 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4264 return (id) [NSNull null];
4266 char value[size + 1];
4267 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4268 return (id) [NSNull null];
4270 // XXX: just in case you request something ludicrous
4273 return [NSString stringWithCString:value];
4276 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4277 NSObject *value(CYIOGetValue([path UTF8String], entry));
4280 if ([value isKindOfClass:[NSData class]])
4281 value = CYHex((NSData *) value);
4286 - (NSArray *) getMetadataKeys {
4287 @synchronized (Values_) {
4288 return [Values_ allKeys];
4291 - (void) _setShowPromoted:(NSNumber *)value {
4292 [Metadata_ setObject:value forKey:@"ShowPromoted"];
4296 - (void) setShowPromoted:(NSNumber *)value {
4297 [self performSelectorOnMainThread:@selector(_setShowPromoted:) withObject:value waitUntilDone:NO];
4300 - (id) getMetadataValue:(NSString *)key {
4301 @synchronized (Values_) {
4302 return [Values_ objectForKey:key];
4305 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4306 @synchronized (Values_) {
4307 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4308 [Values_ removeObjectForKey:key];
4310 [Values_ setObject:value forKey:key];
4312 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4315 - (id) getSessionValue:(NSString *)key {
4316 @synchronized (SessionData_) {
4317 return [SessionData_ objectForKey:key];
4320 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4321 @synchronized (SessionData_) {
4322 if (value == (id) [WebUndefined undefined])
4323 [SessionData_ removeObjectForKey:key];
4325 [SessionData_ setObject:value forKey:key];
4328 - (void) addBridgedHost:(NSString *)host {
4329 @synchronized (HostConfig_) {
4330 [BridgedHosts_ addObject:host];
4333 - (void) addInsecureHost:(NSString *)host {
4334 @synchronized (HostConfig_) {
4335 [InsecureHosts_ addObject:host];
4338 - (void) addTokenHost:(NSString *)host {
4339 @synchronized (HostConfig_) {
4340 [TokenHosts_ addObject:host];
4343 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4344 @synchronized (HostConfig_) {
4345 if (scheme != (id) [WebUndefined undefined])
4346 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4348 [PipelinedHosts_ addObject:host];
4351 - (void) popViewController:(NSNumber *)value {
4352 if (value == (id) [WebUndefined undefined])
4353 value = [NSNumber numberWithBool:YES];
4354 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4357 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4358 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4360 for (NSString *section in sections)
4361 [array addObject:section];
4363 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4366 distribution, @"Distribution",
4368 nil] waitUntilDone:NO];
4371 - (void) addTrivialSource:(NSString *)href {
4372 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4375 - (void) refreshSources {
4376 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4379 - (void) saveConfig {
4380 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4383 - (NSArray *) getAllSources {
4384 return [[Database sharedInstance] sources];
4387 - (NSArray *) getInstalledPackages {
4388 Database *database([Database sharedInstance]);
4389 @synchronized (database) {
4390 NSArray *packages([database packages]);
4391 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4392 for (Package *package in packages)
4393 if (![package uninstalled])
4394 [installed addObject:package];
4398 - (Package *) getPackageById:(NSString *)id {
4399 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4403 return (Package *) [NSNull null];
4406 - (NSString *) getLocaleIdentifier {
4407 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4410 - (NSArray *) getPreferredLanguages {
4414 - (NSArray *) statfs:(NSString *)path {
4417 if (path == nil || statfs([path UTF8String], &stat) == -1)
4420 return [NSArray arrayWithObjects:
4421 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4422 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4423 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4427 - (NSNumber *) du:(NSString *)path {
4428 NSNumber *value(nil);
4431 _assert(pipe(fds) != -1);
4433 pid_t pid(ExecFork());
4435 _assert(dup2(fds[1], 1) != -1);
4436 _assert(close(fds[0]) != -1);
4437 _assert(close(fds[1]) != -1);
4438 /* XXX: this should probably not use du */
4439 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4444 _assert(close(fds[1]) != -1);
4446 if (FILE *du = fdopen(fds[0], "r")) {
4448 while (fgets(line, sizeof(line), du) != NULL) {
4449 size_t length(strlen(line));
4450 while (length != 0 && line[length - 1] == '\n')
4451 line[--length] = '\0';
4452 if (char *tab = strchr(line, '\t')) {
4454 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4459 } else _assert(close(fds[0]));
4467 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4470 - (NSNumber *) isReachable:(NSString *)name {
4471 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4474 - (void) installPackages:(NSArray *)packages {
4475 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4478 - (NSString *) substitutePackageNames:(NSString *)message {
4479 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4480 for (size_t i(0), e([words count]); i != e; ++i) {
4481 NSString *word([words objectAtIndex:i]);
4482 if (Package *package = [[Database sharedInstance] packageWithName:word])
4483 [words replaceObjectAtIndex:i withObject:[package name]];
4486 return [words componentsJoinedByString:@" "];
4489 - (void) removeButton {
4490 [indirect_ removeButton];
4493 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4494 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4497 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4498 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4501 - (void) setBadgeValue:(id)value {
4502 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4505 - (void) setAllowsNavigationAction:(NSString *)value {
4506 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4509 - (void) setHidesBackButton:(NSString *)value {
4510 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4513 - (void) setHidesNavigationBar:(NSString *)value {
4514 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4517 - (void) setNavigationBarStyle:(NSString *)value {
4518 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4521 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4522 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4523 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4524 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4527 - (void) setPasteboardString:(NSString *)value {
4528 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4531 - (void) setPasteboardURL:(NSString *)value {
4532 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4535 - (void) _setToken:(NSString *)token {
4539 [Metadata_ removeObjectForKey:@"Token"];
4541 [Metadata_ setObject:Token_ forKey:@"Token"];
4546 - (void) setToken:(NSString *)token {
4547 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4550 - (void) scrollToBottom:(NSNumber *)animated {
4551 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4554 - (void) setViewportWidth:(float)width {
4555 [indirect_ setViewportWidthOnMainThread:width];
4558 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4559 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4560 unsigned count([arguments count]);
4562 for (unsigned i(0); i != count; ++i)
4563 values[i] = [arguments objectAtIndex:i];
4564 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4567 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4568 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4570 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4572 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4578 @interface NSURL (CydiaSecure)
4581 @implementation NSURL (CydiaSecure)
4583 - (bool) isCydiaSecure {
4584 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4587 @synchronized (HostConfig_) {
4588 if ([InsecureHosts_ containsObject:[self host]])
4597 /* Cydia Browser Controller {{{ */
4598 @implementation CydiaWebViewController
4600 - (NSURL *) navigationURL {
4601 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4604 + (void) _initialize {
4605 [super _initialize];
4607 Diversions_ = [NSMutableSet setWithCapacity:0];
4610 + (void) addDiversion:(Diversion *)diversion {
4611 [Diversions_ addObject:diversion];
4614 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4615 [super webView:view didClearWindowObject:window forFrame:frame];
4616 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4619 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4620 WebDataSource *source([frame dataSource]);
4621 NSURLResponse *response([source response]);
4622 NSURL *url([response URL]);
4623 NSString *scheme([[url scheme] lowercaseString]);
4625 bool bridged(false);
4627 @synchronized (HostConfig_) {
4628 if ([scheme isEqualToString:@"file"])
4630 else if ([scheme isEqualToString:@"https"])
4631 if ([BridgedHosts_ containsObject:[url host]])
4636 [window setValue:cydia forKey:@"cydia"];
4639 - (void) _setupMail:(MFMailComposeViewController *)controller {
4640 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4642 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4643 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4646 - (NSURL *) URLWithURL:(NSURL *)url {
4647 return [Diversion divertURL:url];
4650 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4651 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4654 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4655 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4657 NSURL *url([copy URL]);
4658 NSString *href([url absoluteString]);
4659 NSString *host([url host]);
4661 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4662 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4663 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4664 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4667 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4668 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4670 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4674 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4675 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4676 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4677 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4682 @synchronized (HostConfig_) {
4683 bridged = [BridgedHosts_ containsObject:host];
4684 token = [TokenHosts_ containsObject:host];
4687 if ([url isCydiaSecure]) {
4689 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4690 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4692 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4693 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4700 - (void) setDelegate:(id)delegate {
4701 [super setDelegate:delegate];
4702 [cydia_ setDelegate:delegate];
4705 - (NSString *) applicationNameForUserAgent {
4710 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4711 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4717 @interface AppCacheController : CydiaWebViewController {
4722 @implementation AppCacheController
4724 - (void) didReceiveMemoryWarning {
4725 // XXX: this doesn't work
4728 - (bool) retainsNetworkActivityIndicator {
4736 @interface NSObject (CydiaScript)
4737 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4740 @implementation NSObject (CydiaScript)
4742 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4748 @implementation NSArray (CydiaScript)
4750 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4751 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4752 for (size_t i(0), e([self count]); i != e; ++i)
4753 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4759 @implementation NSDictionary (CydiaScript)
4761 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4762 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4764 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4771 /* Confirmation Controller {{{ */
4772 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4773 if (!iterator.end())
4774 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4775 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4777 pkgCache::PkgIterator package(dep.TargetPkg());
4780 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4787 @protocol ConfirmationControllerDelegate
4788 - (void) cancelAndClear:(bool)clear;
4789 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4793 @interface ConfirmationController : CydiaWebViewController {
4794 _transient Database *database_;
4796 _H<UIAlertView> essential_;
4798 _H<NSDictionary> changes_;
4799 _H<NSMutableArray> issues_;
4800 _H<NSDictionary> sizes_;
4805 - (id) initWithDatabase:(Database *)database;
4809 @implementation ConfirmationController
4813 RestartSubstrate_ = true;
4814 [delegate_ confirmWithNavigationController:[self navigationController]];
4817 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4818 NSString *context([alert context]);
4820 if ([context isEqualToString:@"remove"]) {
4821 if (button == [alert cancelButtonIndex])
4822 [self dismissModalViewControllerAnimated:YES];
4823 else if (button == [alert firstOtherButtonIndex]) {
4824 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
4827 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4828 } else if ([context isEqualToString:@"unable"]) {
4829 [self dismissModalViewControllerAnimated:YES];
4830 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4832 [super alertView:alert clickedButtonAtIndex:button];
4836 - (void) _doContinue {
4837 [delegate_ cancelAndClear:NO];
4838 [self dismissModalViewControllerAnimated:YES];
4841 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4842 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4846 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4847 [super webView:view didClearWindowObject:window forFrame:frame];
4849 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4850 (id) changes_, @"changes",
4851 (id) issues_, @"issues",
4852 (id) sizes_, @"sizes",
4854 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4857 - (id) initWithDatabase:(Database *)database {
4858 if ((self = [super init]) != nil) {
4859 database_ = database;
4861 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4862 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4863 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4864 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4865 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4869 pkgCacheFile &cache([database_ cache]);
4870 NSArray *packages([database_ packages]);
4871 pkgDepCache::Policy *policy([database_ policy]);
4873 issues_ = [NSMutableArray arrayWithCapacity:4];
4875 for (Package *package in packages) {
4876 pkgCache::PkgIterator iterator([package iterator]);
4877 NSString *name([package id]);
4879 if ([package broken]) {
4880 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4882 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4884 reasons, @"reasons",
4887 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4891 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4892 pkgCache::DepIterator start;
4893 pkgCache::DepIterator end;
4894 dep.GlobOr(start, end); // ++dep
4896 if (!cache->IsImportantDep(end))
4898 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4901 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4903 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4904 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4905 clauses, @"clauses",
4909 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4911 pkgCache::PkgIterator target(start.TargetPkg());
4912 if (target->ProvidesList != 0)
4913 reason = @"missing";
4915 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4917 reason = @"installed";
4918 installed = [NSString stringWithUTF8String:ver.VerStr()];
4919 } else if (!cache[target].CandidateVerIter(cache).end())
4920 reason = @"uninstalled";
4921 else if (target->ProvidesList == 0)
4922 reason = @"uninstallable";
4924 reason = @"virtual";
4927 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4928 [NSString stringWithUTF8String:start.CompType()], @"operator",
4929 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4932 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4933 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4934 version, @"version",
4936 installed, @"installed",
4939 // yes, seriously. (wtf?)
4947 pkgDepCache::StateCache &state(cache[iterator]);
4949 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4951 if (state.NewInstall())
4952 [installs addObject:name];
4953 // XXX: else if (state.Install())
4954 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4955 [reinstalls addObject:name];
4956 // XXX: move before previous if
4957 else if (state.Upgrade())
4958 [upgrades addObject:name];
4959 else if (state.Downgrade())
4960 [downgrades addObject:name];
4961 else if (!state.Delete())
4962 // XXX: _assert(state.Keep());
4964 else if (special_r(name))
4965 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4966 [NSNull null], @"package",
4967 [NSArray arrayWithObjects:
4968 [NSDictionary dictionaryWithObjectsAndKeys:
4969 @"Conflicts", @"relationship",
4970 [NSArray arrayWithObjects:
4971 [NSDictionary dictionaryWithObjectsAndKeys:
4973 [NSNull null], @"version",
4974 @"installed", @"reason",
4981 if ([package essential])
4983 [removes addObject:name];
4986 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4987 substrate_ |= DepSubstrate(iterator.CurrentVer());
4992 else if (Advanced_) {
4993 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4995 essential_ = [[[UIAlertView alloc]
4996 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4997 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4999 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5001 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5005 [essential_ setContext:@"remove"];
5006 [essential_ setNumberOfRows:2];
5008 essential_ = [[[UIAlertView alloc]
5009 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5010 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5012 cancelButtonTitle:UCLocalize("OKAY")
5013 otherButtonTitles:nil
5016 [essential_ setContext:@"unable"];
5019 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5020 installs, @"installs",
5021 reinstalls, @"reinstalls",
5022 upgrades, @"upgrades",
5023 downgrades, @"downgrades",
5024 removes, @"removes",
5027 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5028 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5029 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5032 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5036 - (UIBarButtonItem *) leftButton {
5037 return [[[UIBarButtonItem alloc]
5038 initWithTitle:UCLocalize("CANCEL")
5039 style:UIBarButtonItemStylePlain
5041 action:@selector(cancelButtonClicked)
5046 - (void) applyRightButton {
5047 if ([issues_ count] == 0 && ![self isLoading])
5048 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5049 initWithTitle:UCLocalize("CONFIRM")
5050 style:UIBarButtonItemStyleDone
5052 action:@selector(confirmButtonClicked)
5055 [[self navigationItem] setRightBarButtonItem:nil];
5059 - (void) cancelButtonClicked {
5060 [delegate_ cancelAndClear:YES];
5061 [self dismissModalViewControllerAnimated:YES];
5065 - (void) confirmButtonClicked {
5066 if (essential_ != nil)
5076 /* Progress Data {{{ */
5077 @interface CydiaProgressData : NSObject {
5078 _transient id delegate_;
5087 _H<NSMutableArray> events_;
5088 _H<NSString> title_;
5090 _H<NSString> status_;
5091 _H<NSString> finish_;
5096 @implementation CydiaProgressData
5098 + (NSArray *) _attributeKeys {
5099 return [NSArray arrayWithObjects:
5111 - (NSArray *) attributeKeys {
5112 return [[self class] _attributeKeys];
5115 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5116 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5120 if ((self = [super init]) != nil) {
5121 events_ = [NSMutableArray arrayWithCapacity:32];
5125 - (void) setDelegate:(id)delegate {
5126 delegate_ = delegate;
5129 - (void) setPercent:(float)value {
5133 - (NSNumber *) percent {
5134 return [NSNumber numberWithFloat:percent_];
5137 - (void) setCurrent:(float)value {
5141 - (NSNumber *) current {
5142 return [NSNumber numberWithFloat:current_];
5145 - (void) setTotal:(float)value {
5149 - (NSNumber *) total {
5150 return [NSNumber numberWithFloat:total_];
5153 - (void) setSpeed:(float)value {
5157 - (NSNumber *) speed {
5158 return [NSNumber numberWithFloat:speed_];
5161 - (NSArray *) events {
5165 - (void) removeAllEvents {
5166 [events_ removeAllObjects];
5169 - (void) addEvent:(CydiaProgressEvent *)event {
5170 [events_ addObject:event];
5173 - (void) setTitle:(NSString *)text {
5177 - (NSString *) title {
5181 - (void) setFinish:(NSString *)text {
5185 - (NSString *) finish {
5186 return (id) finish_ ?: [NSNull null];
5189 - (void) setRunning:(bool)running {
5193 - (NSNumber *) running {
5194 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5199 /* Progress Controller {{{ */
5200 @interface ProgressController : CydiaWebViewController <
5203 _transient Database *database_;
5204 _H<CydiaProgressData, 1> progress_;
5208 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5210 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5212 - (void) setTitle:(NSString *)title;
5213 - (void) setCancellable:(bool)cancellable;
5217 @implementation ProgressController
5220 [database_ setProgressDelegate:nil];
5224 - (UIBarButtonItem *) leftButton {
5225 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5226 initWithTitle:UCLocalize("CANCEL")
5227 style:UIBarButtonItemStylePlain
5229 action:@selector(cancel)
5230 ] autorelease] : nil;
5233 - (void) updateCancel {
5234 [super applyLeftButton];
5237 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5238 if ((self = [super init]) != nil) {
5239 database_ = database;
5240 delegate_ = delegate;
5242 [database_ setProgressDelegate:self];
5244 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5245 [progress_ setDelegate:self];
5247 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5249 [scroller_ setBackgroundColor:[UIColor blackColor]];
5251 [[self navigationItem] setHidesBackButton:YES];
5253 [self updateCancel];
5257 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5258 [super webView:view didClearWindowObject:window forFrame:frame];
5259 [window setValue:progress_ forKey:@"cydiaProgress"];
5262 - (void) updateProgress {
5263 [self dispatchEvent:@"CydiaProgressUpdate"];
5266 - (void) viewWillAppear:(BOOL)animated {
5267 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5268 [super viewWillAppear:animated];
5271 - (void) reloadSpringBoard {
5272 pid_t pid(ExecFork());
5274 pid_t pid(ExecFork());
5276 execl("/usr/bin/sbreload", "sbreload", NULL);
5287 system("/usr/bin/killall SpringBoard");
5291 UpdateExternalStatus(0);
5294 [delegate_ saveState];
5298 [delegate_ returnToCydia];
5302 [delegate_ terminateWithSuccess];
5303 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5304 [delegate_ suspendWithAnimation:YES];
5306 [delegate_ suspend];*/
5318 UIProgressHUD *hud([delegate_ addProgressHUD]);
5319 [hud setText:UCLocalize("LOADING")];
5320 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5326 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5327 SBReboot(SBSSpringBoardServerPort());
5329 reboot2(RB_AUTOBOOT);
5336 - (void) setTitle:(NSString *)title {
5337 [progress_ setTitle:title];
5338 [self updateProgress];
5341 - (UIBarButtonItem *) rightButton {
5342 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5343 initWithTitle:UCLocalize("CLOSE")
5344 style:UIBarButtonItemStylePlain
5346 action:@selector(close)
5350 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5351 UpdateExternalStatus(1);
5353 [progress_ setRunning:true];
5354 [self setTitle:title];
5355 // implicit updateProgress
5357 SHA1SumValue notifyconf; {
5359 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5362 MMap mmap(file, MMap::ReadOnly);
5364 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5365 notifyconf = sha1.Result();
5369 SHA1SumValue springlist; {
5371 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5374 MMap mmap(file, MMap::ReadOnly);
5376 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5377 springlist = sha1.Result();
5381 if (invocation != nil) {
5382 [invocation yieldToSelector:@selector(invoke)];
5383 [self setTitle:@"COMPLETE"];
5388 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5391 MMap mmap(file, MMap::ReadOnly);
5393 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5394 if (!(notifyconf == sha1.Result()))
5401 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5404 MMap mmap(file, MMap::ReadOnly);
5406 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5407 if (!(springlist == sha1.Result()))
5413 if (RestartSubstrate_)
5417 RestartSubstrate_ = false;
5420 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5421 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5422 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5423 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5424 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5427 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5429 [progress_ setRunning:false];
5430 [self updateProgress];
5432 [self applyRightButton];
5435 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5436 [progress_ addEvent:event];
5437 [self updateProgress];
5440 - (bool) isProgressCancelled {
5441 return cancel_ == 2;
5446 [self updateCancel];
5449 - (void) setCancellable:(bool)cancellable {
5450 unsigned cancel(cancel_);
5454 else if (cancel_ == 0)
5457 if (cancel != cancel_)
5458 [self updateCancel];
5461 - (void) setProgressCancellable:(NSNumber *)cancellable {
5462 [self setCancellable:[cancellable boolValue]];
5465 - (void) setProgressPercent:(NSNumber *)percent {
5466 [progress_ setPercent:[percent floatValue]];
5467 [self updateProgress];
5470 - (void) setProgressStatus:(NSDictionary *)status {
5471 if (status == nil) {
5472 [progress_ setCurrent:0];
5473 [progress_ setTotal:0];
5474 [progress_ setSpeed:0];
5476 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5478 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5479 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5480 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5483 [self updateProgress];
5489 /* Package Cell {{{ */
5490 @interface PackageCell : CyteTableViewCell <
5491 CyteTableViewCellDelegate
5495 _H<NSString> description_;
5497 _H<NSString> source_;
5499 _H<UIImage> placard_;
5503 - (PackageCell *) init;
5504 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5506 - (void) drawContentRect:(CGRect)rect;
5510 @implementation PackageCell
5512 - (PackageCell *) init {
5513 CGRect frame(CGRectMake(0, 0, 320, 74));
5514 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5515 UIView *content([self contentView]);
5516 CGRect bounds([content bounds]);
5518 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5519 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5520 [content addSubview:content_];
5522 [content_ setDelegate:self];
5523 [content_ setOpaque:YES];
5527 - (NSString *) accessibilityLabel {
5528 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5531 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5532 summarized_ = summary;
5542 [content_ setBackgroundColor:[UIColor whiteColor]];
5546 Source *source = [package source];
5548 icon_ = [package icon];
5550 if (NSString *name = [package name])
5551 name_ = [NSString stringWithString:name];
5553 NSString *description(nil);
5555 if (description == nil && IsWildcat_)
5556 description = [package longDescription];
5557 if (description == nil)
5558 description = [package shortDescription];
5560 if (description != nil)
5561 description_ = [NSString stringWithString:description];
5563 commercial_ = [package isCommercial];
5565 NSString *label = nil;
5566 bool trusted = false;
5568 if (source != nil) {
5569 label = [source label];
5570 trusted = [source trusted];
5571 } else if ([[package id] isEqualToString:@"firmware"])
5572 label = UCLocalize("APPLE");
5574 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5576 NSString *from(label);
5578 NSString *section = [package simpleSection];
5579 if (section != nil && ![section isEqualToString:label]) {
5580 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5581 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5584 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5586 if (NSString *purpose = [package primaryPurpose])
5587 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5592 if (NSString *mode = [package mode]) {
5593 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5594 color = RemovingColor_;
5595 //placard = @"removing";
5597 color = InstallingColor_;
5598 //placard = @"installing";
5601 // XXX: the removing/installing placards are not @2x
5604 color = [UIColor whiteColor];
5606 if ([package installed] != nil)
5607 placard = @"installed";
5612 [content_ setBackgroundColor:color];
5615 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5618 [self setNeedsDisplay];
5619 [content_ setNeedsDisplay];
5622 - (void) drawSummaryContentRect:(CGRect)rect {
5623 bool highlighted(highlighted_);
5624 float width([self bounds].size.width);
5628 rect.size = [(UIImage *) icon_ size];
5630 while (rect.size.width > 16 || rect.size.height > 16) {
5631 rect.size.width /= 2;
5632 rect.size.height /= 2;
5635 rect.origin.x = 18 - rect.size.width / 2;
5636 rect.origin.y = 18 - rect.size.height / 2;
5638 [icon_ drawInRect:rect];
5641 if (badge_ != nil) {
5643 rect.size = [(UIImage *) badge_ size];
5645 rect.size.width /= 4;
5646 rect.size.height /= 4;
5648 rect.origin.x = 23 - rect.size.width / 2;
5649 rect.origin.y = 23 - rect.size.height / 2;
5651 [badge_ drawInRect:rect];
5658 UISetColor(commercial_ ? Purple_ : Black_);
5659 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5661 if (placard_ != nil)
5662 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5665 - (void) drawNormalContentRect:(CGRect)rect {
5666 bool highlighted(highlighted_);
5667 float width([self bounds].size.width);
5671 rect.size = [(UIImage *) icon_ size];
5673 while (rect.size.width > 32 || rect.size.height > 32) {
5674 rect.size.width /= 2;
5675 rect.size.height /= 2;
5678 rect.origin.x = 25 - rect.size.width / 2;
5679 rect.origin.y = 25 - rect.size.height / 2;
5681 [icon_ drawInRect:rect];
5684 if (badge_ != nil) {
5686 rect.size = [(UIImage *) badge_ size];
5688 rect.size.width /= 2;
5689 rect.size.height /= 2;
5691 rect.origin.x = 36 - rect.size.width / 2;
5692 rect.origin.y = 36 - rect.size.height / 2;
5694 [badge_ drawInRect:rect];
5701 UISetColor(commercial_ ? Purple_ : Black_);
5702 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5703 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5706 UISetColor(commercial_ ? Purplish_ : Gray_);
5707 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5709 if (placard_ != nil)
5710 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5713 - (void) drawContentRect:(CGRect)rect {
5715 [self drawSummaryContentRect:rect];
5717 [self drawNormalContentRect:rect];
5722 /* Section Cell {{{ */
5723 @interface SectionCell : CyteTableViewCell <
5724 CyteTableViewCellDelegate
5726 _H<NSString> basic_;
5727 _H<NSString> section_;
5729 _H<NSString> count_;
5731 _H<UISwitch> switch_;
5735 - (void) setSection:(Section *)section editing:(BOOL)editing;
5739 @implementation SectionCell
5741 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5742 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5743 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5744 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5745 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5747 UIView *content([self contentView]);
5748 CGRect bounds([content bounds]);
5750 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5751 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5752 [content addSubview:content_];
5753 [content_ setBackgroundColor:[UIColor whiteColor]];
5755 [content_ setDelegate:self];
5759 - (void) onSwitch:(id)sender {
5760 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5761 if (metadata == nil) {
5762 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5763 [Sections_ setObject:metadata forKey:basic_];
5766 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5770 - (void) setSection:(Section *)section editing:(BOOL)editing {
5771 if (editing != editing_) {
5773 [switch_ removeFromSuperview];
5775 [self addSubview:switch_];
5784 if (section == nil) {
5785 name_ = UCLocalize("ALL_PACKAGES");
5788 basic_ = [section name];
5789 section_ = [section localized];
5791 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5792 count_ = [NSString stringWithFormat:@"%d", [section count]];
5795 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5798 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5799 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5801 [content_ setNeedsDisplay];
5804 - (void) setFrame:(CGRect)frame {
5805 [super setFrame:frame];
5807 CGRect rect([switch_ frame]);
5808 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5811 - (NSString *) accessibilityLabel {
5815 - (void) drawContentRect:(CGRect)rect {
5816 bool highlighted(highlighted_ && !editing_);
5818 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5823 float width(rect.size.width);
5829 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5831 CGSize size = [count_ sizeWithFont:Font14_];
5835 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5841 /* File Table {{{ */
5842 @interface FileTable : CyteViewController <
5843 UITableViewDataSource,
5846 _transient Database *database_;
5847 _H<Package> package_;
5849 _H<NSMutableArray> files_;
5850 _H<UITableView, 2> list_;
5853 - (id) initWithDatabase:(Database *)database;
5854 - (void) setPackage:(Package *)package;
5858 @implementation FileTable
5860 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5861 return files_ == nil ? 0 : [files_ count];
5864 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5868 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5869 static NSString *reuseIdentifier = @"Cell";
5871 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5873 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5874 [cell setFont:[UIFont systemFontOfSize:16]];
5876 [cell setText:[files_ objectAtIndex:indexPath.row]];
5877 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5882 - (NSURL *) navigationURL {
5883 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5887 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5888 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5889 [list_ setRowHeight:24.0f];
5890 [(UITableView *) list_ setDataSource:self];
5891 [list_ setDelegate:self];
5892 [self setView:list_];
5895 - (void) viewDidLoad {
5896 [super viewDidLoad];
5898 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5901 - (void) releaseSubviews {
5907 [super releaseSubviews];
5910 - (id) initWithDatabase:(Database *)database {
5911 if ((self = [super init]) != nil) {
5912 database_ = database;
5916 - (void) setPackage:(Package *)package {
5920 files_ = [NSMutableArray arrayWithCapacity:32];
5922 if (package != nil) {
5924 name_ = [package id];
5926 if (NSArray *files = [package files])
5927 [files_ addObjectsFromArray:files];
5929 if ([files_ count] != 0) {
5930 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5931 [files_ removeObjectAtIndex:0];
5932 [files_ sortUsingSelector:@selector(compareByPath:)];
5934 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5935 [stack addObject:@"/"];
5937 for (int i(0), e([files_ count]); i != e; ++i) {
5938 NSString *file = [files_ objectAtIndex:i];
5939 while (![file hasPrefix:[stack lastObject]])
5940 [stack removeLastObject];
5941 NSString *directory = [stack lastObject];
5942 [stack addObject:[file stringByAppendingString:@"/"]];
5943 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5944 ([stack count] - 2) * 3, "",
5945 [file substringFromIndex:[directory length]]
5954 - (void) reloadData {
5957 [self setPackage:[database_ packageWithName:name_]];
5962 /* Package Controller {{{ */
5963 @interface CYPackageController : CydiaWebViewController <
5964 UIActionSheetDelegate
5966 _transient Database *database_;
5967 _H<Package> package_;
5970 _H<NSMutableArray> buttons_;
5971 _H<UIBarButtonItem> button_;
5974 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
5978 @implementation CYPackageController
5980 - (NSURL *) navigationURL {
5981 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5984 /* XXX: this is not safe at all... localization of /fail/ */
5985 - (void) _clickButtonWithName:(NSString *)name {
5986 if ([name isEqualToString:UCLocalize("CLEAR")])
5987 [delegate_ clearPackage:package_];
5988 else if ([name isEqualToString:UCLocalize("INSTALL")])
5989 [delegate_ installPackage:package_];
5990 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5991 [delegate_ installPackage:package_];
5992 else if ([name isEqualToString:UCLocalize("REMOVE")])
5993 [delegate_ removePackage:package_];
5994 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5995 [delegate_ installPackage:package_];
5996 else _assert(false);
5999 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6000 NSString *context([sheet context]);
6002 if ([context isEqualToString:@"modify"]) {
6003 if (button != [sheet cancelButtonIndex]) {
6004 NSString *buttonName = [buttons_ objectAtIndex:button];
6005 [self _clickButtonWithName:buttonName];
6008 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6012 - (bool) _allowJavaScriptPanel {
6017 - (void) _customButtonClicked {
6018 int count([buttons_ count]);
6023 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6025 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6026 [buttons addObjectsFromArray:buttons_];
6028 UIActionSheet *sheet = [[[UIActionSheet alloc]
6031 cancelButtonTitle:nil
6032 destructiveButtonTitle:nil
6033 otherButtonTitles:nil
6036 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6038 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6039 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6041 [sheet setContext:@"modify"];
6043 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6047 // We don't want to allow non-commercial packages to do custom things to the install button,
6048 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6049 - (void) customButtonClicked {
6051 [super customButtonClicked];
6053 [self _customButtonClicked];
6056 - (void) reloadButtonClicked {
6057 // Don't reload a commerical package by tapping the loading button,
6058 // but if it's not an Install button, we should forward it on.
6059 if (![package_ uninstalled])
6060 [self _customButtonClicked];
6063 - (void) applyLoadingTitle {
6064 // Don't show "Loading" as the title. Ever.
6067 - (UIBarButtonItem *) rightButton {
6072 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6073 if ((self = [super init]) != nil) {
6074 database_ = database;
6075 buttons_ = [NSMutableArray arrayWithCapacity:4];
6076 name_ = name == nil ? @"" : [NSString stringWithString:name];
6077 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6081 - (void) reloadData {
6084 package_ = [database_ packageWithName:name_];
6086 [buttons_ removeAllObjects];
6088 if (package_ != nil) {
6089 [(Package *) package_ parse];
6091 commercial_ = [package_ isCommercial];
6093 if ([package_ mode] != nil)
6094 [buttons_ addObject:UCLocalize("CLEAR")];
6095 if ([package_ source] == nil);
6096 else if ([package_ upgradableAndEssential:NO])
6097 [buttons_ addObject:UCLocalize("UPGRADE")];
6098 else if ([package_ uninstalled])
6099 [buttons_ addObject:UCLocalize("INSTALL")];
6101 [buttons_ addObject:UCLocalize("REINSTALL")];
6102 if (![package_ uninstalled])
6103 [buttons_ addObject:UCLocalize("REMOVE")];
6107 switch ([buttons_ count]) {
6108 case 0: title = nil; break;
6109 case 1: title = [buttons_ objectAtIndex:0]; break;
6110 default: title = UCLocalize("MODIFY"); break;
6113 button_ = [[[UIBarButtonItem alloc]
6115 style:UIBarButtonItemStylePlain
6117 action:@selector(customButtonClicked)
6121 - (bool) isLoading {
6122 return commercial_ ? [super isLoading] : false;
6128 /* Package List Controller {{{ */
6129 @interface PackageListController : CyteViewController <
6130 UITableViewDataSource,
6133 _transient Database *database_;
6135 _H<NSArray> packages_;
6136 _H<NSMutableArray> sections_;
6137 _H<UITableView, 2> list_;
6138 _H<NSMutableArray> index_;
6139 _H<NSMutableDictionary> indices_;
6140 _H<NSString> title_;
6141 unsigned reloading_;
6144 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6145 - (void) setDelegate:(id)delegate;
6146 - (void) resetCursor;
6151 @implementation PackageListController
6153 - (NSURL *) referrerURL {
6154 return [self navigationURL];
6157 - (bool) isSummarized {
6161 - (bool) showsSections {
6165 - (void) deselectWithAnimation:(BOOL)animated {
6166 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6169 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6170 CGRect base = [[self view] bounds];
6171 base.size.height -= bounds.size.height;
6172 base.origin = [list_ frame].origin;
6174 [UIView beginAnimations:nil context:NULL];
6175 [UIView setAnimationBeginsFromCurrentState:YES];
6176 [UIView setAnimationCurve:curve];
6177 [UIView setAnimationDuration:duration];
6178 [list_ setFrame:base];
6179 [UIView commitAnimations];
6182 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6183 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6186 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6187 [self resizeForKeyboardBounds:bounds duration:0];
6190 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6191 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6192 *curve = UIViewAnimationCurveEaseInOut;
6194 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6196 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6199 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6202 - (void) keyboardWillShow:(NSNotification *)notification {
6205 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6206 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6208 NSTimeInterval duration;
6209 UIViewAnimationCurve curve;
6210 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6212 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);
6213 UIViewController *base = self;
6214 while ([base parentOrPresentingViewController] != nil)
6215 base = [base parentOrPresentingViewController];
6216 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6217 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6219 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6220 intersection.size.height += CYStatusBarHeight();
6222 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6225 - (void) keyboardWillHide:(NSNotification *)notification {
6226 NSTimeInterval duration;
6227 UIViewAnimationCurve curve;
6228 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6230 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6233 - (void) viewWillAppear:(BOOL)animated {
6234 [super viewWillAppear:animated];
6236 [self resizeForKeyboardBounds:CGRectZero];
6237 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6238 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6241 - (void) viewWillDisappear:(BOOL)animated {
6242 [super viewWillDisappear:animated];
6244 [self resizeForKeyboardBounds:CGRectZero];
6245 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6246 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6249 - (void) viewDidAppear:(BOOL)animated {
6250 [super viewDidAppear:animated];
6251 [self deselectWithAnimation:animated];
6254 - (void) didSelectPackage:(Package *)package {
6255 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6256 [view setDelegate:delegate_];
6257 [[self navigationController] pushViewController:view animated:YES];
6260 #if TryIndexedCollation
6261 + (BOOL) hasIndexedCollation {
6262 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6266 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6267 NSInteger count([sections_ count]);
6268 return count == 0 ? 1 : count;
6271 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6272 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6274 return [[sections_ objectAtIndex:section] name];
6277 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6278 if ([sections_ count] == 0)
6280 return [[sections_ objectAtIndex:section] count];
6283 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6284 @synchronized (database_) {
6285 if ([database_ era] != era_)
6288 Section *section([sections_ objectAtIndex:[path section]]);
6289 NSInteger row([path row]);
6290 Package *package([packages_ objectAtIndex:([section row] + row)]);
6291 return [[package retain] autorelease];
6294 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6295 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6297 cell = [[[PackageCell alloc] init] autorelease];
6299 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6300 [cell setPackage:package asSummary:[self isSummarized]];
6304 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6305 Package *package([self packageAtIndexPath:path]);
6306 package = [database_ packageWithName:[package id]];
6307 [self didSelectPackage:package];
6310 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6311 if (![self showsSections])
6317 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6318 #if TryIndexedCollation
6319 if ([[self class] hasIndexedCollation]) {
6320 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6327 - (void) updateHeight {
6328 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6331 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6332 if ((self = [super init]) != nil) {
6333 database_ = database;
6334 title_ = [title copy];
6335 [[self navigationItem] setTitle:title_];
6340 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6341 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6342 [self setView:view];
6344 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6345 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6346 [view addSubview:list_];
6348 // XXX: is 20 the most optimal number here?
6349 [list_ setSectionIndexMinimumDisplayRowCount:20];
6351 [(UITableView *) list_ setDataSource:self];
6352 [list_ setDelegate:self];
6354 [self updateHeight];
6357 - (void) releaseSubviews {
6365 [super releaseSubviews];
6368 - (void) setDelegate:(id)delegate {
6369 delegate_ = delegate;
6372 - (bool) shouldYield {
6376 - (bool) shouldBlock {
6380 - (NSMutableArray *) _reloadPackages {
6381 @synchronized (database_) {
6382 era_ = [database_ era];
6383 NSArray *packages([database_ packages]);
6385 return [NSMutableArray arrayWithArray:packages];
6388 - (void) _reloadData {
6389 if (reloading_ != 0) {
6397 if ([self shouldYield]) {
6401 if (![self shouldBlock])
6404 hud = [delegate_ addProgressHUD];
6405 [hud setText:UCLocalize("LOADING")];
6409 packages = [self yieldToSelector:@selector(_reloadPackages)];
6412 [delegate_ removeProgressHUD:hud];
6413 } while (reloading_ == 2);
6415 packages = [self _reloadPackages];
6418 @synchronized (database_) {
6419 if (era_ != [database_ era])
6423 packages_ = packages;
6425 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6426 sections_ = [NSMutableArray arrayWithCapacity:16];
6428 Section *section = nil;
6430 #if TryIndexedCollation
6431 if ([[self class] hasIndexedCollation]) {
6432 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6434 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6435 NSArray *titles = [collation sectionIndexTitles];
6438 _profile(PackageTable$reloadData$Section)
6439 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6443 _profile(PackageTable$reloadData$Section$Package)
6444 package = [packages_ objectAtIndex:offset];
6445 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6448 while (secidx < index) {
6451 _profile(PackageTable$reloadData$Section$Allocate)
6452 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6455 _profile(PackageTable$reloadData$Section$Add)
6456 [sections_ addObject:section];
6460 [section addToCount];
6466 index_ = [NSMutableArray arrayWithCapacity:32];
6468 bool sectioned([self showsSections]);
6470 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6471 [sections_ addObject:section];
6474 _profile(PackageTable$reloadData$Section)
6475 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6479 _profile(PackageTable$reloadData$Section$Package)
6480 package = [packages_ objectAtIndex:offset];
6481 index = [package index];
6484 if (sectioned && (section == nil || [section index] != index)) {
6485 _profile(PackageTable$reloadData$Section$Allocate)
6486 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6489 [index_ addObject:[section name]];
6490 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6492 _profile(PackageTable$reloadData$Section$Add)
6493 [sections_ addObject:section];
6497 [section addToCount];
6502 [self updateHeight];
6504 _profile(PackageTable$reloadData$List)
6505 [(UITableView *) list_ setDataSource:self];
6510 - (void) reloadData {
6513 if ([self shouldYield])
6514 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6519 - (void) resetCursor {
6520 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6523 - (void) clearData {
6524 [self updateHeight];
6526 [list_ setDataSource:nil];
6534 /* Filtered Package List Controller {{{ */
6535 @interface FilteredPackageListController : PackageListController {
6538 _H<NSObject> object_;
6541 - (void) setObject:(id)object;
6542 - (void) setObject:(id)object forFilter:(SEL)filter;
6545 - (void) setFilter:(SEL)filter;
6547 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6551 @implementation FilteredPackageListController
6557 - (void) setFilter:(SEL)filter {
6558 @synchronized (self) {
6561 /* XXX: this is an unsafe optimization of doomy hell */
6562 Method method(class_getInstanceMethod([Package class], filter));
6563 _assert(method != NULL);
6564 imp_ = method_getImplementation(method);
6565 _assert(imp_ != NULL);
6568 - (void) setObject:(id)object {
6569 @synchronized (self) {
6573 - (void) setObject:(id)object forFilter:(SEL)filter {
6574 @synchronized (self) {
6575 [self setFilter:filter];
6576 [self setObject:object];
6579 - (NSMutableArray *) _reloadPackages {
6580 @synchronized (database_) {
6581 era_ = [database_ era];
6582 NSArray *packages([database_ packages]);
6584 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6588 _H<NSObject> object;
6590 @synchronized (self) {
6596 _profile(PackageTable$reloadData$Filter)
6597 for (Package *package in packages)
6598 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6599 [filtered addObject:package];
6605 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6606 if ((self = [super initWithDatabase:database title:title]) != nil) {
6607 [self setFilter:filter];
6608 [self setObject:object];
6615 /* Home Controller {{{ */
6616 @interface HomeController : CydiaWebViewController {
6617 CFRunLoopRef runloop_;
6618 SCNetworkReachabilityRef reachability_;
6623 @implementation HomeController
6625 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6626 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6630 if ((self = [super init]) != nil) {
6631 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6634 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6635 if (reachability_ != NULL) {
6636 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6637 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6639 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6640 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6647 if (reachability_ != NULL && runloop_ != NULL)
6648 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6652 - (NSURL *) navigationURL {
6653 return [NSURL URLWithString:@"cydia://home"];
6656 - (void) aboutButtonClicked {
6657 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6659 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6660 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6661 [alert setCancelButtonIndex:0];
6664 @"Copyright \u00a9 2008-2011\n"
6667 "Jay Freeman (saurik)\n"
6668 "saurik@saurik.com\n"
6669 "http://www.saurik.com/"
6675 - (UIBarButtonItem *) leftButton {
6676 return [[[UIBarButtonItem alloc]
6677 initWithTitle:UCLocalize("ABOUT")
6678 style:UIBarButtonItemStylePlain
6680 action:@selector(aboutButtonClicked)
6686 /* Manage Controller {{{ */
6687 @interface ManageController : CydiaWebViewController {
6690 - (void) queueStatusDidChange;
6694 @implementation ManageController
6697 if ((self = [super init]) != nil) {
6698 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6702 - (NSURL *) navigationURL {
6703 return [NSURL URLWithString:@"cydia://manage"];
6706 - (UIBarButtonItem *) leftButton {
6707 return [[[UIBarButtonItem alloc]
6708 initWithTitle:UCLocalize("SETTINGS")
6709 style:UIBarButtonItemStylePlain
6711 action:@selector(settingsButtonClicked)
6715 - (void) settingsButtonClicked {
6716 [delegate_ showSettings];
6719 - (void) queueButtonClicked {
6723 - (UIBarButtonItem *) rightButton {
6724 return Queuing_ ? [[[UIBarButtonItem alloc]
6725 initWithTitle:UCLocalize("QUEUE")
6726 style:UIBarButtonItemStyleDone
6728 action:@selector(queueButtonClicked)
6729 ] autorelease] : nil;
6732 - (void) queueStatusDidChange {
6733 [self applyRightButton];
6736 - (bool) isLoading {
6737 return !Queuing_ && [super isLoading];
6743 /* Refresh Bar {{{ */
6744 @interface RefreshBar : UINavigationBar {
6745 _H<UIProgressIndicator> indicator_;
6746 _H<UITextLabel> prompt_;
6747 _H<UIProgressBar> progress_;
6748 _H<UINavigationButton> cancel_;
6753 @implementation RefreshBar
6755 - (void) positionViews {
6756 CGRect frame = [cancel_ frame];
6757 frame.size = [cancel_ sizeThatFits:frame.size];
6758 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6759 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6760 [cancel_ setFrame:frame];
6762 CGSize prgsize = {75, 100};
6764 [self frame].size.width - prgsize.width - 10,
6765 ([self frame].size.height - prgsize.height) / 2
6767 [progress_ setFrame:prgrect];
6769 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6770 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6771 CGRect indrect = {{indoffset, indoffset}, indsize};
6772 [indicator_ setFrame:indrect];
6774 CGSize prmsize = {215, indsize.height + 4};
6776 indoffset * 2 + indsize.width,
6777 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6779 [prompt_ setFrame:prmrect];
6782 - (void) setFrame:(CGRect)frame {
6783 [super setFrame:frame];
6784 [self positionViews];
6787 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6788 if ((self = [super initWithFrame:frame]) != nil) {
6789 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6791 [self setBarStyle:UIBarStyleBlack];
6793 UIBarStyle barstyle([self _barStyle:NO]);
6794 bool ugly(barstyle == UIBarStyleDefault);
6796 UIProgressIndicatorStyle style = ugly ?
6797 UIProgressIndicatorStyleMediumBrown :
6798 UIProgressIndicatorStyleMediumWhite;
6800 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6801 [(UIProgressIndicator *) indicator_ setStyle:style];
6802 [indicator_ startAnimation];
6803 [self addSubview:indicator_];
6805 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6806 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6807 [prompt_ setBackgroundColor:[UIColor clearColor]];
6808 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6809 [self addSubview:prompt_];
6811 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6812 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6813 [(UIProgressBar *) progress_ setStyle:0];
6814 [self addSubview:progress_];
6816 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6817 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6818 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6819 [cancel_ setBarStyle:barstyle];
6821 [self positionViews];
6825 - (void) setCancellable:(bool)cancellable {
6827 [self addSubview:cancel_];
6829 [cancel_ removeFromSuperview];
6833 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6834 [progress_ setProgress:0];
6838 [self setCancellable:NO];
6841 - (void) setPrompt:(NSString *)prompt {
6842 [prompt_ setText:prompt];
6845 - (void) setProgress:(float)progress {
6846 [progress_ setProgress:progress];
6852 /* Cydia Navigation Controller Interface {{{ */
6853 @interface UINavigationController (Cydia)
6855 - (NSArray *) navigationURLCollection;
6856 - (void) unloadData;
6861 /* Cydia Tab Bar Controller {{{ */
6862 @interface CYTabBarController : UITabBarController <
6863 UITabBarControllerDelegate,
6866 _transient Database *database_;
6867 _H<RefreshBar, 1> refreshbar_;
6871 // XXX: ok, "updatedelegate_"?...
6872 _transient NSObject<CydiaDelegate> *updatedelegate_;
6874 _H<UIViewController> remembered_;
6875 _transient UIViewController *transient_;
6878 - (NSArray *) navigationURLCollection;
6879 - (void) dropBar:(BOOL)animated;
6880 - (void) beginUpdate;
6881 - (void) raiseBar:(BOOL)animated;
6883 - (void) unloadData;
6887 @implementation CYTabBarController
6889 - (void) didReceiveMemoryWarning {
6890 [super didReceiveMemoryWarning];
6892 // presenting a UINavigationController on 2.x does not update its transitionView
6893 // it thereby will not allow its topViewController to be unloaded by memory pressure
6894 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6895 UIViewController *selected([self selectedViewController]);
6896 for (UINavigationController *controller in [self viewControllers])
6897 if (controller != selected)
6898 if (UIViewController *top = [controller topViewController])
6903 - (void) setUnselectedViewController:(UIViewController *)transient {
6904 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6905 if (transient != nil) {
6906 [[[self viewControllers] objectAtIndex:0] pushViewController:transient animated:YES];
6907 [self setSelectedIndex:0];
6911 NSMutableArray *controllers = [[[self viewControllers] mutableCopy] autorelease];
6912 if (transient != nil) {
6913 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
6914 [navigation setViewControllers:[NSArray arrayWithObject:transient]];
6915 transient = navigation;
6917 if (transient_ == nil)
6918 remembered_ = [controllers objectAtIndex:0];
6919 transient_ = transient;
6920 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6921 [controllers replaceObjectAtIndex:0 withObject:transient_];
6922 [self setSelectedIndex:0];
6923 [self setViewControllers:controllers];
6924 [self concealTabBarSelection];
6925 } else if (remembered_ != nil) {
6926 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6927 transient_ = transient;
6928 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6930 [self setViewControllers:controllers];
6931 [self revealTabBarSelection];
6935 - (UIViewController *) unselectedViewController {
6939 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6940 if ([self unselectedViewController])
6941 [self setUnselectedViewController:nil];
6943 // presenting a UINavigationController on 2.x does not update its transitionView
6944 // if this view was unloaded, the tranitionView may currently be presenting nothing
6945 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6946 UINavigationController *navigation((UINavigationController *) viewController);
6947 [navigation pushViewController:[[[UIViewController alloc] init] autorelease] animated:NO];
6948 [navigation popViewControllerAnimated:NO];
6952 - (NSArray *) navigationURLCollection {
6953 NSMutableArray *items([NSMutableArray array]);
6955 // XXX: Should this deal with transient view controllers?
6956 for (id navigation in [self viewControllers]) {
6957 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6959 [items addObject:stack];
6965 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6966 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6967 [self setUnselectedViewController:nil];
6969 [super dismissModalViewControllerAnimated:YES];
6972 - (void) unloadData {
6975 for (UINavigationController *controller in [self viewControllers])
6976 [controller unloadData];
6978 if (UIViewController *selected = [self selectedViewController])
6979 [selected reloadData];
6981 if (UIViewController *unselected = [self unselectedViewController]) {
6982 [unselected unloadData];
6983 [unselected reloadData];
6988 [[NSNotificationCenter defaultCenter] removeObserver:self];
6993 - (id) initWithDatabase:(Database *)database {
6994 if ((self = [super init]) != nil) {
6995 database_ = database;
6996 [self setDelegate:self];
6998 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6999 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7001 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
7005 - (void) setUpdate:(NSDate *)date {
7009 - (void) beginUpdate {
7010 [(RefreshBar *) refreshbar_ start];
7013 [updatedelegate_ retainNetworkActivityIndicator];
7017 detachNewThreadSelector:@selector(performUpdate)
7023 - (void) performUpdate {
7024 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7027 status.setDelegate(self);
7028 [database_ updateWithStatus:status];
7031 performSelectorOnMainThread:@selector(completeUpdate)
7039 - (void) stopUpdateWithSelector:(SEL)selector {
7041 [updatedelegate_ releaseNetworkActivityIndicator];
7043 [self raiseBar:YES];
7046 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7049 - (void) completeUpdate {
7052 [self stopUpdateWithSelector:@selector(reloadData)];
7055 - (void) cancelUpdate {
7056 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7059 - (void) cancelPressed {
7060 [self cancelUpdate];
7067 - (void) addProgressEvent:(CydiaProgressEvent *)event {
7068 [refreshbar_ setPrompt:[event compoundMessage]];
7071 - (bool) isProgressCancelled {
7075 - (void) setProgressCancellable:(NSNumber *)cancellable {
7076 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
7079 - (void) setProgressPercent:(NSNumber *)percent {
7080 [refreshbar_ setProgress:[percent floatValue]];
7083 - (void) setProgressStatus:(NSDictionary *)status {
7085 [self setProgressPercent:[status objectForKey:@"Percent"]];
7088 - (void) setUpdateDelegate:(id)delegate {
7089 updatedelegate_ = delegate;
7092 - (UIView *) transitionView {
7093 if ([self respondsToSelector:@selector(_transitionView)])
7094 return [self _transitionView];
7096 return MSHookIvar<id>(self, "_viewControllerTransitionView");
7099 - (void) dropBar:(BOOL)animated {
7104 UIView *transition([self transitionView]);
7105 [[self view] addSubview:refreshbar_];
7107 CGRect barframe([refreshbar_ frame]);
7109 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
7110 barframe.origin.y = CYStatusBarHeight();
7112 barframe.origin.y = 0;
7114 [refreshbar_ setFrame:barframe];
7117 [UIView beginAnimations:nil context:NULL];
7119 CGRect viewframe = [transition frame];
7120 viewframe.origin.y += barframe.size.height;
7121 viewframe.size.height -= barframe.size.height;
7122 [transition setFrame:viewframe];
7125 [UIView commitAnimations];
7127 // Ensure bar has the proper width for our view, it might have changed
7128 barframe.size.width = viewframe.size.width;
7129 [refreshbar_ setFrame:barframe];
7132 - (void) raiseBar:(BOOL)animated {
7137 UIView *transition([self transitionView]);
7138 [refreshbar_ removeFromSuperview];
7140 CGRect barframe([refreshbar_ frame]);
7143 [UIView beginAnimations:nil context:NULL];
7145 CGRect viewframe = [transition frame];
7146 viewframe.origin.y -= barframe.size.height;
7147 viewframe.size.height += barframe.size.height;
7148 [transition setFrame:viewframe];
7151 [UIView commitAnimations];
7154 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7155 bool dropped(dropped_);
7160 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7166 - (void) statusBarFrameChanged:(NSNotification *)notification {
7176 /* Cydia Navigation Controller Implementation {{{ */
7177 @implementation UINavigationController (Cydia)
7179 - (NSArray *) navigationURLCollection {
7180 NSMutableArray *stack([NSMutableArray array]);
7182 for (CyteViewController *controller in [self viewControllers]) {
7183 NSString *url = [[controller navigationURL] absoluteString];
7185 [stack addObject:url];
7191 - (void) reloadData {
7194 UIViewController *visible([self visibleViewController]);
7196 [visible reloadData];
7198 // on the iPad, this view controller is ALSO visible. :(
7200 if (UIViewController *top = [self topViewController])
7205 - (void) unloadData {
7206 for (CyteViewController *page in [self viewControllers])
7215 /* Cydia:// Protocol {{{ */
7216 @interface CydiaURLProtocol : NSURLProtocol {
7221 @implementation CydiaURLProtocol
7223 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7224 NSURL *url([request URL]);
7228 NSString *scheme([[url scheme] lowercaseString]);
7229 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7231 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7237 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7241 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7242 id<NSURLProtocolClient> client([self client]);
7244 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7246 NSData *data(UIImagePNGRepresentation(icon));
7248 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7249 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7250 [client URLProtocol:self didLoadData:data];
7251 [client URLProtocolDidFinishLoading:self];
7255 - (void) startLoading {
7256 id<NSURLProtocolClient> client([self client]);
7257 NSURLRequest *request([self request]);
7259 NSURL *url([request URL]);
7260 NSString *href([url absoluteString]);
7261 NSString *scheme([[url scheme] lowercaseString]);
7265 if ([scheme isEqualToString:@"cydia"])
7266 path = [href substringFromIndex:8];
7267 else if ([scheme isEqualToString:@"about"])
7268 path = [href substringFromIndex:12];
7269 else _assert(false);
7271 NSRange slash([path rangeOfString:@"/"]);
7274 if (slash.location == NSNotFound) {
7278 command = [path substringToIndex:slash.location];
7279 path = [path substringFromIndex:(slash.location + 1)];
7282 Database *database([Database sharedInstance]);
7284 if ([command isEqualToString:@"package-icon"]) {
7287 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7288 Package *package([database packageWithName:path]);
7292 UIImage *icon([package icon]);
7293 [self _returnPNGWithImage:icon forRequest:request];
7294 } else if ([command isEqualToString:@"uikit-image"]) {
7297 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7298 UIImage *icon(_UIImageWithName(path));
7299 [self _returnPNGWithImage:icon forRequest:request];
7300 } else if ([command isEqualToString:@"section-icon"]) {
7303 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7304 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7306 icon = [UIImage applicationImageNamed:@"unknown.png"];
7307 [self _returnPNGWithImage:icon forRequest:request];
7309 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7313 - (void) stopLoading {
7319 /* Section Controller {{{ */
7320 @interface SectionController : FilteredPackageListController {
7321 _H<IndirectDelegate, 1> indirect_;
7322 _H<CydiaObject> cydia_;
7323 _H<NSString> section_;
7324 std::vector< _H<CyteWebViewTableViewCell, 1> > promoted_;
7327 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7331 @implementation SectionController
7333 - (NSURL *) referrerURL {
7334 NSString *name = section_;
7338 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@", UI_, [name stringByAddingPercentEscapesIncludingReserved]]];
7341 - (NSURL *) navigationURL {
7342 NSString *name = section_;
7346 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", [name stringByAddingPercentEscapesIncludingReserved]]];
7349 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7352 title = UCLocalize("ALL_PACKAGES");
7353 else if (![name isEqual:@""])
7354 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7356 title = UCLocalize("NO_SECTION");
7358 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7359 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7360 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7365 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7366 return [super numberOfSectionsInTableView:list] + 1;
7369 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7370 return section == 0 ? nil : [super tableView:list titleForHeaderInSection:(section - 1)];
7373 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7374 return section == 0 ? promoted_.size() : [super tableView:list numberOfRowsInSection:(section - 1)];
7377 + (NSIndexPath *) adjustedIndexPath:(NSIndexPath *)path {
7378 return [NSIndexPath indexPathForRow:[path row] inSection:([path section] - 1)];
7381 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7382 if ([path section] != 0)
7383 return [super tableView:table cellForRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7385 return promoted_[[path row]];
7388 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
7389 if ([path section] != 0)
7390 return [super tableView:table didSelectRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7393 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
7394 NSInteger section([super tableView:tableView sectionForSectionIndexTitle:title atIndex:index]);
7395 return section == 0 ? 0 : section + 1;
7398 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7399 NSURL *url([request URL]);
7403 if ([frame isEqualToString:@"_open"])
7404 [delegate_ openURL:url];
7406 WebFrame *frame(nil);
7407 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7408 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7410 frame = [view mainFrame];
7412 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7414 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7415 [controller setDelegate:delegate_];
7416 [[self navigationController] pushViewController:controller animated:YES];
7422 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7423 return [CydiaWebViewController requestWithHeaders:request];
7426 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7427 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7433 // XXX: this code is horrible. I mean, wtf Jay?
7434 if (ShowPromoted_ && [[Metadata_ objectForKey:@"ShowPromoted"] boolValue]) {
7435 promoted_.resize(1);
7437 for (unsigned i(0); i != promoted_.size(); ++i) {
7438 CyteWebViewTableViewCell *promoted([CyteWebViewTableViewCell cellWithRequest:[NSURLRequest
7439 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sectionhead/%u/%@",
7440 UI_, i, section_ == nil ? @"" : [section_ stringByAddingPercentEscapesIncludingReserved]]
7443 cachePolicy:NSURLRequestUseProtocolCachePolicy
7447 [promoted setDelegate:self];
7448 promoted_[i] = promoted;
7453 - (void) setDelegate:(id)delegate {
7454 [super setDelegate:delegate];
7455 [cydia_ setDelegate:delegate];
7458 - (void) releaseSubviews {
7460 [super releaseSubviews];
7465 /* Sections Controller {{{ */
7466 @interface SectionsController : CyteViewController <
7467 UITableViewDataSource,
7470 _transient Database *database_;
7471 _H<NSMutableArray> sections_;
7472 _H<NSMutableArray> filtered_;
7473 _H<UITableView, 2> list_;
7476 - (id) initWithDatabase:(Database *)database;
7477 - (void) editButtonClicked;
7481 @implementation SectionsController
7483 - (NSURL *) navigationURL {
7484 return [NSURL URLWithString:@"cydia://sections"];
7487 - (void) updateNavigationItem {
7488 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7489 if ([sections_ count] == 0) {
7490 [[self navigationItem] setRightBarButtonItem:nil];
7492 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7493 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7495 action:@selector(editButtonClicked)
7496 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7500 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7501 [super setEditing:editing animated:animated];
7506 [delegate_ updateData];
7508 [self updateNavigationItem];
7511 - (void) viewDidAppear:(BOOL)animated {
7512 [super viewDidAppear:animated];
7513 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7516 - (void) viewWillDisappear:(BOOL)animated {
7517 [super viewWillDisappear:animated];
7518 [self setEditing:NO];
7521 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7522 Section *section = nil;
7523 int index = [indexPath row];
7524 if (![self isEditing]) {
7527 section = [filtered_ objectAtIndex:index];
7529 section = [sections_ objectAtIndex:index];
7534 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7535 if ([self isEditing])
7536 return [sections_ count];
7538 return [filtered_ count] + 1;
7541 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7545 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7546 static NSString *reuseIdentifier = @"SectionCell";
7548 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7550 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7552 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7557 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7558 if ([self isEditing])
7561 Section *section = [self sectionAtIndexPath:indexPath];
7563 SectionController *controller = [[[SectionController alloc]
7564 initWithDatabase:database_
7565 section:[section name]
7567 [controller setDelegate:delegate_];
7569 [[self navigationController] pushViewController:controller animated:YES];
7573 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7574 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7575 [list_ setRowHeight:45.0f];
7576 [(UITableView *) list_ setDataSource:self];
7577 [list_ setDelegate:self];
7578 [self setView:list_];
7581 - (void) viewDidLoad {
7582 [super viewDidLoad];
7584 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7587 - (void) releaseSubviews {
7593 [super releaseSubviews];
7596 - (id) initWithDatabase:(Database *)database {
7597 if ((self = [super init]) != nil) {
7598 database_ = database;
7602 - (void) reloadData {
7605 NSArray *packages = [database_ packages];
7607 sections_ = [NSMutableArray arrayWithCapacity:16];
7608 filtered_ = [NSMutableArray arrayWithCapacity:16];
7610 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7613 for (Package *package in packages) {
7614 NSString *name([package section]);
7615 NSString *key(name == nil ? @"" : name);
7619 _profile(SectionsView$reloadData$Section)
7620 section = [sections objectForKey:key];
7621 if (section == nil) {
7622 _profile(SectionsView$reloadData$Section$Allocate)
7623 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7624 [sections setObject:section forKey:key];
7629 [section addToCount];
7631 _profile(SectionsView$reloadData$Filter)
7632 if (![package valid] || ![package visible])
7640 [sections_ addObjectsFromArray:[sections allValues]];
7642 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7644 for (Section *section in (id) sections_) {
7645 size_t count([section row]);
7649 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7650 [section setCount:count];
7651 [filtered_ addObject:section];
7654 [self updateNavigationItem];
7659 - (void) editButtonClicked {
7660 [self setEditing:![self isEditing] animated:YES];
7666 /* Changes Controller {{{ */
7667 @interface ChangesController : CyteViewController <
7668 CyteWebViewDelegate,
7669 UITableViewDataSource,
7672 _transient Database *database_;
7674 _H<NSMutableArray> packages_;
7675 _H<NSMutableArray> sections_;
7676 _H<UITableView, 2> list_;
7677 _H<CyteWebView, 1> dickbar_;
7679 _H<IndirectDelegate, 1> indirect_;
7680 _H<CydiaObject> cydia_;
7683 - (id) initWithDatabase:(Database *)database;
7687 @implementation ChangesController
7689 - (NSURL *) navigationURL {
7690 return [NSURL URLWithString:@"cydia://changes"];
7693 - (void) viewDidAppear:(BOOL)animated {
7694 [super viewDidAppear:animated];
7695 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7698 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7699 NSInteger count([sections_ count]);
7700 return count == 0 ? 1 : count;
7703 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7704 if ([sections_ count] == 0)
7706 return [[sections_ objectAtIndex:section] name];
7709 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7710 if ([sections_ count] == 0)
7712 return [[sections_ objectAtIndex:section] count];
7715 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7716 @synchronized (database_) {
7717 if ([database_ era] != era_)
7720 NSUInteger sectionIndex([path section]);
7721 if (sectionIndex >= [sections_ count])
7723 Section *section([sections_ objectAtIndex:sectionIndex]);
7724 NSInteger row([path row]);
7725 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7728 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7729 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7731 cell = [[[PackageCell alloc] init] autorelease];
7733 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7734 [cell setPackage:package asSummary:false];
7738 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7739 Package *package([self packageAtIndexPath:path]);
7740 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[NSString stringWithFormat:@"%@/#!/changes/", UI_]] autorelease]);
7741 [view setDelegate:delegate_];
7742 [[self navigationController] pushViewController:view animated:YES];
7746 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7747 NSString *context([alert context]);
7749 if ([context isEqualToString:@"norefresh"])
7750 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7753 - (void) refreshButtonClicked {
7754 if (IsReachable("cydia.saurik.com")) {
7755 [delegate_ beginUpdate];
7756 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7758 UIAlertView *alert = [[[UIAlertView alloc]
7759 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
7760 message:@"Host Unreachable" // XXX: Localize
7762 cancelButtonTitle:UCLocalize("OK")
7763 otherButtonTitles:nil
7766 [alert setContext:@"norefresh"];
7771 - (void) upgradeButtonClicked {
7772 [delegate_ distUpgrade];
7773 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7777 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7778 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7779 [self setView:view];
7781 list_ = [[[UITableView alloc] initWithFrame:[view bounds] style:UITableViewStylePlain] autorelease];
7782 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7783 [list_ setRowHeight:73];
7784 [(UITableView *) list_ setDataSource:self];
7785 [list_ setDelegate:self];
7786 [view addSubview:list_];
7788 if (AprilFools_ && kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
7789 CGRect dickframe([view bounds]);
7790 dickframe.size.height = 44;
7792 dickbar_ = [[[CyteWebView alloc] initWithFrame:dickframe] autorelease];
7793 [dickbar_ setDelegate:self];
7794 [view addSubview:dickbar_];
7796 [dickbar_ setBackgroundColor:[UIColor clearColor]];
7797 [dickbar_ setScalesPageToFit:YES];
7799 UIWebDocumentView *document([dickbar_ _documentView]);
7800 [document setBackgroundColor:[UIColor clearColor]];
7801 [document setDrawsBackground:NO];
7803 WebView *webview([document webView]);
7804 [webview setShouldUpdateWhileOffscreen:NO];
7806 UIScrollView *scroller([dickbar_ scrollView]);
7807 [scroller setScrollingEnabled:NO];
7808 [scroller setFixedBackgroundPattern:YES];
7809 [scroller setBackgroundColor:[UIColor clearColor]];
7811 WebPreferences *preferences([webview preferences]);
7812 [preferences setCacheModel:WebCacheModelDocumentBrowser];
7813 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
7814 [preferences setOfflineWebApplicationCacheEnabled:YES];
7816 [dickbar_ loadRequest:[NSURLRequest
7817 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/dickbar/", UI_]]]
7818 cachePolicy:NSURLRequestUseProtocolCachePolicy
7822 UIEdgeInsets inset = {44, 0, 0, 0};
7823 [list_ setContentInset:inset];
7825 [dickbar_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7829 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7830 NSURL *url([request URL]);
7834 if ([frame isEqualToString:@"_open"])
7835 [delegate_ openURL:url];
7837 WebFrame *frame(nil);
7838 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7839 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7841 frame = [view mainFrame];
7843 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7845 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7846 [controller setDelegate:delegate_];
7847 [[self navigationController] pushViewController:controller animated:YES];
7853 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7854 return [CydiaWebViewController requestWithHeaders:request];
7857 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7858 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7861 - (void) setDelegate:(id)delegate {
7862 [super setDelegate:delegate];
7863 [cydia_ setDelegate:delegate];
7866 - (void) viewDidLoad {
7867 [super viewDidLoad];
7869 [[self navigationItem] setTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES"))];
7872 - (void) releaseSubviews {
7879 [super releaseSubviews];
7882 - (id) initWithDatabase:(Database *)database {
7883 if ((self = [super init]) != nil) {
7884 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7885 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7886 database_ = database;
7890 - (NSMutableArray *) _reloadPackages {
7891 @synchronized (database_) {
7892 era_ = [database_ era];
7893 NSArray *packages([database_ packages]);
7895 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7898 _profile(ChangesController$_reloadPackages$Filter)
7899 for (Package *package in packages)
7900 if ([package upgradableAndEssential:YES] || [package visible])
7901 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7904 _profile(ChangesController$_reloadPackages$radixSort)
7905 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7912 - (void) _reloadData {
7913 NSMutableArray *packages;
7917 UIProgressHUD *hud([delegate_ addProgressHUD]);
7918 [hud setText:UCLocalize("LOADING")];
7919 //NSLog(@"HUD:%@::%@", delegate_, hud);
7920 packages = [self yieldToSelector:@selector(_reloadPackages)];
7921 [delegate_ removeProgressHUD:hud];
7923 packages = [self _reloadPackages];
7926 @synchronized (database_) {
7927 if (era_ != [database_ era])
7930 packages_ = packages;
7931 sections_ = [NSMutableArray arrayWithCapacity:16];
7933 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7934 Section *ignored = nil;
7935 Section *section = nil;
7939 bool unseens = false;
7941 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7943 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7944 Package *package = [packages_ objectAtIndex:offset];
7946 BOOL uae = [package upgradableAndEssential:YES];
7950 time_t seen([package seen]);
7952 if (section == nil || last != seen) {
7956 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7959 _profile(ChangesController$reloadData$Allocate)
7960 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7961 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7962 [sections_ addObject:section];
7966 [section addToCount];
7967 } else if ([package ignored]) {
7968 if (ignored == nil) {
7969 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7971 [ignored addToCount];
7974 [upgradable addToCount];
7979 CFRelease(formatter);
7982 Section *last = [sections_ lastObject];
7983 size_t count = [last count];
7984 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7985 [sections_ removeLastObject];
7988 if ([ignored count] != 0)
7989 [sections_ insertObject:ignored atIndex:0];
7991 [sections_ insertObject:upgradable atIndex:0];
7995 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7996 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7997 style:UIBarButtonItemStylePlain
7999 action:@selector(upgradeButtonClicked)
8000 ] autorelease]) animated:YES];
8002 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
8003 initWithTitle:UCLocalize("REFRESH")
8004 style:UIBarButtonItemStylePlain
8006 action:@selector(refreshButtonClicked)
8007 ] autorelease]) animated:YES];
8012 - (void) reloadData {
8014 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
8019 /* Search Controller {{{ */
8020 @interface SearchController : FilteredPackageListController <
8023 _H<UISearchBar, 1> search_;
8027 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
8028 - (void) reloadData;
8032 @implementation SearchController
8034 - (NSURL *) referrerURL {
8035 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
8038 - (NSURL *) navigationURL {
8039 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
8040 return [NSURL URLWithString:@"cydia://search"];
8042 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
8045 - (NSArray *) termsForQuery:(NSString *)query {
8046 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
8047 for (NSString *component in [query componentsSeparatedByString:@" "])
8048 if ([component length] != 0)
8049 [terms addObject:component];
8054 - (void) useSearch {
8055 [self setObject:[self termsForQuery:[search_ text]] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
8060 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
8061 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8066 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
8067 [search_ resignFirstResponder];
8071 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
8072 [search_ setText:@""];
8073 [self searchBarButtonClicked:searchBar];
8076 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
8077 [self searchBarButtonClicked:searchBar];
8080 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
8081 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8085 - (bool) shouldYield {
8089 - (bool) shouldBlock {
8090 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
8093 - (bool) isSummarized {
8094 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
8097 - (bool) showsSections {
8101 - (NSMutableArray *) _reloadPackages {
8102 NSMutableArray *packages([super _reloadPackages]);
8103 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8104 [packages radixSortUsingSelector:@selector(rank)];
8108 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
8109 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[self termsForQuery:query]])) {
8110 search_ = [[[UISearchBar alloc] init] autorelease];
8111 [search_ setDelegate:self];
8114 [search_ setText:query];
8118 - (void) viewDidAppear:(BOOL)animated {
8119 [super viewDidAppear:animated];
8121 if (!searchloaded_) {
8122 searchloaded_ = YES;
8123 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
8124 [search_ layoutSubviews];
8125 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
8127 UITextField *textField;
8128 if ([search_ respondsToSelector:@selector(searchField)])
8129 textField = [search_ searchField];
8131 textField = MSHookIvar<UITextField *>(search_, "_searchField");
8133 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8134 [textField setEnablesReturnKeyAutomatically:NO];
8135 [[self navigationItem] setTitleView:textField];
8138 if ([self isSummarized])
8139 [search_ becomeFirstResponder];
8142 - (void) reloadData {
8143 id object([search_ text]);
8144 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8145 object = [self termsForQuery:object];
8147 [self setObject:object];
8153 - (void) didSelectPackage:(Package *)package {
8154 [search_ resignFirstResponder];
8155 [super didSelectPackage:package];
8160 /* Package Settings Controller {{{ */
8161 @interface PackageSettingsController : CyteViewController <
8162 UITableViewDataSource,
8165 _transient Database *database_;
8167 _H<Package> package_;
8168 _H<UITableView, 2> table_;
8169 _H<UISwitch> subscribedSwitch_;
8170 _H<UISwitch> ignoredSwitch_;
8171 _H<UITableViewCell> subscribedCell_;
8172 _H<UITableViewCell> ignoredCell_;
8175 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
8179 @implementation PackageSettingsController
8181 - (NSURL *) navigationURL {
8182 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
8185 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8186 if (package_ == nil)
8189 if ([package_ installed] == nil)
8195 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8196 if (package_ == nil)
8199 // both sections contain just one item right now.
8203 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8207 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8209 return UCLocalize("SHOW_ALL_CHANGES_EX");
8211 return UCLocalize("IGNORE_UPGRADES_EX");
8214 - (void) onSubscribed:(id)control {
8215 bool value([control isOn]);
8216 if (package_ == nil)
8218 if ([package_ setSubscribed:value])
8219 [delegate_ updateData];
8222 - (void) _updateIgnored {
8223 const char *package([name_ UTF8String]);
8224 bool on([ignoredSwitch_ isOn]);
8226 pid_t pid(ExecFork());
8228 FILE *dpkg(popen("dpkg --set-selections", "w"));
8229 fwrite(package, strlen(package), 1, dpkg);
8232 fwrite(" hold\n", 6, 1, dpkg);
8234 fwrite(" install\n", 9, 1, dpkg);
8245 - (void) onIgnored:(id)control {
8246 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8247 [invocation setTarget:self];
8248 [invocation setSelector:@selector(_updateIgnored)];
8250 [delegate_ reloadDataWithInvocation:invocation];
8253 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8254 if (package_ == nil)
8257 switch ([indexPath section]) {
8258 case 0: return subscribedCell_;
8259 case 1: return ignoredCell_;
8268 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8269 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8270 [self setView:view];
8272 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8273 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8274 [(UITableView *) table_ setDataSource:self];
8275 [table_ setDelegate:self];
8276 [view addSubview:table_];
8278 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8279 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8280 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8282 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8283 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8284 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8286 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8287 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8288 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8289 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8291 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8292 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8293 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8294 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8297 - (void) viewDidLoad {
8298 [super viewDidLoad];
8300 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8303 - (void) releaseSubviews {
8305 subscribedCell_ = nil;
8307 ignoredSwitch_ = nil;
8308 subscribedSwitch_ = nil;
8310 [super releaseSubviews];
8313 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8314 if ((self = [super init]) != nil) {
8315 database_ = database;
8320 - (void) reloadData {
8323 package_ = [database_ packageWithName:name_];
8325 if (package_ != nil) {
8326 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8327 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8328 } // XXX: what now, G?
8330 [table_ reloadData];
8336 /* Installed Controller {{{ */
8337 @interface InstalledController : FilteredPackageListController {
8341 - (id) initWithDatabase:(Database *)database;
8343 - (void) updateRoleButton;
8344 - (void) queueStatusDidChange;
8348 @implementation InstalledController
8350 - (NSURL *) referrerURL {
8351 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8354 - (NSURL *) navigationURL {
8355 return [NSURL URLWithString:@"cydia://installed"];
8358 - (id) initWithDatabase:(Database *)database {
8359 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8360 [self updateRoleButton];
8361 [self queueStatusDidChange];
8366 - (void) queueButtonClicked {
8371 - (void) queueStatusDidChange {
8375 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8376 initWithTitle:UCLocalize("QUEUE")
8377 style:UIBarButtonItemStyleDone
8379 action:@selector(queueButtonClicked)
8382 [[self navigationItem] setLeftBarButtonItem:nil];
8388 - (void) updateRoleButton {
8389 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8390 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8391 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8392 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8394 action:@selector(roleButtonClicked)
8398 - (void) roleButtonClicked {
8399 [self setObject:[NSNumber numberWithBool:expert_]];
8403 [self updateRoleButton];
8409 /* Source Cell {{{ */
8410 @interface SourceCell : CyteTableViewCell <
8411 CyteTableViewCellDelegate
8415 _H<NSString> origin_;
8416 _H<NSString> label_;
8419 - (void) setSource:(Source *)source;
8423 @implementation SourceCell
8425 - (void) _setImage:(NSArray *)data {
8426 if ([url_ isEqual:[data objectAtIndex:0]]) {
8427 icon_ = [data objectAtIndex:1];
8428 [content_ setNeedsDisplay];
8432 - (void) _setSource:(NSURL *) url {
8433 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8435 if (NSData *data = [NSURLConnection
8436 sendSynchronousRequest:[NSURLRequest
8438 cachePolicy:NSURLRequestUseProtocolCachePolicy
8442 returningResponse:NULL
8445 if (UIImage *image = [UIImage imageWithData:data])
8446 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8451 - (void) setSource:(Source *)source {
8452 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8454 origin_ = [source name];
8455 label_ = [source rooturi];
8457 [content_ setNeedsDisplay];
8459 url_ = [source iconURL];
8460 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8463 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8464 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8465 UIView *content([self contentView]);
8466 CGRect bounds([content bounds]);
8468 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8469 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8470 [content_ setBackgroundColor:[UIColor whiteColor]];
8471 [content addSubview:content_];
8473 [content_ setDelegate:self];
8474 [content_ setOpaque:YES];
8476 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8480 - (NSString *) accessibilityLabel {
8484 - (void) drawContentRect:(CGRect)rect {
8485 bool highlighted(highlighted_);
8486 float width(rect.size.width);
8490 rect.size = [(UIImage *) icon_ size];
8492 while (rect.size.width > 32 || rect.size.height > 32) {
8493 rect.size.width /= 2;
8494 rect.size.height /= 2;
8497 rect.origin.x = 25 - rect.size.width / 2;
8498 rect.origin.y = 25 - rect.size.height / 2;
8500 [icon_ drawInRect:rect];
8508 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 65) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8512 [label_ drawAtPoint:CGPointMake(48, 29) forWidth:(width - 65) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8517 /* Source Controller {{{ */
8518 @interface SourceController : FilteredPackageListController {
8519 _transient Source *source_;
8523 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8527 @implementation SourceController
8529 - (NSURL *) referrerURL {
8530 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sources/%@", UI_, [key_ stringByAddingPercentEscapesIncludingReserved]]];
8533 - (NSURL *) navigationURL {
8534 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8537 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8538 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8540 key_ = [source key];
8544 - (void) reloadData {
8545 source_ = [database_ sourceWithKey:key_];
8546 key_ = [source_ key];
8547 [self setObject:source_];
8549 [[self navigationItem] setTitle:[source_ label]];
8556 /* Sources Controller {{{ */
8557 @interface SourcesController : CyteViewController <
8558 UITableViewDataSource,
8561 _transient Database *database_;
8564 _H<UITableView, 2> list_;
8565 _H<NSMutableArray> sources_;
8569 _H<UIProgressHUD> hud_;
8572 //NSURLConnection *installer_;
8573 NSURLConnection *trivial_;
8574 NSURLConnection *trivial_bz2_;
8575 NSURLConnection *trivial_gz_;
8576 //NSURLConnection *automatic_;
8581 - (id) initWithDatabase:(Database *)database;
8582 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8586 @implementation SourcesController
8588 - (void) _releaseConnection:(NSURLConnection *)connection {
8589 if (connection != nil) {
8590 [connection cancel];
8591 //[connection setDelegate:nil];
8592 [connection release];
8597 //[self _releaseConnection:installer_];
8598 [self _releaseConnection:trivial_];
8599 [self _releaseConnection:trivial_gz_];
8600 [self _releaseConnection:trivial_bz2_];
8601 //[self _releaseConnection:automatic_];
8606 - (NSURL *) navigationURL {
8607 return [NSURL URLWithString:@"cydia://sources"];
8610 - (void) viewDidAppear:(BOOL)animated {
8611 [super viewDidAppear:animated];
8612 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8615 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8619 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8623 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8624 return [sources_ count];
8627 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8628 @synchronized (database_) {
8629 if ([database_ era] != era_)
8632 NSUInteger index([indexPath row]);
8633 return index < [sources_ count] ? [sources_ objectAtIndex:index] : nil;
8636 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8637 static NSString *cellIdentifier = @"SourceCell";
8639 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8640 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8641 [cell setSource:[self sourceAtIndexPath:indexPath]];
8642 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8647 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8648 Source *source = [self sourceAtIndexPath:indexPath];
8649 if (source == nil) return;
8651 SourceController *controller = [[[SourceController alloc]
8652 initWithDatabase:database_
8656 [controller setDelegate:delegate_];
8658 [[self navigationController] pushViewController:controller animated:YES];
8661 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8662 Source *source = [self sourceAtIndexPath:indexPath];
8663 return [source record] != nil;
8666 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8667 if (editingStyle == UITableViewCellEditingStyleDelete) {
8668 Source *source = [self sourceAtIndexPath:indexPath];
8669 if (source == nil) return;
8671 [Sources_ removeObjectForKey:[source key]];
8672 [delegate_ _saveConfig];
8673 [delegate_ reloadDataWithInvocation:nil];
8678 [delegate_ addTrivialSource:href_];
8681 [delegate_ syncData];
8684 - (NSString *) getWarning {
8685 NSString *href(href_);
8686 NSRange colon([href rangeOfString:@"://"]);
8687 if (colon.location != NSNotFound)
8688 href = [href substringFromIndex:(colon.location + 3)];
8689 href = [href stringByAddingPercentEscapes];
8690 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8692 NSURL *url([NSURL URLWithString:href]);
8694 NSStringEncoding encoding;
8695 NSError *error(nil);
8697 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8698 return [warning length] == 0 ? nil : warning;
8702 - (void) _endConnection:(NSURLConnection *)connection {
8703 // XXX: the memory management in this method is horribly awkward
8705 NSURLConnection **field = NULL;
8706 if (connection == trivial_)
8708 else if (connection == trivial_bz2_)
8709 field = &trivial_bz2_;
8710 else if (connection == trivial_gz_)
8711 field = &trivial_gz_;
8712 _assert(field != NULL);
8713 [connection release];
8718 trivial_bz2_ == nil &&
8721 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8723 [delegate_ releaseNetworkActivityIndicator];
8725 [delegate_ removeProgressHUD:hud_];
8729 if (warning != nil) {
8730 UIAlertView *alert = [[[UIAlertView alloc]
8731 initWithTitle:UCLocalize("SOURCE_WARNING")
8734 cancelButtonTitle:UCLocalize("CANCEL")
8736 UCLocalize("ADD_ANYWAY"),
8740 [alert setContext:@"warning"];
8741 [alert setNumberOfRows:1];
8744 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8750 } else if (error_ != nil) {
8751 UIAlertView *alert = [[[UIAlertView alloc]
8752 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8753 message:[error_ localizedDescription]
8755 cancelButtonTitle:UCLocalize("OK")
8756 otherButtonTitles:nil
8759 [alert setContext:@"urlerror"];
8764 UIAlertView *alert = [[[UIAlertView alloc]
8765 initWithTitle:UCLocalize("NOT_REPOSITORY")
8766 message:UCLocalize("NOT_REPOSITORY_EX")
8768 cancelButtonTitle:UCLocalize("OK")
8769 otherButtonTitles:nil
8772 [alert setContext:@"trivial"];
8782 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8783 switch ([response statusCode]) {
8789 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8790 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8792 [self _endConnection:connection];
8795 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8796 [self _endConnection:connection];
8799 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8800 NSURL *url([NSURL URLWithString:href]);
8802 NSMutableURLRequest *request = [NSMutableURLRequest
8804 cachePolicy:NSURLRequestUseProtocolCachePolicy
8808 [request setHTTPMethod:method];
8810 if (Machine_ != NULL)
8811 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8813 if (UniqueID_ != nil)
8814 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8816 if ([url isCydiaSecure]) {
8817 if (UniqueID_ != nil)
8818 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8821 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8824 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8825 NSString *context([alert context]);
8827 if ([context isEqualToString:@"source"]) {
8830 NSString *href = [[alert textField] text];
8832 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8834 if (![href hasSuffix:@"/"])
8835 href_ = [href stringByAppendingString:@"/"];
8839 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8840 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8841 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8842 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8846 // XXX: this is stupid
8847 hud_ = [delegate_ addProgressHUD];
8848 [hud_ setText:UCLocalize("VERIFYING_URL")];
8849 [delegate_ retainNetworkActivityIndicator];
8858 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8859 } else if ([context isEqualToString:@"trivial"])
8860 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8861 else if ([context isEqualToString:@"urlerror"])
8862 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8863 else if ([context isEqualToString:@"warning"]) {
8866 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8875 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8880 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8881 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8882 [list_ setRowHeight:53];
8883 [(UITableView *) list_ setDataSource:self];
8884 [list_ setDelegate:self];
8885 [self setView:list_];
8888 - (void) viewDidLoad {
8889 [super viewDidLoad];
8891 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8892 [self updateButtonsForEditingStatusAnimated:NO];
8895 - (void) viewWillAppear:(BOOL)animated {
8896 [super viewWillAppear:animated];
8898 [list_ setEditing:NO];
8899 [self updateButtonsForEditingStatusAnimated:NO];
8902 - (void) releaseSubviews {
8907 [super releaseSubviews];
8910 - (id) initWithDatabase:(Database *)database {
8911 if ((self = [super init]) != nil) {
8912 database_ = database;
8916 - (void) reloadData {
8919 @synchronized (database_) {
8920 era_ = [database_ era];
8922 sources_ = [NSMutableArray arrayWithCapacity:16];
8923 [sources_ addObjectsFromArray:[database_ sources]];
8925 [sources_ sortUsingSelector:@selector(compareByName:)];
8928 int count([sources_ count]);
8930 for (int i = 0; i != count; i++) {
8931 if ([[sources_ objectAtIndex:i] record] == nil)
8939 - (void) showAddSourcePrompt {
8940 UIAlertView *alert = [[[UIAlertView alloc]
8941 initWithTitle:UCLocalize("ENTER_APT_URL")
8944 cancelButtonTitle:UCLocalize("CANCEL")
8946 UCLocalize("ADD_SOURCE"),
8950 [alert setContext:@"source"];
8952 [alert setNumberOfRows:1];
8953 [alert addTextFieldWithValue:@"http://" label:@""];
8955 UITextInputTraits *traits = [[alert textField] textInputTraits];
8956 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8957 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8958 [traits setKeyboardType:UIKeyboardTypeURL];
8959 // XXX: UIReturnKeyDone
8960 [traits setReturnKeyType:UIReturnKeyNext];
8965 - (void) addButtonClicked {
8966 [self showAddSourcePrompt];
8969 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8970 BOOL editing([list_ isEditing]);
8972 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8973 initWithTitle:UCLocalize("ADD")
8974 style:UIBarButtonItemStylePlain
8976 action:@selector(addButtonClicked)
8977 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8979 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8980 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8981 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8983 action:@selector(editButtonClicked)
8984 ] autorelease] animated:animated];
8986 if (IsWildcat_ && !editing)
8987 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8988 initWithTitle:UCLocalize("SETTINGS")
8989 style:UIBarButtonItemStylePlain
8991 action:@selector(settingsButtonClicked)
8995 - (void) settingsButtonClicked {
8996 [delegate_ showSettings];
8999 - (void) editButtonClicked {
9000 [list_ setEditing:![list_ isEditing] animated:YES];
9001 [self updateButtonsForEditingStatusAnimated:YES];
9007 /* Settings Controller {{{ */
9008 @interface SettingsController : CyteViewController <
9009 UITableViewDataSource,
9012 _transient Database *database_;
9013 // XXX: ok, "roledelegate_"?...
9014 _transient id roledelegate_;
9015 _H<UITableView, 2> table_;
9016 _H<UISegmentedControl> segment_;
9017 _H<UIView> container_;
9020 - (void) showDoneButton;
9021 - (void) resizeSegmentedControl;
9025 @implementation SettingsController
9028 table_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
9029 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9030 [table_ setDelegate:self];
9031 [(UITableView *) table_ setDataSource:self];
9032 [self setView:table_];
9034 NSArray *items = [NSArray arrayWithObjects:
9036 UCLocalize("HACKER"),
9037 UCLocalize("DEVELOPER"),
9039 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
9040 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
9041 [container_ addSubview:segment_];
9044 - (void) viewDidLoad {
9045 [super viewDidLoad];
9047 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
9050 if ([Role_ isEqualToString:@"User"]) index = 0;
9051 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
9052 if ([Role_ isEqualToString:@"Developer"]) index = 2;
9054 [segment_ setSelectedSegmentIndex:index];
9055 [self showDoneButton];
9058 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
9059 [self resizeSegmentedControl];
9062 - (void) releaseSubviews {
9067 [super releaseSubviews];
9070 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
9071 if ((self = [super init]) != nil) {
9072 database_ = database;
9073 roledelegate_ = delegate;
9077 - (void) resizeSegmentedControl {
9078 CGFloat width = [[self view] frame].size.width;
9079 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
9082 - (void) viewWillAppear:(BOOL)animated {
9083 [super viewWillAppear:animated];
9084 [self resizeSegmentedControl];
9087 - (void) viewDidAppear:(BOOL)animated {
9088 [super viewDidAppear:animated];
9089 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
9090 [self resizeSegmentedControl];
9093 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
9094 [self resizeSegmentedControl];
9097 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
9098 [self resizeSegmentedControl];
9102 NSString *role(nil);
9104 switch ([segment_ selectedSegmentIndex]) {
9105 case 0: role = @"User"; break;
9106 case 1: role = @"Hacker"; break;
9107 case 2: role = @"Developer"; break;
9112 if (![role isEqualToString:Role_]) {
9113 bool rolling(Role_ == nil);
9116 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
9120 [Metadata_ setObject:Settings_ forKey:@"Settings"];
9124 [roledelegate_ loadData];
9126 [roledelegate_ updateData];
9130 - (void) segmentChanged:(UISegmentedControl *)control {
9131 [self showDoneButton];
9134 - (void) saveAndClose {
9137 [[self navigationItem] setRightBarButtonItem:nil];
9138 [[self navigationController] dismissModalViewControllerAnimated:YES];
9141 - (void) doneButtonClicked {
9142 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
9143 [spinner startAnimating];
9144 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
9145 [[self navigationItem] setRightBarButtonItem:spinItem];
9147 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
9150 - (void) showDoneButton {
9151 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
9152 initWithTitle:UCLocalize("DONE")
9153 style:UIBarButtonItemStyleDone
9155 action:@selector(doneButtonClicked)
9156 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
9159 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
9160 // XXX: For not having a single cell in the table, this sure is a lot of sections.
9164 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
9168 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
9169 return nil; // This method is required by the protocol.
9172 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
9174 return UCLocalize("ROLE_EX");
9176 return [NSString stringWithFormat:
9177 @"%@: %@\n%@: %@\n%@: %@",
9178 UCLocalize("USER"), UCLocalize("USER_EX"),
9179 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
9180 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
9185 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
9186 return section == 3 ? 44.0f : 0;
9189 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
9190 return section == 3 ? container_ : nil;
9193 - (void) reloadData {
9196 [table_ reloadData];
9201 /* Stash Controller {{{ */
9202 @interface StashController : CyteViewController {
9203 _H<UIActivityIndicatorView> spinner_;
9204 _H<UILabel> status_;
9205 _H<UILabel> caption_;
9210 @implementation StashController
9213 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
9214 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
9215 [self setView:view];
9217 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
9219 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
9220 CGRect spinrect = [spinner_ frame];
9221 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
9222 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
9223 [spinner_ setFrame:spinrect];
9224 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
9225 [view addSubview:spinner_];
9226 [spinner_ startAnimating];
9229 captrect.size.width = [[self view] frame].size.width;
9230 captrect.size.height = 40.0f;
9231 captrect.origin.x = 0;
9232 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
9233 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
9234 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
9235 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9236 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
9237 [caption_ setTextColor:[UIColor whiteColor]];
9238 [caption_ setBackgroundColor:[UIColor clearColor]];
9239 [caption_ setShadowColor:[UIColor blackColor]];
9240 [caption_ setTextAlignment:UITextAlignmentCenter];
9241 [view addSubview:caption_];
9244 statusrect.size.width = [[self view] frame].size.width;
9245 statusrect.size.height = 30.0f;
9246 statusrect.origin.x = 0;
9247 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
9248 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
9249 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9250 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
9251 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
9252 [status_ setTextColor:[UIColor whiteColor]];
9253 [status_ setBackgroundColor:[UIColor clearColor]];
9254 [status_ setShadowColor:[UIColor blackColor]];
9255 [status_ setTextAlignment:UITextAlignmentCenter];
9256 [view addSubview:status_];
9259 - (void) releaseSubviews {
9264 [super releaseSubviews];
9270 @interface CYURLCache : SDURLCache {
9275 @implementation CYURLCache
9277 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
9280 else if ([event isEqualToString:@"no-cache"])
9282 else if ([event isEqualToString:@"store"])
9284 else if ([event isEqualToString:@"invalid"])
9286 else if ([event isEqualToString:@"memory"])
9288 else if ([event isEqualToString:@"disk"])
9290 else if ([event isEqualToString:@"miss"])
9293 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
9297 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
9298 if (NSURLResponse *response = [cached response])
9299 if (NSString *mime = [response MIMEType])
9300 if ([mime isEqualToString:@"text/cache-manifest"]) {
9301 NSURL *url([response URL]);
9304 NSLog(@"###: %@", [url absoluteString]);
9307 @synchronized (HostConfig_) {
9308 [CachedURLs_ addObject:url];
9312 [super storeCachedResponse:cached forRequest:request];
9317 @interface Cydia : UIApplication <
9318 ConfirmationControllerDelegate,
9321 UINavigationControllerDelegate,
9322 UITabBarControllerDelegate
9324 _H<UIWindow> window_;
9325 _H<CYTabBarController> tabbar_;
9326 _H<CydiaLoadingViewController> emulated_;
9328 _H<NSMutableArray> essential_;
9329 _H<NSMutableArray> broken_;
9331 Database *database_;
9333 _H<NSURL> starturl_;
9338 _H<StashController> stash_;
9347 @implementation Cydia
9349 - (void) lockSuspend {
9350 if (locked_++ == 0) {
9351 if ($SBSSetInterceptsMenuButtonForever != NULL)
9352 (*$SBSSetInterceptsMenuButtonForever)(true);
9356 - (void) unlockSuspend {
9357 if (--locked_ == 0) {
9358 if ($SBSSetInterceptsMenuButtonForever != NULL)
9359 (*$SBSSetInterceptsMenuButtonForever)(false);
9363 - (void) beginUpdate {
9364 [tabbar_ beginUpdate];
9368 return [tabbar_ updating];
9372 if ([broken_ count] != 0) {
9373 int count = [broken_ count];
9375 UIAlertView *alert = [[[UIAlertView alloc]
9376 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9377 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9379 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9381 UCLocalize("TEMPORARY_IGNORE"),
9385 [alert setContext:@"fixhalf"];
9386 [alert setNumberOfRows:2];
9388 } else if (!Ignored_ && [essential_ count] != 0) {
9389 int count = [essential_ count];
9391 UIAlertView *alert = [[[UIAlertView alloc]
9392 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9393 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9395 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9397 UCLocalize("UPGRADE_ESSENTIAL"),
9398 UCLocalize("COMPLETE_UPGRADE"),
9402 [alert setContext:@"upgrade"];
9407 - (void) returnToCydia {
9411 - (void) _saveConfig {
9412 @synchronized (database_) {
9419 NSString *error(nil);
9421 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9423 NSError *error(nil);
9424 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9425 NSLog(@"failure to save metadata data: %@", error);
9430 NSLog(@"failure to serialize metadata: %@", error);
9434 CydiaWriteSources();
9437 // Navigation controller for the queuing badge.
9438 - (UINavigationController *) queueNavigationController {
9439 NSArray *controllers = [tabbar_ viewControllers];
9440 return [controllers objectAtIndex:3];
9443 - (void) unloadData {
9444 [tabbar_ unloadData];
9447 - (void) _updateData {
9451 UINavigationController *navigation = [self queueNavigationController];
9453 id queuedelegate = nil;
9454 if ([[navigation viewControllers] count] > 0)
9455 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9457 [queuedelegate queueStatusDidChange];
9458 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9461 - (void) _refreshIfPossible:(NSDate *)update {
9462 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9464 bool recently = false;
9465 if (update != nil) {
9466 NSTimeInterval interval([update timeIntervalSinceNow]);
9467 if (interval <= 0 && interval > -(15*60))
9471 // Don't automatic refresh if:
9472 // - We already refreshed recently.
9473 // - We already auto-refreshed this launch.
9474 // - Auto-refresh is disabled.
9475 // - Cydia's server is not reachable
9476 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9477 // If we are cancelling, we need to make sure it knows it's already loaded.
9480 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9482 // We are going to load, so remember that.
9485 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9491 - (void) refreshIfPossible {
9492 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9495 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9496 @synchronized (self) {
9497 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9498 [hud setText:UCLocalize("RELOADING_DATA")];
9500 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9504 [essential_ removeAllObjects];
9505 [broken_ removeAllObjects];
9507 NSArray *packages([database_ packages]);
9508 for (Package *package in packages) {
9510 [broken_ addObject:package];
9511 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9512 if ([package essential] && [package installed] != nil)
9513 [essential_ addObject:package];
9518 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9521 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9522 [changesItem setBadgeValue:badge];
9523 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9524 [self setApplicationIconBadgeNumber:changes];
9527 [changesItem setBadgeValue:nil];
9528 [changesItem setAnimatedBadge:NO];
9529 [self setApplicationIconBadgeNumber:0];
9535 [self removeProgressHUD:hud];
9538 - (void) updateData {
9542 - (void) updateDataAndLoad {
9544 if ([database_ progressDelegate] == nil)
9550 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9553 - (void) disemulate {
9554 if (emulated_ == nil)
9557 [window_ addSubview:[tabbar_ view]];
9558 [[emulated_ view] removeFromSuperview];
9560 [window_ setUserInteractionEnabled:YES];
9563 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9564 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9566 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9568 UIViewController *parent;
9569 if (emulated_ == nil)
9578 [parent presentModalViewController:navigation animated:YES];
9581 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9582 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9584 if (navigation != nil)
9585 [navigation pushViewController:progress animated:YES];
9587 [self presentModalViewController:progress force:YES];
9589 [progress invoke:invocation withTitle:title];
9593 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9594 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9597 - (void) repairWithInvocation:(NSInvocation *)invocation {
9599 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9603 - (void) repairWithSelector:(SEL)selector {
9604 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9607 - (void) reloadData {
9608 [self reloadDataWithInvocation:nil];
9609 if ([database_ progressDelegate] == nil)
9615 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9618 - (void) addSource:(NSDictionary *) source {
9619 CydiaAddSource(source);
9622 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9623 CydiaAddSource(href, distribution, sections);
9626 - (void) addTrivialSource:(NSString *)href {
9627 CydiaAddSource(href, @"./");
9630 - (void) updateValues {
9635 pkgProblemResolver *resolver = [database_ resolver];
9637 resolver->InstallProtect();
9638 if (!resolver->Resolve(true))
9643 // XXX: this is a really crappy way of doing this.
9644 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9645 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9646 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9647 if ([tabbar_ updating])
9648 [tabbar_ cancelUpdate];
9650 if (![database_ prepare])
9653 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9654 [page setDelegate:self];
9655 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9658 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9659 [tabbar_ presentModalViewController:confirm_ animated:YES];
9665 @synchronized (self) {
9670 - (void) clearPackage:(Package *)package {
9671 @synchronized (self) {
9678 - (void) installPackages:(NSArray *)packages {
9679 @synchronized (self) {
9680 for (Package *package in packages)
9687 - (void) installPackage:(Package *)package {
9688 @synchronized (self) {
9695 - (void) removePackage:(Package *)package {
9696 @synchronized (self) {
9703 - (void) distUpgrade {
9704 @synchronized (self) {
9705 if (![database_ upgrade])
9713 system("su -c /usr/bin/uicache mobile");
9718 UIProgressHUD *hud([self addProgressHUD]);
9719 [hud setText:UCLocalize("LOADING")];
9720 [self yieldToSelector:@selector(_uicache)];
9721 [self removeProgressHUD:hud];
9725 [database_ perform];
9726 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9727 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9730 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9733 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9734 [self unlockSuspend];
9737 - (void) showSettings {
9738 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9741 - (void) retainNetworkActivityIndicator {
9742 if (activity_++ == 0)
9743 [self setNetworkActivityIndicatorVisible:YES];
9746 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9750 - (void) releaseNetworkActivityIndicator {
9751 if (--activity_ == 0)
9752 [self setNetworkActivityIndicatorVisible:NO];
9755 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9760 - (void) cancelAndClear:(bool)clear {
9761 @synchronized (self) {
9773 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9774 NSString *context([alert context]);
9776 if ([context isEqualToString:@"conffile"]) {
9777 FILE *input = [database_ input];
9778 if (button == [alert cancelButtonIndex])
9779 fprintf(input, "N\n");
9780 else if (button == [alert firstOtherButtonIndex])
9781 fprintf(input, "Y\n");
9784 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9785 } else if ([context isEqualToString:@"fixhalf"]) {
9786 if (button == [alert cancelButtonIndex]) {
9787 @synchronized (self) {
9788 for (Package *broken in (id) broken_) {
9791 NSString *id = [broken id];
9792 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9793 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9794 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9795 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9801 } else if (button == [alert firstOtherButtonIndex]) {
9802 [broken_ removeAllObjects];
9806 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9807 } else if ([context isEqualToString:@"upgrade"]) {
9808 if (button == [alert firstOtherButtonIndex]) {
9809 @synchronized (self) {
9810 for (Package *essential in (id) essential_)
9811 [essential install];
9816 } else if (button == [alert firstOtherButtonIndex] + 1) {
9818 } else if (button == [alert cancelButtonIndex]) {
9822 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9826 - (void) system:(NSString *)command {
9827 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9830 system([command UTF8String]);
9836 - (void) applicationWillSuspend {
9838 [super applicationWillSuspend];
9841 - (BOOL) isSafeToSuspend {
9844 NSLog(@"isSafeToSuspend: locked_ != 0");
9849 // Use external process status API internally.
9850 // This is probably a really bad idea.
9851 // XXX: what is the point of this? does this solve anything at all?
9852 uint64_t status = 0;
9854 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9855 notify_get_state(notify_token, &status);
9856 notify_cancel(notify_token);
9861 NSLog(@"isSafeToSuspend: status != 0");
9867 NSLog(@"isSafeToSuspend: -> true");
9872 - (void) applicationSuspend:(__GSEvent *)event {
9873 if ([self isSafeToSuspend])
9874 [super applicationSuspend:event];
9877 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9878 if ([self isSafeToSuspend])
9879 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9882 - (void) _setSuspended:(BOOL)value {
9883 if ([self isSafeToSuspend])
9884 [super _setSuspended:value];
9887 - (UIProgressHUD *) addProgressHUD {
9888 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9889 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9891 [window_ setUserInteractionEnabled:NO];
9893 UIViewController *target(tabbar_);
9894 if (UIViewController *modal = [target modalViewController])
9897 [hud showInView:[target view]];
9903 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9904 [self unlockSuspend];
9906 [hud removeFromSuperview];
9907 [window_ setUserInteractionEnabled:YES];
9910 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9911 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9914 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9915 NSString *scheme([[url scheme] lowercaseString]);
9916 if ([[url absoluteString] length] <= [scheme length] + 3)
9918 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9919 NSArray *components([path componentsSeparatedByString:@"/"]);
9921 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9922 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9923 if (controller != nil)
9924 [controller setDelegate:self];
9928 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9931 NSString *base([components objectAtIndex:0]);
9933 CyteViewController *controller = nil;
9935 if ([base isEqualToString:@"url"]) {
9936 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9937 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9938 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9939 } else if (!external && [components count] == 1) {
9940 if ([base isEqualToString:@"manage"]) {
9941 controller = [[[ManageController alloc] init] autorelease];
9944 if ([base isEqualToString:@"storage"]) {
9945 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9948 if ([base isEqualToString:@"sources"]) {
9949 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9952 if ([base isEqualToString:@"home"]) {
9953 controller = [[[HomeController alloc] init] autorelease];
9956 if ([base isEqualToString:@"sections"]) {
9957 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9960 if ([base isEqualToString:@"search"]) {
9961 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9964 if ([base isEqualToString:@"changes"]) {
9965 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9968 if ([base isEqualToString:@"installed"]) {
9969 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9971 } else if ([components count] == 2) {
9972 NSString *argument = [components objectAtIndex:1];
9974 if ([base isEqualToString:@"package"]) {
9975 controller = [self pageForPackage:argument withReferrer:referrer];
9978 if (!external && [base isEqualToString:@"search"]) {
9979 controller = [[[SearchController alloc] initWithDatabase:database_ query:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9982 if (!external && [base isEqualToString:@"sections"]) {
9983 if ([argument isEqualToString:@"all"])
9985 controller = [[[SectionController alloc] initWithDatabase:database_ section:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9988 if (!external && [base isEqualToString:@"sources"]) {
9989 if ([argument isEqualToString:@"add"]) {
9990 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9991 [(SourcesController *)controller showAddSourcePrompt];
9993 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9994 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9998 if (!external && [base isEqualToString:@"launch"]) {
9999 [self launchApplicationWithIdentifier:argument suspended:NO];
10002 } else if (!external && [components count] == 3) {
10003 NSString *arg1 = [components objectAtIndex:1];
10004 NSString *arg2 = [components objectAtIndex:2];
10006 if ([base isEqualToString:@"package"]) {
10007 if ([arg2 isEqualToString:@"settings"]) {
10008 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
10009 } else if ([arg2 isEqualToString:@"files"]) {
10010 if (Package *package = [database_ packageWithName:arg1]) {
10011 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
10012 [(FileTable *)controller setPackage:package];
10018 [controller setDelegate:self];
10022 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
10023 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
10026 [tabbar_ setUnselectedViewController:page];
10028 return page != nil;
10031 - (void) applicationOpenURL:(NSURL *)url {
10032 [super applicationOpenURL:url];
10037 [self openCydiaURL:url forExternal:YES];
10040 - (void) applicationWillResignActive:(UIApplication *)application {
10041 // Stop refreshing if you get a phone call or lock the device.
10042 if ([tabbar_ updating])
10043 [tabbar_ cancelUpdate];
10045 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
10046 [super applicationWillResignActive:application];
10049 - (void) saveState {
10050 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
10051 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
10052 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
10055 [self _saveConfig];
10058 - (void) applicationWillTerminate:(UIApplication *)application {
10062 - (void) setConfigurationData:(NSString *)data {
10063 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
10065 if (!conffile_r(data)) {
10066 lprintf("E:invalid conffile\n");
10070 NSString *ofile = conffile_r[1];
10071 //NSString *nfile = conffile_r[2];
10073 UIAlertView *alert = [[[UIAlertView alloc]
10074 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
10075 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
10077 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
10079 UCLocalize("ACCEPT_NEW_COPY"),
10080 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
10084 [alert setContext:@"conffile"];
10085 [alert setNumberOfRows:2];
10089 - (void) addStashController {
10090 [self lockSuspend];
10091 stash_ = [[[StashController alloc] init] autorelease];
10092 [window_ addSubview:[stash_ view]];
10095 - (void) removeStashController {
10096 [[stash_ view] removeFromSuperview];
10098 [self unlockSuspend];
10102 [self setIdleTimerDisabled:YES];
10104 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
10105 UpdateExternalStatus(1);
10106 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
10107 UpdateExternalStatus(0);
10109 [self removeStashController];
10111 pid_t pid(ExecFork());
10113 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
10114 perror("launchctl stop");
10121 - (void) setupViewControllers {
10122 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
10124 NSMutableArray *items([NSMutableArray arrayWithObjects:
10125 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
10126 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
10127 [[[UITabBarItem alloc] initWithTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES")) image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
10128 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
10132 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
10133 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10135 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10138 NSMutableArray *controllers([NSMutableArray array]);
10139 for (UITabBarItem *item in items) {
10140 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
10141 [controller setTabBarItem:item];
10142 [controllers addObject:controller];
10144 [tabbar_ setViewControllers:controllers];
10146 [tabbar_ setUpdateDelegate:self];
10149 - (void) _sendMemoryWarningNotification {
10150 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
10151 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
10153 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
10156 - (void) _sendMemoryWarningNotifications {
10158 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
10164 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
10166 [[NSURLCache sharedURLCache] removeAllCachedResponses];
10169 - (void) applicationDidFinishLaunching:(id)unused {
10170 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
10173 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
10174 [self setApplicationSupportsShakeToEdit:NO];
10176 @synchronized (HostConfig_) {
10177 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
10180 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
10181 initWithMemoryCapacity:524288
10182 diskCapacity:10485760
10183 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
10186 [CydiaWebViewController _initialize];
10188 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
10190 // this would disallow http{,s} URLs from accessing this data
10191 //[WebView registerURLSchemeAsLocal:@"cydia"];
10193 Font12_ = [UIFont systemFontOfSize:12];
10194 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
10195 Font14_ = [UIFont systemFontOfSize:14];
10196 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
10197 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
10199 essential_ = [NSMutableArray arrayWithCapacity:4];
10200 broken_ = [NSMutableArray arrayWithCapacity:4];
10202 // XXX: I really need this thing... like, seriously... I'm sorry
10203 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
10205 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
10206 [window_ orderFront:self];
10207 [window_ makeKey:self];
10208 [window_ setHidden:NO];
10210 if (false) stash: {
10211 [self addStashController];
10212 // XXX: this would be much cleaner as a yieldToSelector:
10213 // that way the removeStashController could happen right here inline
10214 // we also could no longer require the useless stash_ field anymore
10215 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
10220 int error(stat("/", &root));
10221 _assert(error != -1);
10223 #define Stash_(path) do { \
10224 struct stat folder; \
10225 int error(lstat((path), &folder)); \
10226 if (error != -1 && ( \
10227 folder.st_dev == root.st_dev && \
10228 S_ISDIR(folder.st_mode) \
10229 ) || error == -1 && ( \
10230 errno == ENOENT || \
10235 Stash_("/Applications");
10236 Stash_("/Library/Ringtones");
10237 Stash_("/Library/Wallpaper");
10238 //Stash_("/usr/bin");
10239 Stash_("/usr/include");
10240 Stash_("/usr/lib/pam");
10241 Stash_("/usr/libexec");
10242 Stash_("/usr/share");
10243 //Stash_("/var/lib");
10245 database_ = [Database sharedInstance];
10246 [database_ setDelegate:self];
10248 [window_ setUserInteractionEnabled:NO];
10249 [self setupViewControllers];
10251 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
10252 [window_ addSubview:[emulated_ view]];
10254 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
10258 - (NSArray *) defaultStartPages {
10259 NSMutableArray *standard = [NSMutableArray array];
10260 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
10261 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
10262 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
10264 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
10266 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
10267 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
10269 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10273 - (void) loadData {
10275 if (Role_ == nil) {
10276 [window_ setUserInteractionEnabled:YES];
10277 [self showSettings];
10280 if ([emulated_ modalViewController] != nil)
10281 [emulated_ dismissModalViewControllerAnimated:YES];
10282 [window_ setUserInteractionEnabled:NO];
10285 [self reloadDataWithInvocation:nil];
10286 [self refreshIfPossible];
10291 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
10292 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
10293 int standardIndex = 0;
10294 NSArray *standard = [self defaultStartPages];
10301 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
10302 if (valid && closed != nil) {
10303 NSTimeInterval interval([closed timeIntervalSinceNow]);
10304 // XXX: Is 30 minutes the optimal time here?
10305 if (interval <= -(30*60))
10309 if (valid && [saved count] != [standard count])
10313 for (unsigned int i = 0; i < [standard count]; i++) {
10314 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10315 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10316 // but it's good enough for now.
10317 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10324 NSArray *items = nil;
10326 [tabbar_ setSelectedIndex:savedIndex];
10329 [tabbar_ setSelectedIndex:standardIndex];
10333 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10334 NSArray *stack = [items objectAtIndex:tab];
10335 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10336 NSMutableArray *current = [NSMutableArray array];
10338 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10339 NSString *addr = [stack objectAtIndex:nav];
10340 NSURL *url = [NSURL URLWithString:addr];
10341 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10343 [current addObject:page];
10346 [navigation setViewControllers:current];
10349 // (Try to) show the startup URL.
10350 if (starturl_ != nil) {
10351 [self openCydiaURL:starturl_ forExternal:NO];
10356 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10357 if (item != nil && IsWildcat_) {
10358 [sheet showFromBarButtonItem:item animated:YES];
10360 [sheet showInView:window_];
10364 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10365 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10366 [progress setTitle:task];
10367 [progress addProgressEvent:event];
10370 - (void) addProgressEventForTask:(NSArray *)data {
10371 CydiaProgressEvent *event([data objectAtIndex:0]);
10372 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10373 [self addProgressEvent:event forTask:task];
10376 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10377 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10383 id Alloc_(id self, SEL selector) {
10384 id object = alloc_(self, selector);
10385 lprintf("[%s]A-%p\n", self->isa->name, object);
10390 id Dealloc_(id self, SEL selector) {
10391 id object = dealloc_(self, selector);
10392 lprintf("[%s]D-%p\n", self->isa->name, object);
10396 static NSSet *MobilizedFiles_;
10398 static NSURL *MobilizeURL(NSURL *url) {
10399 NSString *path([url path]);
10400 if ([path hasPrefix:@"/var/root/"]) {
10401 NSString *file([path substringFromIndex:10]);
10402 if ([MobilizedFiles_ containsObject:file])
10403 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10409 Class $CFXPreferencesPropertyListSource;
10410 @class CFXPreferencesPropertyListSource;
10412 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10413 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10414 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10415 url = MobilizeURL(url);
10416 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10417 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10423 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10424 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10425 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10426 url = MobilizeURL(url);
10427 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10428 //NSLog(@"%@ %@", [url absoluteString], value);
10434 Class $NSURLConnection;
10436 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10437 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10439 NSURL *url([copy URL]);
10441 NSString *host([url host]);
10442 NSString *scheme([[url scheme] lowercaseString]);
10444 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10446 @synchronized (HostConfig_) {
10447 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10448 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10449 [copy setHTTPShouldUsePipelining:YES];
10451 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10452 if ([control isEqualToString:@"max-age=0"])
10453 if ([CachedURLs_ containsObject:url]) {
10455 NSLog(@"~~~: %@", url);
10458 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10460 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10461 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10462 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10466 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10472 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10473 CGSize size([[UIScreen mainScreen] bounds].size);
10474 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10475 if ([$WAKWindow hasLandscapeOrientation])
10476 std::swap(size.width, size.height);*/
10480 int main(int argc, char *argv[]) {
10481 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10485 UpdateExternalStatus(0);
10487 if (Class $UIDevice = objc_getClass("UIDevice")) {
10488 UIDevice *device([$UIDevice currentDevice]);
10489 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10491 IsWildcat_ = false;
10493 UIScreen *screen([UIScreen mainScreen]);
10494 if ([screen respondsToSelector:@selector(scale)])
10495 ScreenScale_ = [screen scale];
10499 UIDevice *device([UIDevice currentDevice]);
10500 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10501 Idiom_ = @"iphone";
10503 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10504 if (idiom == UIUserInterfaceIdiomPhone)
10505 Idiom_ = @"iphone";
10506 else if (idiom == UIUserInterfaceIdiomPad)
10509 NSLog(@"unknown UIUserInterfaceIdiom!");
10512 Pcre pattern("^([0-9]+\\.[0-9]+)");
10514 if (pattern([device systemVersion]))
10515 Firmware_ = pattern[1];
10516 if (pattern(Cydia_))
10517 Major_ = pattern[1];
10519 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10521 HostConfig_ = [[[NSObject alloc] init] autorelease];
10522 @synchronized (HostConfig_) {
10523 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10524 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10525 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10526 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10527 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10530 NSString *ui(@"ui/ios");
10532 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10533 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10534 UI_ = CydiaURL(ui);
10536 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10538 MobilizedFiles_ = [NSMutableSet setWithObjects:
10539 @"Library/Preferences/com.apple.Accessibility.plist",
10540 @"Library/Preferences/com.apple.preferences.sounds.plist",
10543 /* Library Hacks {{{ */
10544 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10546 $WAKWindow = objc_getClass("WAKWindow");
10547 if ($WAKWindow != NULL)
10548 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10549 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10551 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10553 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10554 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10555 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10556 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10559 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10560 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10561 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10562 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10565 $NSURLConnection = objc_getClass("NSURLConnection");
10566 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10567 if (NSURLConnection$init$ != NULL) {
10568 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10569 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10572 /* Set Locale {{{ */
10573 Locale_ = CFLocaleCopyCurrent();
10574 Languages_ = [NSLocale preferredLanguages];
10576 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10577 //NSLog(@"%@", [Languages_ description]);
10580 if (Locale_ != NULL)
10581 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10582 else if (Languages_ != nil && [Languages_ count] != 0)
10583 lang = [[Languages_ objectAtIndex:0] UTF8String];
10585 // XXX: consider just setting to C and then falling through?
10588 if (lang != NULL) {
10589 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10590 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10593 NSLog(@"Setting Language: %s", lang);
10595 if (lang != NULL) {
10596 setenv("LANG", lang, true);
10597 std::setlocale(LC_ALL, lang);
10601 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10603 /* Parse Arguments {{{ */
10604 bool substrate(false);
10610 for (int argi(1); argi != argc; ++argi)
10611 if (strcmp(argv[argi], "--") == 0) {
10613 argv[argi] = argv[0];
10619 for (int argi(1); argi != arge; ++argi)
10620 if (strcmp(args[argi], "--substrate") == 0)
10623 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10627 App_ = [[NSBundle mainBundle] bundlePath];
10633 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10634 alloc_ = alloc->method_imp;
10635 alloc->method_imp = (IMP) &Alloc_;*/
10637 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10638 dealloc_ = dealloc->method_imp;
10639 dealloc->method_imp = (IMP) &Dealloc_;*/
10641 /* System Information {{{ */
10645 size = sizeof(maxproc);
10646 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10647 perror("sysctlbyname(\"kern.maxproc\", ?)");
10648 else if (maxproc < 64) {
10650 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10651 perror("sysctlbyname(\"kern.maxproc\", #)");
10654 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10655 char *osversion = new char[size];
10656 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10657 perror("sysctlbyname(\"kern.osversion\", ?)");
10659 System_ = [NSString stringWithUTF8String:osversion];
10661 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10662 char *machine = new char[size];
10663 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10664 perror("sysctlbyname(\"hw.machine\", ?)");
10666 Machine_ = machine;
10668 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10669 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10670 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10672 UniqueID_ = [device uniqueIdentifier];
10674 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10675 Product_ = [info objectForKey:@"SafariProductVersion"];
10676 Safari_ = [info objectForKey:@"CFBundleVersion"];
10679 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10681 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10682 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10683 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10684 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10685 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10686 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10688 UserAgent_ = agent;
10690 /* Load Database {{{ */
10692 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10694 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10696 if (Metadata_ == NULL)
10697 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10699 Settings_ = [Metadata_ objectForKey:@"Settings"];
10701 Packages_ = [Metadata_ objectForKey:@"Packages"];
10703 Values_ = [Metadata_ objectForKey:@"Values"];
10704 Sections_ = [Metadata_ objectForKey:@"Sections"];
10705 Sources_ = [Metadata_ objectForKey:@"Sources"];
10707 Token_ = [Metadata_ objectForKey:@"Token"];
10709 Version_ = [Metadata_ objectForKey:@"Version"];
10712 if (Settings_ != nil)
10713 Role_ = [Settings_ objectForKey:@"Role"];
10715 if (Values_ == nil) {
10716 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10717 [Metadata_ setObject:Values_ forKey:@"Values"];
10720 if (Sections_ == nil) {
10721 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10722 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10725 if (Sources_ == nil) {
10726 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10727 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10730 if (Version_ == nil) {
10731 Version_ = [NSNumber numberWithUnsignedInt:0];
10732 [Metadata_ setObject:Version_ forKey:@"Version"];
10735 if ([Version_ unsignedIntValue] == 0) {
10736 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10737 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10738 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10739 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10741 Version_ = [NSNumber numberWithUnsignedInt:1];
10742 [Metadata_ setObject:Version_ forKey:@"Version"];
10744 [Metadata_ removeObjectForKey:@"LastUpdate"];
10750 CydiaWriteSources();
10753 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10756 if (Packages_ != nil) {
10758 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10762 [Metadata_ removeObjectForKey:@"Packages"];
10768 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10770 #define MobileSubstrate_(name) \
10771 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10772 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10773 if (handle == NULL) \
10774 NSLog(@"%s", dlerror()); \
10777 MobileSubstrate_(Activator)
10778 MobileSubstrate_(libstatusbar)
10779 MobileSubstrate_(SimulatedKeyEvents)
10780 MobileSubstrate_(WinterBoard)
10782 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10783 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10785 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10787 if (access("/User", F_OK) != 0 || version != 5) {
10789 system("/usr/libexec/cydia/firmware.sh");
10793 _assert([[NSFileManager defaultManager]
10794 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10795 withIntermediateDirectories:YES
10800 if (access("/tmp/cydia.chk", F_OK) == 0) {
10801 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10802 _assert(errno == ENOENT);
10803 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10804 _assert(errno == ENOENT);
10807 /* APT Initialization {{{ */
10808 _assert(pkgInitConfig(*_config));
10809 _assert(pkgInitSystem(*_config, _system));
10812 _config->Set("APT::Acquire::Translation", lang);
10814 // XXX: this timeout might be important :(
10815 //_config->Set("Acquire::http::Timeout", 15);
10817 _config->Set("Acquire::http::MaxParallel", 3);
10819 /* Color Choices {{{ */
10820 space_ = CGColorSpaceCreateDeviceRGB();
10822 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10823 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10824 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10825 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10826 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10827 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10828 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10829 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10830 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10832 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10833 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10835 /* UIKit Configuration {{{ */
10836 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10837 if ($GSFontSetUseLegacyFontMetrics != NULL)
10838 $GSFontSetUseLegacyFontMetrics(YES);
10840 // XXX: I have a feeling this was important
10841 //UIKeyboardDisableAutomaticAppearance();
10844 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10846 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemHasCapability"));
10847 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10849 ShowPromoted_ = fast;
10850 PulseInterval_ = fast ? 50000 : 500000;
10852 Colon_ = UCLocalize("COLON_DELIMITED");
10853 Elision_ = UCLocalize("ELISION");
10854 Error_ = UCLocalize("ERROR");
10855 Warning_ = UCLocalize("WARNING");
10858 AprilFools_ = true;
10860 CFGregorianDate date(CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem()));
10861 AprilFools_ = date.month == 4 && date.day == 1;
10865 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10867 CGColorSpaceRelease(space_);
10868 CFRelease(Locale_);