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 goto tag; for (; !tag.end(); ++tag) tag: {
2326 const char *name(tag.Name());
2327 NSString *string((NSString *) CYStringCreate(name));
2331 [tags_ addObject:[string autorelease]];
2333 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2334 if (strcmp(name + 6, "enduser") == 0)
2336 else if (strcmp(name + 6, "hacker") == 0)
2338 else if (strcmp(name + 6, "developer") == 0)
2340 else if (strcmp(name + 6, "cydia") == 0)
2346 if (strncmp(name, "cydia::", 7) == 0) {
2347 if (strcmp(name + 7, "essential") == 0)
2349 else if (strcmp(name + 7, "obsolete") == 0)
2356 _profile(Package$initWithVersion$Metadata)
2357 const char *mixed(iterator.Name());
2358 size_t size(strlen(mixed));
2359 char lower[size + 1];
2361 for (size_t i(0); i != size; ++i)
2362 lower[i] = mixed[i] | 0x20;
2365 PackageValue *metadata(PackageFind(lower, size));
2366 metadata_ = metadata;
2368 id_.set(NULL, metadata->name_, size);
2370 const char *latest(version_.VerStr());
2371 size_t length(strlen(latest));
2373 uint16_t vhash(hashlittle(latest, length));
2375 size_t capped(std::min<size_t>(8, length));
2376 latest = latest + length - capped;
2378 if (metadata->first_ == 0)
2379 metadata->first_ = now_;
2381 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2382 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2383 metadata->vhash_ = vhash;
2384 metadata->last_ = now_;
2385 } else if (metadata->last_ == 0)
2386 metadata->last_ = metadata->first_;
2389 _profile(Package$initWithVersion$Section)
2390 section_ = version_.Section();
2393 _profile(Package$initWithVersion$Flags)
2394 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2395 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2400 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2401 pkgCache::VerIterator version;
2403 _profile(Package$packageWithIterator$GetCandidateVer)
2404 version = [database policy]->GetCandidateVer(iterator);
2412 _profile(Package$packageWithIterator$Allocate)
2413 package = [Package allocWithZone:zone];
2416 _profile(Package$packageWithIterator$Initialize)
2418 initWithVersion:version
2425 _profile(Package$packageWithIterator$Autorelease)
2426 package = [package autorelease];
2432 - (pkgCache::PkgIterator) iterator {
2436 - (NSString *) section {
2437 if (section$_ == nil) {
2438 if (section_ == NULL)
2441 _profile(Package$section$mappedSectionForPointer)
2442 section$_ = [database_ mappedSectionForPointer:section_];
2447 - (NSString *) simpleSection {
2448 if (NSString *section = [self section])
2449 return Simplify(section);
2454 - (NSString *) longSection {
2455 return LocalizeSection([self section]);
2458 - (NSString *) shortSection {
2459 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2462 - (NSString *) uri {
2465 pkgIndexFile *index;
2466 pkgCache::PkgFileIterator file(file_.File());
2467 if (![database_ list].FindIndex(file, index))
2469 return [NSString stringWithUTF8String:iterator_->Path];
2470 //return [NSString stringWithUTF8String:file.Site()];
2471 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2475 - (MIMEAddress *) maintainer {
2476 @synchronized (database_) {
2477 if ([database_ era] != era_ || file_.end())
2480 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2481 const std::string &maintainer(parser->Maintainer());
2482 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2485 - (NSString *) md5sum {
2486 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2490 @synchronized (database_) {
2491 if ([database_ era] != era_ || version_.end())
2494 return version_->InstalledSize;
2497 - (NSString *) longDescription {
2498 @synchronized (database_) {
2499 if ([database_ era] != era_ || file_.end())
2502 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2503 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2505 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2506 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2507 if ([lines count] < 2)
2510 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2511 for (size_t i(1), e([lines count]); i != e; ++i) {
2512 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2513 [trimmed addObject:trim];
2516 return [trimmed componentsJoinedByString:@"\n"];
2519 - (NSString *) shortDescription {
2520 if (parsed_ != NULL)
2521 return static_cast<NSString *>(parsed_->tagline_);
2523 @synchronized (database_) {
2524 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2526 const char *start, *end;
2527 if (!parser.ShortDesc(start, end))
2530 if (end - start > 200)
2534 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2537 while (end != start && end[-1] == '\r')
2541 return [(id) CYStringCreate(start, end - start) autorelease];
2545 _profile(Package$index)
2546 CFStringRef name((CFStringRef) [self name]);
2547 if (CFStringGetLength(name) == 0)
2549 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2550 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2552 return toupper(character);
2556 - (PackageValue *) metadata {
2561 PackageValue *metadata([self metadata]);
2562 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2565 - (bool) subscribed {
2566 return [self metadata]->subscribed_;
2569 - (bool) setSubscribed:(bool)subscribed {
2570 PackageValue *metadata([self metadata]);
2571 if (metadata->subscribed_ == subscribed)
2573 metadata->subscribed_ = subscribed;
2581 - (NSString *) latest {
2585 - (NSString *) installed {
2589 - (BOOL) uninstalled {
2590 return installed_.empty();
2594 return !version_.end();
2597 - (BOOL) upgradableAndEssential:(BOOL)essential {
2598 _profile(Package$upgradableAndEssential)
2599 pkgCache::VerIterator current(iterator_.CurrentVer());
2601 return essential && essential_;
2603 return !version_.end() && version_ != current;
2607 - (BOOL) essential {
2612 return [database_ cache][iterator_].InstBroken();
2615 - (BOOL) unfiltered {
2616 _profile(Package$unfiltered$obsolete)
2617 if (_unlikely(obsolete_))
2621 _profile(Package$unfiltered$hasSupportingRole)
2622 if (_unlikely(![self hasSupportingRole]))
2630 if (![self unfiltered])
2635 _profile(Package$visible$section)
2636 section = [self section];
2639 _profile(Package$visible$isSectionVisible)
2640 if (!isSectionVisible(section))
2648 unsigned char current(iterator_->CurrentState);
2649 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2652 - (BOOL) halfConfigured {
2653 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2656 - (BOOL) halfInstalled {
2657 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2661 @synchronized (database_) {
2662 if ([database_ era] != era_ || iterator_.end())
2665 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2666 return state.Mode != pkgDepCache::ModeKeep;
2669 - (NSString *) mode {
2670 @synchronized (database_) {
2671 if ([database_ era] != era_ || iterator_.end())
2674 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2676 switch (state.Mode) {
2677 case pkgDepCache::ModeDelete:
2678 if ((state.iFlags & pkgDepCache::Purge) != 0)
2682 case pkgDepCache::ModeKeep:
2683 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2684 return @"REINSTALL";
2685 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2689 case pkgDepCache::ModeInstall:
2690 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2691 return @"REINSTALL";
2692 else*/ switch (state.Status) {
2694 return @"DOWNGRADE";
2700 return @"NEW_INSTALL";
2711 - (NSString *) name {
2712 return name_.empty() ? id_ : name_;
2715 - (UIImage *) icon {
2716 NSString *section = [self simpleSection];
2719 if (parsed_ != NULL)
2720 if (NSString *href = parsed_->icon_)
2721 if ([href hasPrefix:@"file:///"])
2722 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2723 if (icon == nil) if (section != nil)
2724 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2725 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2726 if ([dicon hasPrefix:@"file:///"])
2727 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2729 icon = [UIImage applicationImageNamed:@"unknown.png"];
2733 - (NSString *) homepage {
2734 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2737 - (NSString *) depiction {
2738 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2741 - (MIMEAddress *) sponsor {
2742 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2745 - (MIMEAddress *) author {
2746 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2749 - (NSString *) support {
2750 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2753 - (NSArray *) files {
2754 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2755 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2758 fin.open([path UTF8String]);
2763 while (std::getline(fin, line))
2764 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2769 - (NSString *) state {
2770 @synchronized (database_) {
2771 if ([database_ era] != era_ || file_.end())
2774 switch (iterator_->CurrentState) {
2775 case pkgCache::State::NotInstalled:
2776 return @"NotInstalled";
2777 case pkgCache::State::UnPacked:
2779 case pkgCache::State::HalfConfigured:
2780 return @"HalfConfigured";
2781 case pkgCache::State::HalfInstalled:
2782 return @"HalfInstalled";
2783 case pkgCache::State::ConfigFiles:
2784 return @"ConfigFiles";
2785 case pkgCache::State::Installed:
2786 return @"Installed";
2787 case pkgCache::State::TriggersAwaited:
2788 return @"TriggersAwaited";
2789 case pkgCache::State::TriggersPending:
2790 return @"TriggersPending";
2793 return (NSString *) [NSNull null];
2796 - (NSString *) selection {
2797 @synchronized (database_) {
2798 if ([database_ era] != era_ || file_.end())
2801 switch (iterator_->SelectedState) {
2802 case pkgCache::State::Unknown:
2804 case pkgCache::State::Install:
2806 case pkgCache::State::Hold:
2808 case pkgCache::State::DeInstall:
2809 return @"DeInstall";
2810 case pkgCache::State::Purge:
2814 return (NSString *) [NSNull null];
2817 - (NSArray *) warnings {
2818 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2819 const char *name(iterator_.Name());
2821 size_t length(strlen(name));
2822 if (length < 2) invalid:
2823 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2824 else for (size_t i(0); i != length; ++i)
2826 /* XXX: technically this is not allowed */
2827 (name[i] < 'A' || name[i] > 'Z') &&
2828 (name[i] < 'a' || name[i] > 'z') &&
2829 (name[i] < '0' || name[i] > '9') &&
2830 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2833 if (strcmp(name, "cydia") != 0) {
2836 bool _private = false;
2839 bool repository = [[self section] isEqualToString:@"Repositories"];
2841 if (NSArray *files = [self files])
2842 for (NSString *file in files)
2843 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2845 else if (!user && [file isEqualToString:@"/User"])
2847 else if (!_private && [file isEqualToString:@"/private"])
2849 else if (!stash && [file isEqualToString:@"/var/stash"])
2852 /* XXX: this is not sensitive enough. only some folders are valid. */
2853 if (cydia && !repository)
2854 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2856 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2858 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2860 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2863 return [warnings count] == 0 ? nil : warnings;
2866 - (NSArray *) applications {
2867 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2869 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2871 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2872 if (NSArray *files = [self files])
2873 for (NSString *file in files)
2874 if (application_r(file)) {
2875 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2876 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2877 if ([id isEqualToString:me])
2880 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2882 display = application_r[1];
2884 NSString *bundle([file stringByDeletingLastPathComponent]);
2885 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2886 if (icon == nil || [icon length] == 0)
2888 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2890 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2891 [applications addObject:application];
2893 [application addObject:id];
2894 [application addObject:display];
2895 [application addObject:url];
2898 return [applications count] == 0 ? nil : applications;
2901 - (Source *) source {
2902 if (source_ == nil) {
2903 @synchronized (database_) {
2904 if ([database_ era] != era_ || file_.end())
2905 source_ = (Source *) [NSNull null];
2907 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2911 return source_ == (Source *) [NSNull null] ? nil : source_;
2918 - (BOOL) matches:(NSArray *)query {
2919 if (query == nil || [query count] == 0)
2928 string = [self name];
2929 length = [string length];
2931 for (NSString *term in query) {
2932 range = [string rangeOfString:term options:MatchCompareOptions_];
2933 if (range.location != NSNotFound)
2934 rank_ -= 6 * 1000000 / length;
2939 length = [string length];
2941 for (NSString *term in query) {
2942 range = [string rangeOfString:term options:MatchCompareOptions_];
2943 if (range.location != NSNotFound)
2944 rank_ -= 6 * 1000000 / length;
2948 string = [self shortDescription];
2949 length = [string length];
2950 NSUInteger stop(std::min<NSUInteger>(length, 200));
2952 for (NSString *term in query) {
2953 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2954 if (range.location != NSNotFound)
2955 rank_ -= 2 * 100000;
2961 - (bool) hasSupportingRole {
2966 if ([Role_ isEqualToString:@"User"])
2970 if ([Role_ isEqualToString:@"Hacker"])
2974 if ([Role_ isEqualToString:@"Developer"])
2979 - (NSArray *) tags {
2983 - (BOOL) hasTag:(NSString *)tag {
2984 return tags_ == nil ? NO : [tags_ containsObject:tag];
2987 - (NSString *) primaryPurpose {
2988 for (NSString *tag in (NSArray *) tags_)
2989 if ([tag hasPrefix:@"purpose::"])
2990 return [tag substringFromIndex:9];
2994 - (NSArray *) purposes {
2995 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2996 for (NSString *tag in (NSArray *) tags_)
2997 if ([tag hasPrefix:@"purpose::"])
2998 [purposes addObject:[tag substringFromIndex:9]];
2999 return [purposes count] == 0 ? nil : purposes;
3002 - (bool) isCommercial {
3003 return [self hasTag:@"cydia::commercial"];
3006 - (void) setIndex:(size_t)index {
3007 if (metadata_->index_ != index)
3008 metadata_->index_ = index;
3011 - (CYString &) cyname {
3012 return name_.empty() ? id_ : name_;
3015 - (uint32_t) compareBySection:(NSArray *)sections {
3016 NSString *section([self section]);
3017 for (size_t i(0), e([sections count]); i != e; ++i) {
3018 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3022 return _not(uint32_t);
3026 @synchronized (database_) {
3027 pkgProblemResolver *resolver = [database_ resolver];
3028 resolver->Clear(iterator_);
3030 pkgCacheFile &cache([database_ cache]);
3031 cache->SetReInstall(iterator_, false);
3032 cache->MarkKeep(iterator_, false);
3036 @synchronized (database_) {
3037 pkgProblemResolver *resolver = [database_ resolver];
3038 resolver->Clear(iterator_);
3039 resolver->Protect(iterator_);
3041 pkgCacheFile &cache([database_ cache]);
3042 cache->SetReInstall(iterator_, false);
3043 cache->MarkInstall(iterator_, false);
3045 pkgDepCache::StateCache &state((*cache)[iterator_]);
3046 if (!state.Install())
3047 cache->SetReInstall(iterator_, true);
3051 @synchronized (database_) {
3052 pkgProblemResolver *resolver = [database_ resolver];
3053 resolver->Clear(iterator_);
3054 resolver->Remove(iterator_);
3055 resolver->Protect(iterator_);
3057 pkgCacheFile &cache([database_ cache]);
3058 cache->SetReInstall(iterator_, false);
3059 cache->MarkDelete(iterator_, true);
3062 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3063 _profile(Package$isUnfilteredAndSearchedForBy)
3066 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3067 value &= [self unfiltered];
3070 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3071 value &= [self matches:query];
3078 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3079 if ([search length] == 0)
3082 _profile(Package$isUnfilteredAndSelectedForBy)
3085 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3086 value &= [self unfiltered];
3089 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3090 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3097 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3098 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3101 - (bool) isVisibleInSection:(NSString *)name {
3102 NSString *section([self section]);
3106 section == nil && [name length] == 0 ||
3107 [name isEqualToString:section]
3108 ) && [self visible];
3111 - (bool) isVisibleInSource:(Source *)source {
3112 return [self source] == source && [self visible];
3117 /* Section Class {{{ */
3118 @interface Section : NSObject {
3123 _H<NSString> localized_;
3126 - (NSComparisonResult) compareByLocalized:(Section *)section;
3127 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3128 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3129 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3130 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3131 - (NSString *) name;
3138 - (void) addToCount;
3140 - (void) setCount:(size_t)count;
3141 - (NSString *) localized;
3145 @implementation Section
3147 - (NSComparisonResult) compareByLocalized:(Section *)section {
3148 NSString *lhs(localized_);
3149 NSString *rhs([section localized]);
3151 /*if ([lhs length] != 0 && [rhs length] != 0) {
3152 unichar lhc = [lhs characterAtIndex:0];
3153 unichar rhc = [rhs characterAtIndex:0];
3155 if (isalpha(lhc) && !isalpha(rhc))
3156 return NSOrderedAscending;
3157 else if (!isalpha(lhc) && isalpha(rhc))
3158 return NSOrderedDescending;
3161 return [lhs compare:rhs options:LaxCompareOptions_];
3164 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3165 if ((self = [self initWithName:name localize:NO]) != nil) {
3166 if (localized != nil)
3167 localized_ = localized;
3171 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3172 return [self initWithName:name row:0 localize:localize];
3175 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3176 if ((self = [super init]) != nil) {
3181 localized_ = LocalizeSection(name_);
3185 /* XXX: localize the index thingees */
3186 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3187 if ((self = [super init]) != nil) {
3188 name_ = [NSString stringWithCharacters:&index length:1];
3194 - (NSString *) name {
3214 - (void) addToCount {
3218 - (void) setCount:(size_t)count {
3222 - (NSString *) localized {
3229 class CydiaLogCleaner :
3230 public pkgArchiveCleaner
3233 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3238 /* Database Implementation {{{ */
3239 @implementation Database
3241 + (Database *) sharedInstance {
3242 static _H<Database> instance;
3243 if (instance == nil)
3244 instance = [[[Database alloc] init] autorelease];
3252 - (void) releasePackages {
3253 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3254 CFArrayRemoveAllValues(packages_);
3258 // XXX: actually implement this thing
3260 [self releasePackages];
3261 apr_pool_destroy(pool_);
3262 NSRecycleZone(zone_);
3266 - (void) _readCydia:(NSNumber *)fd {
3267 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3268 std::istream is(&ib);
3271 static Pcre finish_r("^finish:([^:]*)$");
3273 while (std::getline(is, line)) {
3274 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3276 const char *data(line.c_str());
3277 size_t size = line.size();
3278 lprintf("C:%s\n", data);
3280 if (finish_r(data, size)) {
3281 NSString *finish = finish_r[1];
3282 int index = [Finishes_ indexOfObject:finish];
3283 if (index != INT_MAX && index > Finish_)
3293 - (void) _readStatus:(NSNumber *)fd {
3294 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3295 std::istream is(&ib);
3298 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3299 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3301 while (std::getline(is, line)) {
3302 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3304 const char *data(line.c_str());
3305 size_t size(line.size());
3306 lprintf("S:%s\n", data);
3308 if (conffile_r(data, size)) {
3309 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3310 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3311 } else if (strncmp(data, "status: ", 8) == 0) {
3312 // status: <package>: {unpacked,half-configured,installed}
3313 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3314 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3315 } else if (strncmp(data, "processing: ", 12) == 0) {
3316 // processing: configure: config-test
3317 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3318 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3319 } else if (pmstatus_r(data, size)) {
3320 std::string type([pmstatus_r[1] UTF8String]);
3322 NSString *package = pmstatus_r[2];
3323 if ([package isEqualToString:@"dpkg-exec"])
3326 float percent([pmstatus_r[3] floatValue]);
3327 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3329 NSString *string = pmstatus_r[4];
3331 if (type == "pmerror") {
3332 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3333 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3334 } else if (type == "pmstatus") {
3335 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3336 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3337 } else if (type == "pmconffile")
3338 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3340 lprintf("E:unknown pmstatus\n");
3342 lprintf("E:unknown status\n");
3350 - (void) _readOutput:(NSNumber *)fd {
3351 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3352 std::istream is(&ib);
3355 while (std::getline(is, line)) {
3356 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3358 lprintf("O:%s\n", line.c_str());
3360 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3361 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3373 - (Package *) packageWithName:(NSString *)name {
3376 @synchronized (self) {
3377 if (static_cast<pkgDepCache *>(cache_) == NULL)
3379 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3380 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3384 if ((self = [super init]) != nil) {
3391 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3392 apr_pool_create(&pool_, NULL);
3394 size_t capacity(MetaFile_->active_);
3400 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3401 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3405 _assert(pipe(fds) != -1);
3408 _config->Set("APT::Keep-Fds::", cydiafd_);
3409 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3412 detachNewThreadSelector:@selector(_readCydia:)
3414 withObject:[NSNumber numberWithInt:fds[0]]
3417 _assert(pipe(fds) != -1);
3421 detachNewThreadSelector:@selector(_readStatus:)
3423 withObject:[NSNumber numberWithInt:fds[0]]
3426 _assert(pipe(fds) != -1);
3427 _assert(dup2(fds[0], 0) != -1);
3428 _assert(close(fds[0]) != -1);
3430 input_ = fdopen(fds[1], "a");
3432 _assert(pipe(fds) != -1);
3433 _assert(dup2(fds[1], 1) != -1);
3434 _assert(close(fds[1]) != -1);
3437 detachNewThreadSelector:@selector(_readOutput:)
3439 withObject:[NSNumber numberWithInt:fds[0]]
3444 - (pkgCacheFile &) cache {
3448 - (pkgDepCache::Policy *) policy {
3452 - (pkgRecords *) records {
3456 - (pkgProblemResolver *) resolver {
3460 - (pkgAcquire &) fetcher {
3464 - (pkgSourceList &) list {
3468 - (NSArray *) packages {
3469 return (NSArray *) packages_;
3472 - (NSArray *) sources {
3476 - (Source *) sourceWithKey:(NSString *)key {
3477 for (Source *source in [self sources]) {
3478 if ([[source key] isEqualToString:key])
3483 - (bool) popErrorWithTitle:(NSString *)title {
3486 while (!_error->empty()) {
3488 bool warning(!_error->PopMessage(error));
3493 size_t size(error.size());
3494 if (size == 0 || error[size - 1] != '\n')
3496 error.resize(size - 1);
3499 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3501 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3502 if (warning && no_pubkey(error.c_str()))
3505 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3511 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3512 return [self popErrorWithTitle:title] || !success;
3515 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3516 @synchronized (self) {
3519 [self releasePackages];
3522 [sourceList_ removeAllObjects];
3542 apr_pool_clear(pool_);
3544 NSRecycleZone(zone_);
3545 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3547 int chk(creat("/tmp/cydia.chk", 0644));
3551 if (invocation != nil)
3552 [invocation invoke];
3554 NSString *title(UCLocalize("DATABASE"));
3556 list_ = new pkgSourceList();
3557 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3560 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3561 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3562 [sourceList_ addObject:object];
3566 OpProgress progress;
3568 if (!cache_.Open(progress, true)) {
3569 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3570 while (!_error->empty()) {
3572 bool warning(!_error->PopMessage(error));
3574 lprintf("cache_.Open():[%s]\n", error.c_str());
3576 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3580 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3581 repair = @selector(configure);
3582 //else if (error == "The package lists or status file could not be parsed or opened.")
3583 // repair = @selector(update);
3584 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3585 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3586 // else if (error == "Malformed Status line")
3587 // else if (error == "The list of sources could not be read.")
3589 if (repair != NULL) {
3591 [delegate_ repairWithSelector:repair];
3600 unlink("/tmp/cydia.chk");
3602 now_ = [[NSDate date] timeIntervalSince1970];
3604 policy_ = new pkgDepCache::Policy();
3605 records_ = new pkgRecords(cache_);
3606 resolver_ = new pkgProblemResolver(cache_);
3607 fetcher_ = new pkgAcquire(&status_);
3610 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3611 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3615 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3618 if (cache_->BrokenCount() != 0) {
3619 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3622 if (cache_->BrokenCount() != 0) {
3623 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3627 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3631 for (Source *object in (id) sourceList_) {
3632 metaIndex *source([object metaIndex]);
3633 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3634 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3635 // XXX: this could be more intelligent
3636 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3637 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3639 sourceMap_[cached->ID] = object;
3644 /*std::vector<Package *> packages;
3645 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3650 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3651 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3652 //packages.push_back(package);
3653 CFArrayAppendValue(packages_, CFRetain(package));
3657 /*if (packages.empty())
3658 packages_ = [[NSArray alloc] init];
3660 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3663 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3664 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3665 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3673 /*if (!packages.empty())
3674 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3675 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3677 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3679 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3681 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3685 size_t count(CFArrayGetCount(packages_));
3686 MetaFile_->active_ = count;
3688 for (size_t index(0); index != count; ++index)
3689 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3696 @synchronized (self) {
3698 resolver_ = new pkgProblemResolver(cache_);
3700 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3701 if (!cache_[iterator].Keep())
3702 cache_->MarkKeep(iterator, false);
3703 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3704 cache_->SetReInstall(iterator, false);
3707 - (void) configure {
3708 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3710 system([dpkg UTF8String]);
3715 @synchronized (self) {
3716 // XXX: I don't remember this condition
3721 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3723 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3725 if ([self popErrorWithTitle:title])
3729 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3731 CydiaLogCleaner cleaner;
3732 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3739 fetcher_->Shutdown();
3741 pkgRecords records(cache_);
3743 lock_ = new FileFd();
3744 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3746 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3748 if ([self popErrorWithTitle:title])
3752 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3755 manager_ = (_system->CreatePM(cache_));
3756 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3763 bool substrate(RestartSubstrate_);
3764 RestartSubstrate_ = false;
3766 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3768 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3770 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3772 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3773 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3776 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3778 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3780 [self popErrorWithTitle:title];
3784 bool failed = false;
3785 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3786 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3788 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3791 std::string uri = (*item)->DescURI();
3792 std::string error = (*item)->ErrorText;
3794 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3797 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3798 [delegate_ addProgressEventOnMainThread:event forTask:title];
3801 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3809 RestartSubstrate_ = true;
3812 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3813 if ([self popErrorWithTitle:title])
3816 if (result == pkgPackageManager::Failed) {
3821 if (result != pkgPackageManager::Completed) {
3826 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3828 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3830 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3831 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3834 if (![before isEqualToArray:after])
3839 NSString *title(UCLocalize("UPGRADE"));
3840 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3846 [self updateWithStatus:status_];
3849 - (void) updateWithStatus:(Status &)status {
3850 NSString *title(UCLocalize("REFRESHING_DATA"));
3853 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3857 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3858 if ([self popErrorWithTitle:title])
3861 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3863 bool success(ListUpdate(status, list, PulseInterval_));
3864 if (status.WasCancelled())
3867 [self popErrorWithTitle:title forOperation:success];
3868 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3872 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3875 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3876 delegate_ = delegate;
3879 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3880 progress_ = delegate;
3881 status_.setDelegate(delegate);
3884 - (NSObject<ProgressDelegate> *) progressDelegate {
3888 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3889 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3890 return i == sourceMap_.end() ? nil : i->second;
3893 - (NSString *) mappedSectionForPointer:(const char *)section {
3894 _H<NSString> *mapped;
3896 _profile(Database$mappedSectionForPointer$Cache)
3897 mapped = §ions_[section];
3900 if (*mapped == NULL) {
3901 size_t length(strlen(section));
3902 char spaced[length + 1];
3904 _profile(Database$mappedSectionForPointer$Replace)
3905 for (size_t index(0); index != length; ++index)
3906 spaced[index] = section[index] == '_' ? ' ' : section[index];
3907 spaced[length] = '\0';
3912 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3913 string = [NSString stringWithUTF8String:spaced];
3916 _profile(Database$mappedSectionForPointer$Map)
3917 string = [SectionMap_ objectForKey:string] ?: string;
3927 static _H<NSMutableSet> Diversions_;
3929 @interface Diversion : NSObject {
3932 _H<NSString> format_;
3937 @implementation Diversion
3939 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3940 if ((self = [super init]) != nil) {
3941 pattern_ = [from UTF8String];
3947 - (NSString *) divert:(NSString *)url {
3948 return !pattern_(url) ? nil : pattern_->*format_;
3951 + (NSURL *) divertURL:(NSURL *)url {
3953 NSString *href([url absoluteString]);
3955 for (Diversion *diversion in (id) Diversions_)
3956 if (NSString *diverted = [diversion divert:href]) {
3958 NSLog(@"div: %@", diverted);
3960 url = [NSURL URLWithString:diverted];
3967 - (NSString *) key {
3971 - (NSUInteger) hash {
3975 - (BOOL) isEqual:(Diversion *)object {
3976 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3981 @interface CydiaObject : NSObject {
3982 _H<CyteWebViewController> indirect_;
3983 _transient id delegate_;
3986 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3992 @interface CydiaWebViewController : CyteWebViewController {
3993 _H<CydiaObject> cydia_;
3996 + (void) addDiversion:(Diversion *)diversion;
3997 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
3998 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
3999 - (void) setDelegate:(id)delegate;
4003 /* Web Scripting {{{ */
4004 @implementation CydiaObject
4006 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4007 if ((self = [super init]) != nil) {
4008 indirect_ = (CyteWebViewController *) indirect;
4012 - (void) setDelegate:(id)delegate {
4013 delegate_ = delegate;
4016 + (NSArray *) _attributeKeys {
4017 return [NSArray arrayWithObjects:
4020 @"coreFoundationVersionNumber",
4037 - (NSArray *) attributeKeys {
4038 return [[self class] _attributeKeys];
4041 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4042 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4045 - (NSString *) version {
4049 - (NSString *) build {
4053 - (NSString *) coreFoundationVersionNumber {
4054 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4057 - (NSString *) device {
4058 return [[UIDevice currentDevice] uniqueIdentifier];
4061 - (NSString *) firmware {
4062 return [[UIDevice currentDevice] systemVersion];
4065 - (NSString *) hostname {
4066 return [[UIDevice currentDevice] name];
4069 - (NSString *) idiom {
4070 return (id) Idiom_ ?: [NSNull null];
4073 - (NSString *) mcc {
4074 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4075 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4079 - (NSString *) mnc {
4080 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4081 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4085 - (NSString *) operator {
4086 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4087 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4091 - (NSString *) bbsnum {
4092 return (id) BBSNum_ ?: [NSNull null];
4095 - (NSString *) ecid {
4096 return (id) ChipID_ ?: [NSNull null];
4099 - (NSString *) serial {
4100 return SerialNumber_;
4103 - (NSString *) role {
4104 return (id) Role_ ?: [NSNull null];
4107 - (NSString *) model {
4108 return [NSString stringWithUTF8String:Machine_];
4111 - (NSString *) token {
4112 return (id) Token_ ?: [NSNull null];
4115 + (NSString *) webScriptNameForSelector:(SEL)selector {
4117 else if (selector == @selector(addBridgedHost:))
4118 return @"addBridgedHost";
4119 else if (selector == @selector(addInsecureHost:))
4120 return @"addInsecureHost";
4121 else if (selector == @selector(addInternalRedirect::))
4122 return @"addInternalRedirect";
4123 else if (selector == @selector(addPipelinedHost:scheme:))
4124 return @"addPipelinedHost";
4125 else if (selector == @selector(addSource:::))
4126 return @"addSource";
4127 else if (selector == @selector(addTokenHost:))
4128 return @"addTokenHost";
4129 else if (selector == @selector(addTrivialSource:))
4130 return @"addTrivialSource";
4131 else if (selector == @selector(close))
4133 else if (selector == @selector(du:))
4135 else if (selector == @selector(stringWithFormat:arguments:))
4137 else if (selector == @selector(getAllSources))
4138 return @"getAllSourcs";
4139 else if (selector == @selector(getKernelNumber:))
4140 return @"getKernelNumber";
4141 else if (selector == @selector(getKernelString:))
4142 return @"getKernelString";
4143 else if (selector == @selector(getInstalledPackages))
4144 return @"getInstalledPackages";
4145 else if (selector == @selector(getIORegistryEntry::))
4146 return @"getIORegistryEntry";
4147 else if (selector == @selector(getLocaleIdentifier))
4148 return @"getLocaleIdentifier";
4149 else if (selector == @selector(getPreferredLanguages))
4150 return @"getPreferredLanguages";
4151 else if (selector == @selector(getPackageById:))
4152 return @"getPackageById";
4153 else if (selector == @selector(getMetadataKeys))
4154 return @"getMetadataKeys";
4155 else if (selector == @selector(getMetadataValue:))
4156 return @"getMetadataValue";
4157 else if (selector == @selector(getSessionValue:))
4158 return @"getSessionValue";
4159 else if (selector == @selector(installPackages:))
4160 return @"installPackages";
4161 else if (selector == @selector(isReachable:))
4162 return @"isReachable";
4163 else if (selector == @selector(localizedStringForKey:value:table:))
4165 else if (selector == @selector(popViewController:))
4166 return @"popViewController";
4167 else if (selector == @selector(refreshSources))
4168 return @"refreshSources";
4169 else if (selector == @selector(removeButton))
4170 return @"removeButton";
4171 else if (selector == @selector(saveConfig))
4172 return @"saveConfig";
4173 else if (selector == @selector(setMetadataValue::))
4174 return @"setMetadataValue";
4175 else if (selector == @selector(setSessionValue::))
4176 return @"setSessionValue";
4177 else if (selector == @selector(setShowPromoted:))
4178 return @"setShowPromoted";
4179 else if (selector == @selector(substitutePackageNames:))
4180 return @"substitutePackageNames";
4181 else if (selector == @selector(scrollToBottom:))
4182 return @"scrollToBottom";
4183 else if (selector == @selector(setAllowsNavigationAction:))
4184 return @"setAllowsNavigationAction";
4185 else if (selector == @selector(setBadgeValue:))
4186 return @"setBadgeValue";
4187 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4188 return @"setButtonImage";
4189 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4190 return @"setButtonTitle";
4191 else if (selector == @selector(setHidesBackButton:))
4192 return @"setHidesBackButton";
4193 else if (selector == @selector(setHidesNavigationBar:))
4194 return @"setHidesNavigationBar";
4195 else if (selector == @selector(setNavigationBarStyle:))
4196 return @"setNavigationBarStyle";
4197 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4198 return @"setNavigationBarTintColor";
4199 else if (selector == @selector(setPasteboardString:))
4200 return @"setPasteboardString";
4201 else if (selector == @selector(setPasteboardURL:))
4202 return @"setPasteboardURL";
4203 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4204 return @"setScrollAlwaysBounceVertical";
4205 else if (selector == @selector(setScrollIndicatorStyle:))
4206 return @"setScrollIndicatorStyle";
4207 else if (selector == @selector(setToken:))
4209 else if (selector == @selector(setViewportWidth:))
4210 return @"setViewportWidth";
4211 else if (selector == @selector(statfs:))
4213 else if (selector == @selector(supports:))
4215 else if (selector == @selector(unload))
4221 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4222 return [self webScriptNameForSelector:selector] == nil;
4225 - (BOOL) supports:(NSString *)feature {
4226 return [feature isEqualToString:@"window.open"];
4230 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4233 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4234 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4237 - (void) setScrollIndicatorStyle:(NSString *)style {
4238 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4241 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4242 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4245 - (NSNumber *) getKernelNumber:(NSString *)name {
4246 const char *string([name UTF8String]);
4249 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4250 return (id) [NSNull null];
4252 if (size != sizeof(int))
4253 return (id) [NSNull null];
4256 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4257 return (id) [NSNull null];
4259 return [NSNumber numberWithInt:value];
4262 - (NSString *) getKernelString:(NSString *)name {
4263 const char *string([name UTF8String]);
4266 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4267 return (id) [NSNull null];
4269 char value[size + 1];
4270 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4271 return (id) [NSNull null];
4273 // XXX: just in case you request something ludicrous
4276 return [NSString stringWithCString:value];
4279 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4280 NSObject *value(CYIOGetValue([path UTF8String], entry));
4283 if ([value isKindOfClass:[NSData class]])
4284 value = CYHex((NSData *) value);
4289 - (NSArray *) getMetadataKeys {
4290 @synchronized (Values_) {
4291 return [Values_ allKeys];
4294 - (void) _setShowPromoted:(NSNumber *)value {
4295 [Metadata_ setObject:value forKey:@"ShowPromoted"];
4299 - (void) setShowPromoted:(NSNumber *)value {
4300 [self performSelectorOnMainThread:@selector(_setShowPromoted:) withObject:value waitUntilDone:NO];
4303 - (id) getMetadataValue:(NSString *)key {
4304 @synchronized (Values_) {
4305 return [Values_ objectForKey:key];
4308 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4309 @synchronized (Values_) {
4310 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4311 [Values_ removeObjectForKey:key];
4313 [Values_ setObject:value forKey:key];
4315 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4318 - (id) getSessionValue:(NSString *)key {
4319 @synchronized (SessionData_) {
4320 return [SessionData_ objectForKey:key];
4323 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4324 @synchronized (SessionData_) {
4325 if (value == (id) [WebUndefined undefined])
4326 [SessionData_ removeObjectForKey:key];
4328 [SessionData_ setObject:value forKey:key];
4331 - (void) addBridgedHost:(NSString *)host {
4332 @synchronized (HostConfig_) {
4333 [BridgedHosts_ addObject:host];
4336 - (void) addInsecureHost:(NSString *)host {
4337 @synchronized (HostConfig_) {
4338 [InsecureHosts_ addObject:host];
4341 - (void) addTokenHost:(NSString *)host {
4342 @synchronized (HostConfig_) {
4343 [TokenHosts_ addObject:host];
4346 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4347 @synchronized (HostConfig_) {
4348 if (scheme != (id) [WebUndefined undefined])
4349 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4351 [PipelinedHosts_ addObject:host];
4354 - (void) popViewController:(NSNumber *)value {
4355 if (value == (id) [WebUndefined undefined])
4356 value = [NSNumber numberWithBool:YES];
4357 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4360 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4361 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4363 for (NSString *section in sections)
4364 [array addObject:section];
4366 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4369 distribution, @"Distribution",
4371 nil] waitUntilDone:NO];
4374 - (void) addTrivialSource:(NSString *)href {
4375 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4378 - (void) refreshSources {
4379 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4382 - (void) saveConfig {
4383 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4386 - (NSArray *) getAllSources {
4387 return [[Database sharedInstance] sources];
4390 - (NSArray *) getInstalledPackages {
4391 Database *database([Database sharedInstance]);
4392 @synchronized (database) {
4393 NSArray *packages([database packages]);
4394 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4395 for (Package *package in packages)
4396 if (![package uninstalled])
4397 [installed addObject:package];
4401 - (Package *) getPackageById:(NSString *)id {
4402 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4406 return (Package *) [NSNull null];
4409 - (NSString *) getLocaleIdentifier {
4410 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4413 - (NSArray *) getPreferredLanguages {
4417 - (NSArray *) statfs:(NSString *)path {
4420 if (path == nil || statfs([path UTF8String], &stat) == -1)
4423 return [NSArray arrayWithObjects:
4424 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4425 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4426 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4430 - (NSNumber *) du:(NSString *)path {
4431 NSNumber *value(nil);
4434 _assert(pipe(fds) != -1);
4436 pid_t pid(ExecFork());
4438 _assert(dup2(fds[1], 1) != -1);
4439 _assert(close(fds[0]) != -1);
4440 _assert(close(fds[1]) != -1);
4441 /* XXX: this should probably not use du */
4442 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4447 _assert(close(fds[1]) != -1);
4449 if (FILE *du = fdopen(fds[0], "r")) {
4451 while (fgets(line, sizeof(line), du) != NULL) {
4452 size_t length(strlen(line));
4453 while (length != 0 && line[length - 1] == '\n')
4454 line[--length] = '\0';
4455 if (char *tab = strchr(line, '\t')) {
4457 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4462 } else _assert(close(fds[0]));
4470 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4473 - (NSNumber *) isReachable:(NSString *)name {
4474 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4477 - (void) installPackages:(NSArray *)packages {
4478 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4481 - (NSString *) substitutePackageNames:(NSString *)message {
4482 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4483 for (size_t i(0), e([words count]); i != e; ++i) {
4484 NSString *word([words objectAtIndex:i]);
4485 if (Package *package = [[Database sharedInstance] packageWithName:word])
4486 [words replaceObjectAtIndex:i withObject:[package name]];
4489 return [words componentsJoinedByString:@" "];
4492 - (void) removeButton {
4493 [indirect_ removeButton];
4496 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4497 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4500 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4501 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4504 - (void) setBadgeValue:(id)value {
4505 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4508 - (void) setAllowsNavigationAction:(NSString *)value {
4509 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4512 - (void) setHidesBackButton:(NSString *)value {
4513 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4516 - (void) setHidesNavigationBar:(NSString *)value {
4517 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4520 - (void) setNavigationBarStyle:(NSString *)value {
4521 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4524 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4525 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4526 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4527 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4530 - (void) setPasteboardString:(NSString *)value {
4531 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4534 - (void) setPasteboardURL:(NSString *)value {
4535 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4538 - (void) _setToken:(NSString *)token {
4542 [Metadata_ removeObjectForKey:@"Token"];
4544 [Metadata_ setObject:Token_ forKey:@"Token"];
4549 - (void) setToken:(NSString *)token {
4550 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4553 - (void) scrollToBottom:(NSNumber *)animated {
4554 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4557 - (void) setViewportWidth:(float)width {
4558 [indirect_ setViewportWidthOnMainThread:width];
4561 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4562 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4563 unsigned count([arguments count]);
4565 for (unsigned i(0); i != count; ++i)
4566 values[i] = [arguments objectAtIndex:i];
4567 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4570 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4571 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4573 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4575 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4581 @interface NSURL (CydiaSecure)
4584 @implementation NSURL (CydiaSecure)
4586 - (bool) isCydiaSecure {
4587 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4590 @synchronized (HostConfig_) {
4591 if ([InsecureHosts_ containsObject:[self host]])
4600 /* Cydia Browser Controller {{{ */
4601 @implementation CydiaWebViewController
4603 - (NSURL *) navigationURL {
4604 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4607 + (void) _initialize {
4608 [super _initialize];
4610 Diversions_ = [NSMutableSet setWithCapacity:0];
4613 + (void) addDiversion:(Diversion *)diversion {
4614 [Diversions_ addObject:diversion];
4617 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4618 [super webView:view didClearWindowObject:window forFrame:frame];
4619 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4622 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4623 WebDataSource *source([frame dataSource]);
4624 NSURLResponse *response([source response]);
4625 NSURL *url([response URL]);
4626 NSString *scheme([[url scheme] lowercaseString]);
4628 bool bridged(false);
4630 @synchronized (HostConfig_) {
4631 if ([scheme isEqualToString:@"file"])
4633 else if ([scheme isEqualToString:@"https"])
4634 if ([BridgedHosts_ containsObject:[url host]])
4639 [window setValue:cydia forKey:@"cydia"];
4642 - (void) _setupMail:(MFMailComposeViewController *)controller {
4643 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4645 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4646 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4649 - (NSURL *) URLWithURL:(NSURL *)url {
4650 return [Diversion divertURL:url];
4653 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4654 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4657 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4658 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4660 NSURL *url([copy URL]);
4661 NSString *href([url absoluteString]);
4662 NSString *host([url host]);
4664 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4665 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4666 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4667 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4670 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4671 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4673 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4677 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4678 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4679 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4680 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4685 @synchronized (HostConfig_) {
4686 bridged = [BridgedHosts_ containsObject:host];
4687 token = [TokenHosts_ containsObject:host];
4690 if ([url isCydiaSecure]) {
4692 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4693 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4695 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4696 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4703 - (void) setDelegate:(id)delegate {
4704 [super setDelegate:delegate];
4705 [cydia_ setDelegate:delegate];
4708 - (NSString *) applicationNameForUserAgent {
4713 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4714 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4720 @interface AppCacheController : CydiaWebViewController {
4725 @implementation AppCacheController
4727 - (void) didReceiveMemoryWarning {
4728 // XXX: this doesn't work
4731 - (bool) retainsNetworkActivityIndicator {
4739 @interface NSObject (CydiaScript)
4740 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4743 @implementation NSObject (CydiaScript)
4745 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4751 @implementation NSArray (CydiaScript)
4753 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4754 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4755 for (size_t i(0), e([self count]); i != e; ++i)
4756 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4762 @implementation NSDictionary (CydiaScript)
4764 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4765 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4767 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4774 /* Confirmation Controller {{{ */
4775 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4776 if (!iterator.end())
4777 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4778 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4780 pkgCache::PkgIterator package(dep.TargetPkg());
4783 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4790 @protocol ConfirmationControllerDelegate
4791 - (void) cancelAndClear:(bool)clear;
4792 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4796 @interface ConfirmationController : CydiaWebViewController {
4797 _transient Database *database_;
4799 _H<UIAlertView> essential_;
4801 _H<NSDictionary> changes_;
4802 _H<NSMutableArray> issues_;
4803 _H<NSDictionary> sizes_;
4808 - (id) initWithDatabase:(Database *)database;
4812 @implementation ConfirmationController
4816 RestartSubstrate_ = true;
4817 [delegate_ confirmWithNavigationController:[self navigationController]];
4820 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4821 NSString *context([alert context]);
4823 if ([context isEqualToString:@"remove"]) {
4824 if (button == [alert cancelButtonIndex])
4825 [self dismissModalViewControllerAnimated:YES];
4826 else if (button == [alert firstOtherButtonIndex]) {
4827 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
4830 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4831 } else if ([context isEqualToString:@"unable"]) {
4832 [self dismissModalViewControllerAnimated:YES];
4833 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4835 [super alertView:alert clickedButtonAtIndex:button];
4839 - (void) _doContinue {
4840 [delegate_ cancelAndClear:NO];
4841 [self dismissModalViewControllerAnimated:YES];
4844 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4845 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4849 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4850 [super webView:view didClearWindowObject:window forFrame:frame];
4852 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4853 (id) changes_, @"changes",
4854 (id) issues_, @"issues",
4855 (id) sizes_, @"sizes",
4857 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4860 - (id) initWithDatabase:(Database *)database {
4861 if ((self = [super init]) != nil) {
4862 database_ = database;
4864 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4865 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4866 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4867 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4868 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4872 pkgCacheFile &cache([database_ cache]);
4873 NSArray *packages([database_ packages]);
4874 pkgDepCache::Policy *policy([database_ policy]);
4876 issues_ = [NSMutableArray arrayWithCapacity:4];
4878 for (Package *package in packages) {
4879 pkgCache::PkgIterator iterator([package iterator]);
4880 NSString *name([package id]);
4882 if ([package broken]) {
4883 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4885 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4887 reasons, @"reasons",
4890 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4894 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4895 pkgCache::DepIterator start;
4896 pkgCache::DepIterator end;
4897 dep.GlobOr(start, end); // ++dep
4899 if (!cache->IsImportantDep(end))
4901 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4904 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4906 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4907 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4908 clauses, @"clauses",
4912 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4914 pkgCache::PkgIterator target(start.TargetPkg());
4915 if (target->ProvidesList != 0)
4916 reason = @"missing";
4918 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4920 reason = @"installed";
4921 installed = [NSString stringWithUTF8String:ver.VerStr()];
4922 } else if (!cache[target].CandidateVerIter(cache).end())
4923 reason = @"uninstalled";
4924 else if (target->ProvidesList == 0)
4925 reason = @"uninstallable";
4927 reason = @"virtual";
4930 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4931 [NSString stringWithUTF8String:start.CompType()], @"operator",
4932 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4935 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4936 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4937 version, @"version",
4939 installed, @"installed",
4942 // yes, seriously. (wtf?)
4950 pkgDepCache::StateCache &state(cache[iterator]);
4952 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4954 if (state.NewInstall())
4955 [installs addObject:name];
4956 // XXX: else if (state.Install())
4957 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4958 [reinstalls addObject:name];
4959 // XXX: move before previous if
4960 else if (state.Upgrade())
4961 [upgrades addObject:name];
4962 else if (state.Downgrade())
4963 [downgrades addObject:name];
4964 else if (!state.Delete())
4965 // XXX: _assert(state.Keep());
4967 else if (special_r(name))
4968 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4969 [NSNull null], @"package",
4970 [NSArray arrayWithObjects:
4971 [NSDictionary dictionaryWithObjectsAndKeys:
4972 @"Conflicts", @"relationship",
4973 [NSArray arrayWithObjects:
4974 [NSDictionary dictionaryWithObjectsAndKeys:
4976 [NSNull null], @"version",
4977 @"installed", @"reason",
4984 if ([package essential])
4986 [removes addObject:name];
4989 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4990 substrate_ |= DepSubstrate(iterator.CurrentVer());
4995 else if (Advanced_) {
4996 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4998 essential_ = [[[UIAlertView alloc]
4999 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5000 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5002 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5004 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5008 [essential_ setContext:@"remove"];
5009 [essential_ setNumberOfRows:2];
5011 essential_ = [[[UIAlertView alloc]
5012 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5013 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5015 cancelButtonTitle:UCLocalize("OKAY")
5016 otherButtonTitles:nil
5019 [essential_ setContext:@"unable"];
5022 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5023 installs, @"installs",
5024 reinstalls, @"reinstalls",
5025 upgrades, @"upgrades",
5026 downgrades, @"downgrades",
5027 removes, @"removes",
5030 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5031 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5032 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5035 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5039 - (UIBarButtonItem *) leftButton {
5040 return [[[UIBarButtonItem alloc]
5041 initWithTitle:UCLocalize("CANCEL")
5042 style:UIBarButtonItemStylePlain
5044 action:@selector(cancelButtonClicked)
5049 - (void) applyRightButton {
5050 if ([issues_ count] == 0 && ![self isLoading])
5051 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5052 initWithTitle:UCLocalize("CONFIRM")
5053 style:UIBarButtonItemStyleDone
5055 action:@selector(confirmButtonClicked)
5058 [[self navigationItem] setRightBarButtonItem:nil];
5062 - (void) cancelButtonClicked {
5063 [delegate_ cancelAndClear:YES];
5064 [self dismissModalViewControllerAnimated:YES];
5068 - (void) confirmButtonClicked {
5069 if (essential_ != nil)
5079 /* Progress Data {{{ */
5080 @interface CydiaProgressData : NSObject {
5081 _transient id delegate_;
5090 _H<NSMutableArray> events_;
5091 _H<NSString> title_;
5093 _H<NSString> status_;
5094 _H<NSString> finish_;
5099 @implementation CydiaProgressData
5101 + (NSArray *) _attributeKeys {
5102 return [NSArray arrayWithObjects:
5114 - (NSArray *) attributeKeys {
5115 return [[self class] _attributeKeys];
5118 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5119 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5123 if ((self = [super init]) != nil) {
5124 events_ = [NSMutableArray arrayWithCapacity:32];
5128 - (void) setDelegate:(id)delegate {
5129 delegate_ = delegate;
5132 - (void) setPercent:(float)value {
5136 - (NSNumber *) percent {
5137 return [NSNumber numberWithFloat:percent_];
5140 - (void) setCurrent:(float)value {
5144 - (NSNumber *) current {
5145 return [NSNumber numberWithFloat:current_];
5148 - (void) setTotal:(float)value {
5152 - (NSNumber *) total {
5153 return [NSNumber numberWithFloat:total_];
5156 - (void) setSpeed:(float)value {
5160 - (NSNumber *) speed {
5161 return [NSNumber numberWithFloat:speed_];
5164 - (NSArray *) events {
5168 - (void) removeAllEvents {
5169 [events_ removeAllObjects];
5172 - (void) addEvent:(CydiaProgressEvent *)event {
5173 [events_ addObject:event];
5176 - (void) setTitle:(NSString *)text {
5180 - (NSString *) title {
5184 - (void) setFinish:(NSString *)text {
5188 - (NSString *) finish {
5189 return (id) finish_ ?: [NSNull null];
5192 - (void) setRunning:(bool)running {
5196 - (NSNumber *) running {
5197 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5202 /* Progress Controller {{{ */
5203 @interface ProgressController : CydiaWebViewController <
5206 _transient Database *database_;
5207 _H<CydiaProgressData, 1> progress_;
5211 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5213 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5215 - (void) setTitle:(NSString *)title;
5216 - (void) setCancellable:(bool)cancellable;
5220 @implementation ProgressController
5223 [database_ setProgressDelegate:nil];
5227 - (UIBarButtonItem *) leftButton {
5228 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5229 initWithTitle:UCLocalize("CANCEL")
5230 style:UIBarButtonItemStylePlain
5232 action:@selector(cancel)
5233 ] autorelease] : nil;
5236 - (void) updateCancel {
5237 [super applyLeftButton];
5240 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5241 if ((self = [super init]) != nil) {
5242 database_ = database;
5243 delegate_ = delegate;
5245 [database_ setProgressDelegate:self];
5247 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5248 [progress_ setDelegate:self];
5250 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5252 [scroller_ setBackgroundColor:[UIColor blackColor]];
5254 [[self navigationItem] setHidesBackButton:YES];
5256 [self updateCancel];
5260 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5261 [super webView:view didClearWindowObject:window forFrame:frame];
5262 [window setValue:progress_ forKey:@"cydiaProgress"];
5265 - (void) updateProgress {
5266 [self dispatchEvent:@"CydiaProgressUpdate"];
5269 - (void) viewWillAppear:(BOOL)animated {
5270 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5271 [super viewWillAppear:animated];
5274 - (void) reloadSpringBoard {
5275 pid_t pid(ExecFork());
5277 pid_t pid(ExecFork());
5279 execl("/usr/bin/sbreload", "sbreload", NULL);
5290 system("/usr/bin/killall SpringBoard");
5294 UpdateExternalStatus(0);
5297 [delegate_ saveState];
5301 [delegate_ returnToCydia];
5305 [delegate_ terminateWithSuccess];
5306 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5307 [delegate_ suspendWithAnimation:YES];
5309 [delegate_ suspend];*/
5321 UIProgressHUD *hud([delegate_ addProgressHUD]);
5322 [hud setText:UCLocalize("LOADING")];
5323 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5329 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5330 SBReboot(SBSSpringBoardServerPort());
5332 reboot2(RB_AUTOBOOT);
5339 - (void) setTitle:(NSString *)title {
5340 [progress_ setTitle:title];
5341 [self updateProgress];
5344 - (UIBarButtonItem *) rightButton {
5345 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5346 initWithTitle:UCLocalize("CLOSE")
5347 style:UIBarButtonItemStylePlain
5349 action:@selector(close)
5353 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5354 UpdateExternalStatus(1);
5356 [progress_ setRunning:true];
5357 [self setTitle:title];
5358 // implicit updateProgress
5360 SHA1SumValue notifyconf; {
5362 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5365 MMap mmap(file, MMap::ReadOnly);
5367 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5368 notifyconf = sha1.Result();
5372 SHA1SumValue springlist; {
5374 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5377 MMap mmap(file, MMap::ReadOnly);
5379 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5380 springlist = sha1.Result();
5384 if (invocation != nil) {
5385 [invocation yieldToSelector:@selector(invoke)];
5386 [self setTitle:@"COMPLETE"];
5391 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5394 MMap mmap(file, MMap::ReadOnly);
5396 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5397 if (!(notifyconf == sha1.Result()))
5404 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5407 MMap mmap(file, MMap::ReadOnly);
5409 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5410 if (!(springlist == sha1.Result()))
5416 if (RestartSubstrate_)
5420 RestartSubstrate_ = false;
5423 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5424 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5425 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5426 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5427 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5430 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5432 [progress_ setRunning:false];
5433 [self updateProgress];
5435 [self applyRightButton];
5438 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5439 [progress_ addEvent:event];
5440 [self updateProgress];
5443 - (bool) isProgressCancelled {
5444 return cancel_ == 2;
5449 [self updateCancel];
5452 - (void) setCancellable:(bool)cancellable {
5453 unsigned cancel(cancel_);
5457 else if (cancel_ == 0)
5460 if (cancel != cancel_)
5461 [self updateCancel];
5464 - (void) setProgressCancellable:(NSNumber *)cancellable {
5465 [self setCancellable:[cancellable boolValue]];
5468 - (void) setProgressPercent:(NSNumber *)percent {
5469 [progress_ setPercent:[percent floatValue]];
5470 [self updateProgress];
5473 - (void) setProgressStatus:(NSDictionary *)status {
5474 if (status == nil) {
5475 [progress_ setCurrent:0];
5476 [progress_ setTotal:0];
5477 [progress_ setSpeed:0];
5479 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5481 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5482 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5483 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5486 [self updateProgress];
5492 /* Package Cell {{{ */
5493 @interface PackageCell : CyteTableViewCell <
5494 CyteTableViewCellDelegate
5498 _H<NSString> description_;
5500 _H<NSString> source_;
5502 _H<UIImage> placard_;
5506 - (PackageCell *) init;
5507 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5509 - (void) drawContentRect:(CGRect)rect;
5513 @implementation PackageCell
5515 - (PackageCell *) init {
5516 CGRect frame(CGRectMake(0, 0, 320, 74));
5517 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5518 UIView *content([self contentView]);
5519 CGRect bounds([content bounds]);
5521 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5522 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5523 [content addSubview:content_];
5525 [content_ setDelegate:self];
5526 [content_ setOpaque:YES];
5530 - (NSString *) accessibilityLabel {
5531 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5534 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5535 summarized_ = summary;
5545 [content_ setBackgroundColor:[UIColor whiteColor]];
5549 Source *source = [package source];
5551 icon_ = [package icon];
5553 if (NSString *name = [package name])
5554 name_ = [NSString stringWithString:name];
5556 NSString *description(nil);
5558 if (description == nil && IsWildcat_)
5559 description = [package longDescription];
5560 if (description == nil)
5561 description = [package shortDescription];
5563 if (description != nil)
5564 description_ = [NSString stringWithString:description];
5566 commercial_ = [package isCommercial];
5568 NSString *label = nil;
5569 bool trusted = false;
5571 if (source != nil) {
5572 label = [source label];
5573 trusted = [source trusted];
5574 } else if ([[package id] isEqualToString:@"firmware"])
5575 label = UCLocalize("APPLE");
5577 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5579 NSString *from(label);
5581 NSString *section = [package simpleSection];
5582 if (section != nil && ![section isEqualToString:label]) {
5583 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5584 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5587 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5589 if (NSString *purpose = [package primaryPurpose])
5590 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5595 if (NSString *mode = [package mode]) {
5596 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5597 color = RemovingColor_;
5598 //placard = @"removing";
5600 color = InstallingColor_;
5601 //placard = @"installing";
5604 // XXX: the removing/installing placards are not @2x
5607 color = [UIColor whiteColor];
5609 if ([package installed] != nil)
5610 placard = @"installed";
5615 [content_ setBackgroundColor:color];
5618 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5621 [self setNeedsDisplay];
5622 [content_ setNeedsDisplay];
5625 - (void) drawSummaryContentRect:(CGRect)rect {
5626 bool highlighted(highlighted_);
5627 float width([self bounds].size.width);
5631 rect.size = [(UIImage *) icon_ size];
5633 while (rect.size.width > 16 || rect.size.height > 16) {
5634 rect.size.width /= 2;
5635 rect.size.height /= 2;
5638 rect.origin.x = 18 - rect.size.width / 2;
5639 rect.origin.y = 18 - rect.size.height / 2;
5641 [icon_ drawInRect:rect];
5644 if (badge_ != nil) {
5646 rect.size = [(UIImage *) badge_ size];
5648 rect.size.width /= 4;
5649 rect.size.height /= 4;
5651 rect.origin.x = 23 - rect.size.width / 2;
5652 rect.origin.y = 23 - rect.size.height / 2;
5654 [badge_ drawInRect:rect];
5661 UISetColor(commercial_ ? Purple_ : Black_);
5662 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5664 if (placard_ != nil)
5665 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5668 - (void) drawNormalContentRect:(CGRect)rect {
5669 bool highlighted(highlighted_);
5670 float width([self bounds].size.width);
5674 rect.size = [(UIImage *) icon_ size];
5676 while (rect.size.width > 32 || rect.size.height > 32) {
5677 rect.size.width /= 2;
5678 rect.size.height /= 2;
5681 rect.origin.x = 25 - rect.size.width / 2;
5682 rect.origin.y = 25 - rect.size.height / 2;
5684 [icon_ drawInRect:rect];
5687 if (badge_ != nil) {
5689 rect.size = [(UIImage *) badge_ size];
5691 rect.size.width /= 2;
5692 rect.size.height /= 2;
5694 rect.origin.x = 36 - rect.size.width / 2;
5695 rect.origin.y = 36 - rect.size.height / 2;
5697 [badge_ drawInRect:rect];
5704 UISetColor(commercial_ ? Purple_ : Black_);
5705 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5706 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5709 UISetColor(commercial_ ? Purplish_ : Gray_);
5710 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5712 if (placard_ != nil)
5713 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5716 - (void) drawContentRect:(CGRect)rect {
5718 [self drawSummaryContentRect:rect];
5720 [self drawNormalContentRect:rect];
5725 /* Section Cell {{{ */
5726 @interface SectionCell : CyteTableViewCell <
5727 CyteTableViewCellDelegate
5729 _H<NSString> basic_;
5730 _H<NSString> section_;
5732 _H<NSString> count_;
5734 _H<UISwitch> switch_;
5738 - (void) setSection:(Section *)section editing:(BOOL)editing;
5742 @implementation SectionCell
5744 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5745 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5746 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5747 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5748 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5750 UIView *content([self contentView]);
5751 CGRect bounds([content bounds]);
5753 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5754 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5755 [content addSubview:content_];
5756 [content_ setBackgroundColor:[UIColor whiteColor]];
5758 [content_ setDelegate:self];
5762 - (void) onSwitch:(id)sender {
5763 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5764 if (metadata == nil) {
5765 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5766 [Sections_ setObject:metadata forKey:basic_];
5769 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5773 - (void) setSection:(Section *)section editing:(BOOL)editing {
5774 if (editing != editing_) {
5776 [switch_ removeFromSuperview];
5778 [self addSubview:switch_];
5787 if (section == nil) {
5788 name_ = UCLocalize("ALL_PACKAGES");
5791 basic_ = [section name];
5792 section_ = [section localized];
5794 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5795 count_ = [NSString stringWithFormat:@"%d", [section count]];
5798 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5801 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5802 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5804 [content_ setNeedsDisplay];
5807 - (void) setFrame:(CGRect)frame {
5808 [super setFrame:frame];
5810 CGRect rect([switch_ frame]);
5811 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5814 - (NSString *) accessibilityLabel {
5818 - (void) drawContentRect:(CGRect)rect {
5819 bool highlighted(highlighted_ && !editing_);
5821 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5826 float width(rect.size.width);
5832 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5834 CGSize size = [count_ sizeWithFont:Font14_];
5838 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5844 /* File Table {{{ */
5845 @interface FileTable : CyteViewController <
5846 UITableViewDataSource,
5849 _transient Database *database_;
5850 _H<Package> package_;
5852 _H<NSMutableArray> files_;
5853 _H<UITableView, 2> list_;
5856 - (id) initWithDatabase:(Database *)database;
5857 - (void) setPackage:(Package *)package;
5861 @implementation FileTable
5863 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5864 return files_ == nil ? 0 : [files_ count];
5867 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5871 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5872 static NSString *reuseIdentifier = @"Cell";
5874 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5876 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5877 [cell setFont:[UIFont systemFontOfSize:16]];
5879 [cell setText:[files_ objectAtIndex:indexPath.row]];
5880 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5885 - (NSURL *) navigationURL {
5886 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5890 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5891 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5892 [list_ setRowHeight:24.0f];
5893 [(UITableView *) list_ setDataSource:self];
5894 [list_ setDelegate:self];
5895 [self setView:list_];
5898 - (void) viewDidLoad {
5899 [super viewDidLoad];
5901 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5904 - (void) releaseSubviews {
5910 [super releaseSubviews];
5913 - (id) initWithDatabase:(Database *)database {
5914 if ((self = [super init]) != nil) {
5915 database_ = database;
5919 - (void) setPackage:(Package *)package {
5923 files_ = [NSMutableArray arrayWithCapacity:32];
5925 if (package != nil) {
5927 name_ = [package id];
5929 if (NSArray *files = [package files])
5930 [files_ addObjectsFromArray:files];
5932 if ([files_ count] != 0) {
5933 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5934 [files_ removeObjectAtIndex:0];
5935 [files_ sortUsingSelector:@selector(compareByPath:)];
5937 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5938 [stack addObject:@"/"];
5940 for (int i(0), e([files_ count]); i != e; ++i) {
5941 NSString *file = [files_ objectAtIndex:i];
5942 while (![file hasPrefix:[stack lastObject]])
5943 [stack removeLastObject];
5944 NSString *directory = [stack lastObject];
5945 [stack addObject:[file stringByAppendingString:@"/"]];
5946 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5947 ([stack count] - 2) * 3, "",
5948 [file substringFromIndex:[directory length]]
5957 - (void) reloadData {
5960 [self setPackage:[database_ packageWithName:name_]];
5965 /* Package Controller {{{ */
5966 @interface CYPackageController : CydiaWebViewController <
5967 UIActionSheetDelegate
5969 _transient Database *database_;
5970 _H<Package> package_;
5973 _H<NSMutableArray> buttons_;
5974 _H<UIBarButtonItem> button_;
5977 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
5981 @implementation CYPackageController
5983 - (NSURL *) navigationURL {
5984 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5987 /* XXX: this is not safe at all... localization of /fail/ */
5988 - (void) _clickButtonWithName:(NSString *)name {
5989 if ([name isEqualToString:UCLocalize("CLEAR")])
5990 [delegate_ clearPackage:package_];
5991 else if ([name isEqualToString:UCLocalize("INSTALL")])
5992 [delegate_ installPackage:package_];
5993 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5994 [delegate_ installPackage:package_];
5995 else if ([name isEqualToString:UCLocalize("REMOVE")])
5996 [delegate_ removePackage:package_];
5997 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5998 [delegate_ installPackage:package_];
5999 else _assert(false);
6002 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6003 NSString *context([sheet context]);
6005 if ([context isEqualToString:@"modify"]) {
6006 if (button != [sheet cancelButtonIndex]) {
6007 NSString *buttonName = [buttons_ objectAtIndex:button];
6008 [self _clickButtonWithName:buttonName];
6011 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6015 - (bool) _allowJavaScriptPanel {
6020 - (void) _customButtonClicked {
6021 int count([buttons_ count]);
6026 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6028 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6029 [buttons addObjectsFromArray:buttons_];
6031 UIActionSheet *sheet = [[[UIActionSheet alloc]
6034 cancelButtonTitle:nil
6035 destructiveButtonTitle:nil
6036 otherButtonTitles:nil
6039 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6041 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6042 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6044 [sheet setContext:@"modify"];
6046 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6050 // We don't want to allow non-commercial packages to do custom things to the install button,
6051 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6052 - (void) customButtonClicked {
6054 [super customButtonClicked];
6056 [self _customButtonClicked];
6059 - (void) reloadButtonClicked {
6060 // Don't reload a commerical package by tapping the loading button,
6061 // but if it's not an Install button, we should forward it on.
6062 if (![package_ uninstalled])
6063 [self _customButtonClicked];
6066 - (void) applyLoadingTitle {
6067 // Don't show "Loading" as the title. Ever.
6070 - (UIBarButtonItem *) rightButton {
6075 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6076 if ((self = [super init]) != nil) {
6077 database_ = database;
6078 buttons_ = [NSMutableArray arrayWithCapacity:4];
6079 name_ = name == nil ? @"" : [NSString stringWithString:name];
6080 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6084 - (void) reloadData {
6087 package_ = [database_ packageWithName:name_];
6089 [buttons_ removeAllObjects];
6091 if (package_ != nil) {
6092 [(Package *) package_ parse];
6094 commercial_ = [package_ isCommercial];
6096 if ([package_ mode] != nil)
6097 [buttons_ addObject:UCLocalize("CLEAR")];
6098 if ([package_ source] == nil);
6099 else if ([package_ upgradableAndEssential:NO])
6100 [buttons_ addObject:UCLocalize("UPGRADE")];
6101 else if ([package_ uninstalled])
6102 [buttons_ addObject:UCLocalize("INSTALL")];
6104 [buttons_ addObject:UCLocalize("REINSTALL")];
6105 if (![package_ uninstalled])
6106 [buttons_ addObject:UCLocalize("REMOVE")];
6110 switch ([buttons_ count]) {
6111 case 0: title = nil; break;
6112 case 1: title = [buttons_ objectAtIndex:0]; break;
6113 default: title = UCLocalize("MODIFY"); break;
6116 button_ = [[[UIBarButtonItem alloc]
6118 style:UIBarButtonItemStylePlain
6120 action:@selector(customButtonClicked)
6124 - (bool) isLoading {
6125 return commercial_ ? [super isLoading] : false;
6131 /* Package List Controller {{{ */
6132 @interface PackageListController : CyteViewController <
6133 UITableViewDataSource,
6136 _transient Database *database_;
6138 _H<NSArray> packages_;
6139 _H<NSMutableArray> sections_;
6140 _H<UITableView, 2> list_;
6141 _H<NSMutableArray> index_;
6142 _H<NSMutableDictionary> indices_;
6143 _H<NSString> title_;
6144 unsigned reloading_;
6147 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6148 - (void) setDelegate:(id)delegate;
6149 - (void) resetCursor;
6154 @implementation PackageListController
6156 - (NSURL *) referrerURL {
6157 return [self navigationURL];
6160 - (bool) isSummarized {
6164 - (bool) showsSections {
6168 - (void) deselectWithAnimation:(BOOL)animated {
6169 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6172 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6173 CGRect base = [[self view] bounds];
6174 base.size.height -= bounds.size.height;
6175 base.origin = [list_ frame].origin;
6177 [UIView beginAnimations:nil context:NULL];
6178 [UIView setAnimationBeginsFromCurrentState:YES];
6179 [UIView setAnimationCurve:curve];
6180 [UIView setAnimationDuration:duration];
6181 [list_ setFrame:base];
6182 [UIView commitAnimations];
6185 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6186 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6189 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6190 [self resizeForKeyboardBounds:bounds duration:0];
6193 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6194 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6195 *curve = UIViewAnimationCurveEaseInOut;
6197 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6199 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6202 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6205 - (void) keyboardWillShow:(NSNotification *)notification {
6208 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6209 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6211 NSTimeInterval duration;
6212 UIViewAnimationCurve curve;
6213 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6215 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);
6216 UIViewController *base = self;
6217 while ([base parentOrPresentingViewController] != nil)
6218 base = [base parentOrPresentingViewController];
6219 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6220 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6222 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6223 intersection.size.height += CYStatusBarHeight();
6225 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6228 - (void) keyboardWillHide:(NSNotification *)notification {
6229 NSTimeInterval duration;
6230 UIViewAnimationCurve curve;
6231 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6233 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6236 - (void) viewWillAppear:(BOOL)animated {
6237 [super viewWillAppear:animated];
6239 [self resizeForKeyboardBounds:CGRectZero];
6240 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6241 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6244 - (void) viewWillDisappear:(BOOL)animated {
6245 [super viewWillDisappear:animated];
6247 [self resizeForKeyboardBounds:CGRectZero];
6248 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6249 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6252 - (void) viewDidAppear:(BOOL)animated {
6253 [super viewDidAppear:animated];
6254 [self deselectWithAnimation:animated];
6257 - (void) didSelectPackage:(Package *)package {
6258 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6259 [view setDelegate:delegate_];
6260 [[self navigationController] pushViewController:view animated:YES];
6263 #if TryIndexedCollation
6264 + (BOOL) hasIndexedCollation {
6265 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6269 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6270 NSInteger count([sections_ count]);
6271 return count == 0 ? 1 : count;
6274 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6275 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6277 return [[sections_ objectAtIndex:section] name];
6280 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6281 if ([sections_ count] == 0)
6283 return [[sections_ objectAtIndex:section] count];
6286 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6287 @synchronized (database_) {
6288 if ([database_ era] != era_)
6291 Section *section([sections_ objectAtIndex:[path section]]);
6292 NSInteger row([path row]);
6293 Package *package([packages_ objectAtIndex:([section row] + row)]);
6294 return [[package retain] autorelease];
6297 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6298 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6300 cell = [[[PackageCell alloc] init] autorelease];
6302 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6303 [cell setPackage:package asSummary:[self isSummarized]];
6307 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6308 Package *package([self packageAtIndexPath:path]);
6309 package = [database_ packageWithName:[package id]];
6310 [self didSelectPackage:package];
6313 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6314 if (![self showsSections])
6320 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6321 #if TryIndexedCollation
6322 if ([[self class] hasIndexedCollation]) {
6323 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6330 - (void) updateHeight {
6331 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6334 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6335 if ((self = [super init]) != nil) {
6336 database_ = database;
6337 title_ = [title copy];
6338 [[self navigationItem] setTitle:title_];
6343 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6344 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6345 [self setView:view];
6347 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6348 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6349 [view addSubview:list_];
6351 // XXX: is 20 the most optimal number here?
6352 [list_ setSectionIndexMinimumDisplayRowCount:20];
6354 [(UITableView *) list_ setDataSource:self];
6355 [list_ setDelegate:self];
6357 [self updateHeight];
6360 - (void) releaseSubviews {
6368 [super releaseSubviews];
6371 - (void) setDelegate:(id)delegate {
6372 delegate_ = delegate;
6375 - (bool) shouldYield {
6379 - (bool) shouldBlock {
6383 - (NSMutableArray *) _reloadPackages {
6384 @synchronized (database_) {
6385 era_ = [database_ era];
6386 NSArray *packages([database_ packages]);
6388 return [NSMutableArray arrayWithArray:packages];
6391 - (void) _reloadData {
6392 if (reloading_ != 0) {
6400 if ([self shouldYield]) {
6404 if (![self shouldBlock])
6407 hud = [delegate_ addProgressHUD];
6408 [hud setText:UCLocalize("LOADING")];
6412 packages = [self yieldToSelector:@selector(_reloadPackages)];
6415 [delegate_ removeProgressHUD:hud];
6416 } while (reloading_ == 2);
6418 packages = [self _reloadPackages];
6421 @synchronized (database_) {
6422 if (era_ != [database_ era])
6426 packages_ = packages;
6428 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6429 sections_ = [NSMutableArray arrayWithCapacity:16];
6431 Section *section = nil;
6433 #if TryIndexedCollation
6434 if ([[self class] hasIndexedCollation]) {
6435 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6437 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6438 NSArray *titles = [collation sectionIndexTitles];
6441 _profile(PackageTable$reloadData$Section)
6442 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6446 _profile(PackageTable$reloadData$Section$Package)
6447 package = [packages_ objectAtIndex:offset];
6448 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6451 while (secidx < index) {
6454 _profile(PackageTable$reloadData$Section$Allocate)
6455 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6458 _profile(PackageTable$reloadData$Section$Add)
6459 [sections_ addObject:section];
6463 [section addToCount];
6469 index_ = [NSMutableArray arrayWithCapacity:32];
6471 bool sectioned([self showsSections]);
6473 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6474 [sections_ addObject:section];
6477 _profile(PackageTable$reloadData$Section)
6478 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6482 _profile(PackageTable$reloadData$Section$Package)
6483 package = [packages_ objectAtIndex:offset];
6484 index = [package index];
6487 if (sectioned && (section == nil || [section index] != index)) {
6488 _profile(PackageTable$reloadData$Section$Allocate)
6489 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6492 [index_ addObject:[section name]];
6493 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6495 _profile(PackageTable$reloadData$Section$Add)
6496 [sections_ addObject:section];
6500 [section addToCount];
6505 [self updateHeight];
6507 _profile(PackageTable$reloadData$List)
6508 [(UITableView *) list_ setDataSource:self];
6513 - (void) reloadData {
6516 if ([self shouldYield])
6517 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6522 - (void) resetCursor {
6523 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6526 - (void) clearData {
6527 [self updateHeight];
6529 [list_ setDataSource:nil];
6537 /* Filtered Package List Controller {{{ */
6538 @interface FilteredPackageListController : PackageListController {
6541 _H<NSObject> object_;
6544 - (void) setObject:(id)object;
6545 - (void) setObject:(id)object forFilter:(SEL)filter;
6548 - (void) setFilter:(SEL)filter;
6550 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6554 @implementation FilteredPackageListController
6560 - (void) setFilter:(SEL)filter {
6561 @synchronized (self) {
6564 /* XXX: this is an unsafe optimization of doomy hell */
6565 Method method(class_getInstanceMethod([Package class], filter));
6566 _assert(method != NULL);
6567 imp_ = method_getImplementation(method);
6568 _assert(imp_ != NULL);
6571 - (void) setObject:(id)object {
6572 @synchronized (self) {
6576 - (void) setObject:(id)object forFilter:(SEL)filter {
6577 @synchronized (self) {
6578 [self setFilter:filter];
6579 [self setObject:object];
6582 - (NSMutableArray *) _reloadPackages {
6583 @synchronized (database_) {
6584 era_ = [database_ era];
6585 NSArray *packages([database_ packages]);
6587 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6591 _H<NSObject> object;
6593 @synchronized (self) {
6599 _profile(PackageTable$reloadData$Filter)
6600 for (Package *package in packages)
6601 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6602 [filtered addObject:package];
6608 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6609 if ((self = [super initWithDatabase:database title:title]) != nil) {
6610 [self setFilter:filter];
6611 [self setObject:object];
6618 /* Home Controller {{{ */
6619 @interface HomeController : CydiaWebViewController {
6620 CFRunLoopRef runloop_;
6621 SCNetworkReachabilityRef reachability_;
6626 @implementation HomeController
6628 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6629 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6633 if ((self = [super init]) != nil) {
6634 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6637 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6638 if (reachability_ != NULL) {
6639 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6640 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6642 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6643 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6650 if (reachability_ != NULL && runloop_ != NULL)
6651 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6655 - (NSURL *) navigationURL {
6656 return [NSURL URLWithString:@"cydia://home"];
6659 - (void) aboutButtonClicked {
6660 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6662 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6663 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6664 [alert setCancelButtonIndex:0];
6667 @"Copyright \u00a9 2008-2011\n"
6670 "Jay Freeman (saurik)\n"
6671 "saurik@saurik.com\n"
6672 "http://www.saurik.com/"
6678 - (UIBarButtonItem *) leftButton {
6679 return [[[UIBarButtonItem alloc]
6680 initWithTitle:UCLocalize("ABOUT")
6681 style:UIBarButtonItemStylePlain
6683 action:@selector(aboutButtonClicked)
6689 /* Manage Controller {{{ */
6690 @interface ManageController : CydiaWebViewController {
6693 - (void) queueStatusDidChange;
6697 @implementation ManageController
6700 if ((self = [super init]) != nil) {
6701 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6705 - (NSURL *) navigationURL {
6706 return [NSURL URLWithString:@"cydia://manage"];
6709 - (UIBarButtonItem *) leftButton {
6710 return [[[UIBarButtonItem alloc]
6711 initWithTitle:UCLocalize("SETTINGS")
6712 style:UIBarButtonItemStylePlain
6714 action:@selector(settingsButtonClicked)
6718 - (void) settingsButtonClicked {
6719 [delegate_ showSettings];
6722 - (void) queueButtonClicked {
6726 - (UIBarButtonItem *) rightButton {
6727 return Queuing_ ? [[[UIBarButtonItem alloc]
6728 initWithTitle:UCLocalize("QUEUE")
6729 style:UIBarButtonItemStyleDone
6731 action:@selector(queueButtonClicked)
6732 ] autorelease] : nil;
6735 - (void) queueStatusDidChange {
6736 [self applyRightButton];
6739 - (bool) isLoading {
6740 return !Queuing_ && [super isLoading];
6746 /* Refresh Bar {{{ */
6747 @interface RefreshBar : UINavigationBar {
6748 _H<UIProgressIndicator> indicator_;
6749 _H<UITextLabel> prompt_;
6750 _H<UIProgressBar> progress_;
6751 _H<UINavigationButton> cancel_;
6756 @implementation RefreshBar
6758 - (void) positionViews {
6759 CGRect frame = [cancel_ frame];
6760 frame.size = [cancel_ sizeThatFits:frame.size];
6761 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6762 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6763 [cancel_ setFrame:frame];
6765 CGSize prgsize = {75, 100};
6767 [self frame].size.width - prgsize.width - 10,
6768 ([self frame].size.height - prgsize.height) / 2
6770 [progress_ setFrame:prgrect];
6772 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6773 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6774 CGRect indrect = {{indoffset, indoffset}, indsize};
6775 [indicator_ setFrame:indrect];
6777 CGSize prmsize = {215, indsize.height + 4};
6779 indoffset * 2 + indsize.width,
6780 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6782 [prompt_ setFrame:prmrect];
6785 - (void) setFrame:(CGRect)frame {
6786 [super setFrame:frame];
6787 [self positionViews];
6790 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6791 if ((self = [super initWithFrame:frame]) != nil) {
6792 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6794 [self setBarStyle:UIBarStyleBlack];
6796 UIBarStyle barstyle([self _barStyle:NO]);
6797 bool ugly(barstyle == UIBarStyleDefault);
6799 UIProgressIndicatorStyle style = ugly ?
6800 UIProgressIndicatorStyleMediumBrown :
6801 UIProgressIndicatorStyleMediumWhite;
6803 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6804 [(UIProgressIndicator *) indicator_ setStyle:style];
6805 [indicator_ startAnimation];
6806 [self addSubview:indicator_];
6808 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6809 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6810 [prompt_ setBackgroundColor:[UIColor clearColor]];
6811 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6812 [self addSubview:prompt_];
6814 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6815 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6816 [(UIProgressBar *) progress_ setStyle:0];
6817 [self addSubview:progress_];
6819 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6820 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6821 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6822 [cancel_ setBarStyle:barstyle];
6824 [self positionViews];
6828 - (void) setCancellable:(bool)cancellable {
6830 [self addSubview:cancel_];
6832 [cancel_ removeFromSuperview];
6836 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6837 [progress_ setProgress:0];
6841 [self setCancellable:NO];
6844 - (void) setPrompt:(NSString *)prompt {
6845 [prompt_ setText:prompt];
6848 - (void) setProgress:(float)progress {
6849 [progress_ setProgress:progress];
6855 /* Cydia Navigation Controller Interface {{{ */
6856 @interface UINavigationController (Cydia)
6858 - (NSArray *) navigationURLCollection;
6859 - (void) unloadData;
6864 /* Cydia Tab Bar Controller {{{ */
6865 @interface CYTabBarController : UITabBarController <
6866 UITabBarControllerDelegate,
6869 _transient Database *database_;
6870 _H<RefreshBar, 1> refreshbar_;
6874 // XXX: ok, "updatedelegate_"?...
6875 _transient NSObject<CydiaDelegate> *updatedelegate_;
6877 _H<UIViewController> remembered_;
6878 _transient UIViewController *transient_;
6881 - (NSArray *) navigationURLCollection;
6882 - (void) dropBar:(BOOL)animated;
6883 - (void) beginUpdate;
6884 - (void) raiseBar:(BOOL)animated;
6886 - (void) unloadData;
6890 @implementation CYTabBarController
6892 - (void) didReceiveMemoryWarning {
6893 [super didReceiveMemoryWarning];
6895 // presenting a UINavigationController on 2.x does not update its transitionView
6896 // it thereby will not allow its topViewController to be unloaded by memory pressure
6897 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6898 UIViewController *selected([self selectedViewController]);
6899 for (UINavigationController *controller in [self viewControllers])
6900 if (controller != selected)
6901 if (UIViewController *top = [controller topViewController])
6906 - (void) setUnselectedViewController:(UIViewController *)transient {
6907 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6908 if (transient != nil) {
6909 [[[self viewControllers] objectAtIndex:0] pushViewController:transient animated:YES];
6910 [self setSelectedIndex:0];
6914 NSMutableArray *controllers = [[[self viewControllers] mutableCopy] autorelease];
6915 if (transient != nil) {
6916 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
6917 [navigation setViewControllers:[NSArray arrayWithObject:transient]];
6918 transient = navigation;
6920 if (transient_ == nil)
6921 remembered_ = [controllers objectAtIndex:0];
6922 transient_ = transient;
6923 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6924 [controllers replaceObjectAtIndex:0 withObject:transient_];
6925 [self setSelectedIndex:0];
6926 [self setViewControllers:controllers];
6927 [self concealTabBarSelection];
6928 } else if (remembered_ != nil) {
6929 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6930 transient_ = transient;
6931 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6933 [self setViewControllers:controllers];
6934 [self revealTabBarSelection];
6938 - (UIViewController *) unselectedViewController {
6942 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6943 if ([self unselectedViewController])
6944 [self setUnselectedViewController:nil];
6946 // presenting a UINavigationController on 2.x does not update its transitionView
6947 // if this view was unloaded, the tranitionView may currently be presenting nothing
6948 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6949 UINavigationController *navigation((UINavigationController *) viewController);
6950 [navigation pushViewController:[[[UIViewController alloc] init] autorelease] animated:NO];
6951 [navigation popViewControllerAnimated:NO];
6955 - (NSArray *) navigationURLCollection {
6956 NSMutableArray *items([NSMutableArray array]);
6958 // XXX: Should this deal with transient view controllers?
6959 for (id navigation in [self viewControllers]) {
6960 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6962 [items addObject:stack];
6968 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6969 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6970 [self setUnselectedViewController:nil];
6972 [super dismissModalViewControllerAnimated:YES];
6975 - (void) unloadData {
6978 for (UINavigationController *controller in [self viewControllers])
6979 [controller unloadData];
6981 if (UIViewController *selected = [self selectedViewController])
6982 [selected reloadData];
6984 if (UIViewController *unselected = [self unselectedViewController]) {
6985 [unselected unloadData];
6986 [unselected reloadData];
6991 [[NSNotificationCenter defaultCenter] removeObserver:self];
6996 - (id) initWithDatabase:(Database *)database {
6997 if ((self = [super init]) != nil) {
6998 database_ = database;
6999 [self setDelegate:self];
7001 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7002 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7004 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
7008 - (void) setUpdate:(NSDate *)date {
7012 - (void) beginUpdate {
7013 [(RefreshBar *) refreshbar_ start];
7016 [updatedelegate_ retainNetworkActivityIndicator];
7020 detachNewThreadSelector:@selector(performUpdate)
7026 - (void) performUpdate {
7027 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7030 status.setDelegate(self);
7031 [database_ updateWithStatus:status];
7034 performSelectorOnMainThread:@selector(completeUpdate)
7042 - (void) stopUpdateWithSelector:(SEL)selector {
7044 [updatedelegate_ releaseNetworkActivityIndicator];
7046 [self raiseBar:YES];
7049 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7052 - (void) completeUpdate {
7055 [self stopUpdateWithSelector:@selector(reloadData)];
7058 - (void) cancelUpdate {
7059 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7062 - (void) cancelPressed {
7063 [self cancelUpdate];
7070 - (void) addProgressEvent:(CydiaProgressEvent *)event {
7071 [refreshbar_ setPrompt:[event compoundMessage]];
7074 - (bool) isProgressCancelled {
7078 - (void) setProgressCancellable:(NSNumber *)cancellable {
7079 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
7082 - (void) setProgressPercent:(NSNumber *)percent {
7083 [refreshbar_ setProgress:[percent floatValue]];
7086 - (void) setProgressStatus:(NSDictionary *)status {
7088 [self setProgressPercent:[status objectForKey:@"Percent"]];
7091 - (void) setUpdateDelegate:(id)delegate {
7092 updatedelegate_ = delegate;
7095 - (UIView *) transitionView {
7096 if ([self respondsToSelector:@selector(_transitionView)])
7097 return [self _transitionView];
7099 return MSHookIvar<id>(self, "_viewControllerTransitionView");
7102 - (void) dropBar:(BOOL)animated {
7107 UIView *transition([self transitionView]);
7108 [[self view] addSubview:refreshbar_];
7110 CGRect barframe([refreshbar_ frame]);
7112 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
7113 barframe.origin.y = CYStatusBarHeight();
7115 barframe.origin.y = 0;
7117 [refreshbar_ setFrame:barframe];
7120 [UIView beginAnimations:nil context:NULL];
7122 CGRect viewframe = [transition frame];
7123 viewframe.origin.y += barframe.size.height;
7124 viewframe.size.height -= barframe.size.height;
7125 [transition setFrame:viewframe];
7128 [UIView commitAnimations];
7130 // Ensure bar has the proper width for our view, it might have changed
7131 barframe.size.width = viewframe.size.width;
7132 [refreshbar_ setFrame:barframe];
7135 - (void) raiseBar:(BOOL)animated {
7140 UIView *transition([self transitionView]);
7141 [refreshbar_ removeFromSuperview];
7143 CGRect barframe([refreshbar_ frame]);
7146 [UIView beginAnimations:nil context:NULL];
7148 CGRect viewframe = [transition frame];
7149 viewframe.origin.y -= barframe.size.height;
7150 viewframe.size.height += barframe.size.height;
7151 [transition setFrame:viewframe];
7154 [UIView commitAnimations];
7157 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7158 bool dropped(dropped_);
7163 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7169 - (void) statusBarFrameChanged:(NSNotification *)notification {
7179 /* Cydia Navigation Controller Implementation {{{ */
7180 @implementation UINavigationController (Cydia)
7182 - (NSArray *) navigationURLCollection {
7183 NSMutableArray *stack([NSMutableArray array]);
7185 for (CyteViewController *controller in [self viewControllers]) {
7186 NSString *url = [[controller navigationURL] absoluteString];
7188 [stack addObject:url];
7194 - (void) reloadData {
7197 UIViewController *visible([self visibleViewController]);
7199 [visible reloadData];
7201 // on the iPad, this view controller is ALSO visible. :(
7203 if (UIViewController *top = [self topViewController])
7208 - (void) unloadData {
7209 for (CyteViewController *page in [self viewControllers])
7218 /* Cydia:// Protocol {{{ */
7219 @interface CydiaURLProtocol : NSURLProtocol {
7224 @implementation CydiaURLProtocol
7226 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7227 NSURL *url([request URL]);
7231 NSString *scheme([[url scheme] lowercaseString]);
7232 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7234 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7240 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7244 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7245 id<NSURLProtocolClient> client([self client]);
7247 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7249 NSData *data(UIImagePNGRepresentation(icon));
7251 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7252 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7253 [client URLProtocol:self didLoadData:data];
7254 [client URLProtocolDidFinishLoading:self];
7258 - (void) startLoading {
7259 id<NSURLProtocolClient> client([self client]);
7260 NSURLRequest *request([self request]);
7262 NSURL *url([request URL]);
7263 NSString *href([url absoluteString]);
7264 NSString *scheme([[url scheme] lowercaseString]);
7268 if ([scheme isEqualToString:@"cydia"])
7269 path = [href substringFromIndex:8];
7270 else if ([scheme isEqualToString:@"about"])
7271 path = [href substringFromIndex:12];
7272 else _assert(false);
7274 NSRange slash([path rangeOfString:@"/"]);
7277 if (slash.location == NSNotFound) {
7281 command = [path substringToIndex:slash.location];
7282 path = [path substringFromIndex:(slash.location + 1)];
7285 Database *database([Database sharedInstance]);
7287 if ([command isEqualToString:@"package-icon"]) {
7290 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7291 Package *package([database packageWithName:path]);
7295 UIImage *icon([package icon]);
7296 [self _returnPNGWithImage:icon forRequest:request];
7297 } else if ([command isEqualToString:@"uikit-image"]) {
7300 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7301 UIImage *icon(_UIImageWithName(path));
7302 [self _returnPNGWithImage:icon forRequest:request];
7303 } else if ([command isEqualToString:@"section-icon"]) {
7306 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7307 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7309 icon = [UIImage applicationImageNamed:@"unknown.png"];
7310 [self _returnPNGWithImage:icon forRequest:request];
7312 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7316 - (void) stopLoading {
7322 /* Section Controller {{{ */
7323 @interface SectionController : FilteredPackageListController {
7324 _H<IndirectDelegate, 1> indirect_;
7325 _H<CydiaObject> cydia_;
7326 _H<NSString> section_;
7327 std::vector< _H<CyteWebViewTableViewCell, 1> > promoted_;
7330 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7334 @implementation SectionController
7336 - (NSURL *) referrerURL {
7337 NSString *name = section_;
7341 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@", UI_, [name stringByAddingPercentEscapesIncludingReserved]]];
7344 - (NSURL *) navigationURL {
7345 NSString *name = section_;
7349 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", [name stringByAddingPercentEscapesIncludingReserved]]];
7352 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7355 title = UCLocalize("ALL_PACKAGES");
7356 else if (![name isEqual:@""])
7357 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7359 title = UCLocalize("NO_SECTION");
7361 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7362 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7363 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7368 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7369 return [super numberOfSectionsInTableView:list] + 1;
7372 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7373 return section == 0 ? nil : [super tableView:list titleForHeaderInSection:(section - 1)];
7376 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7377 return section == 0 ? promoted_.size() : [super tableView:list numberOfRowsInSection:(section - 1)];
7380 + (NSIndexPath *) adjustedIndexPath:(NSIndexPath *)path {
7381 return [NSIndexPath indexPathForRow:[path row] inSection:([path section] - 1)];
7384 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7385 if ([path section] != 0)
7386 return [super tableView:table cellForRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7388 return promoted_[[path row]];
7391 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
7392 if ([path section] != 0)
7393 return [super tableView:table didSelectRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7396 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
7397 NSInteger section([super tableView:tableView sectionForSectionIndexTitle:title atIndex:index]);
7398 return section == 0 ? 0 : section + 1;
7401 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7402 NSURL *url([request URL]);
7406 if ([frame isEqualToString:@"_open"])
7407 [delegate_ openURL:url];
7409 WebFrame *frame(nil);
7410 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7411 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7413 frame = [view mainFrame];
7415 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7417 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7418 [controller setDelegate:delegate_];
7419 [[self navigationController] pushViewController:controller animated:YES];
7425 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7426 return [CydiaWebViewController requestWithHeaders:request];
7429 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7430 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7436 // XXX: this code is horrible. I mean, wtf Jay?
7437 if (ShowPromoted_ && [[Metadata_ objectForKey:@"ShowPromoted"] boolValue]) {
7438 promoted_.resize(1);
7440 for (unsigned i(0); i != promoted_.size(); ++i) {
7441 CyteWebViewTableViewCell *promoted([CyteWebViewTableViewCell cellWithRequest:[NSURLRequest
7442 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sectionhead/%u/%@",
7443 UI_, i, section_ == nil ? @"" : [section_ stringByAddingPercentEscapesIncludingReserved]]
7446 cachePolicy:NSURLRequestUseProtocolCachePolicy
7450 [promoted setDelegate:self];
7451 promoted_[i] = promoted;
7456 - (void) setDelegate:(id)delegate {
7457 [super setDelegate:delegate];
7458 [cydia_ setDelegate:delegate];
7461 - (void) releaseSubviews {
7463 [super releaseSubviews];
7468 /* Sections Controller {{{ */
7469 @interface SectionsController : CyteViewController <
7470 UITableViewDataSource,
7473 _transient Database *database_;
7474 _H<NSMutableArray> sections_;
7475 _H<NSMutableArray> filtered_;
7476 _H<UITableView, 2> list_;
7479 - (id) initWithDatabase:(Database *)database;
7480 - (void) editButtonClicked;
7484 @implementation SectionsController
7486 - (NSURL *) navigationURL {
7487 return [NSURL URLWithString:@"cydia://sections"];
7490 - (void) updateNavigationItem {
7491 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7492 if ([sections_ count] == 0) {
7493 [[self navigationItem] setRightBarButtonItem:nil];
7495 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7496 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7498 action:@selector(editButtonClicked)
7499 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7503 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7504 [super setEditing:editing animated:animated];
7509 [delegate_ updateData];
7511 [self updateNavigationItem];
7514 - (void) viewDidAppear:(BOOL)animated {
7515 [super viewDidAppear:animated];
7516 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7519 - (void) viewWillDisappear:(BOOL)animated {
7520 [super viewWillDisappear:animated];
7521 [self setEditing:NO];
7524 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7525 Section *section = nil;
7526 int index = [indexPath row];
7527 if (![self isEditing]) {
7530 section = [filtered_ objectAtIndex:index];
7532 section = [sections_ objectAtIndex:index];
7537 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7538 if ([self isEditing])
7539 return [sections_ count];
7541 return [filtered_ count] + 1;
7544 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7548 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7549 static NSString *reuseIdentifier = @"SectionCell";
7551 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7553 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7555 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7560 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7561 if ([self isEditing])
7564 Section *section = [self sectionAtIndexPath:indexPath];
7566 SectionController *controller = [[[SectionController alloc]
7567 initWithDatabase:database_
7568 section:[section name]
7570 [controller setDelegate:delegate_];
7572 [[self navigationController] pushViewController:controller animated:YES];
7576 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7577 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7578 [list_ setRowHeight:45.0f];
7579 [(UITableView *) list_ setDataSource:self];
7580 [list_ setDelegate:self];
7581 [self setView:list_];
7584 - (void) viewDidLoad {
7585 [super viewDidLoad];
7587 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7590 - (void) releaseSubviews {
7596 [super releaseSubviews];
7599 - (id) initWithDatabase:(Database *)database {
7600 if ((self = [super init]) != nil) {
7601 database_ = database;
7605 - (void) reloadData {
7608 NSArray *packages = [database_ packages];
7610 sections_ = [NSMutableArray arrayWithCapacity:16];
7611 filtered_ = [NSMutableArray arrayWithCapacity:16];
7613 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7616 for (Package *package in packages) {
7617 NSString *name([package section]);
7618 NSString *key(name == nil ? @"" : name);
7622 _profile(SectionsView$reloadData$Section)
7623 section = [sections objectForKey:key];
7624 if (section == nil) {
7625 _profile(SectionsView$reloadData$Section$Allocate)
7626 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7627 [sections setObject:section forKey:key];
7632 [section addToCount];
7634 _profile(SectionsView$reloadData$Filter)
7635 if (![package valid] || ![package visible])
7643 [sections_ addObjectsFromArray:[sections allValues]];
7645 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7647 for (Section *section in (id) sections_) {
7648 size_t count([section row]);
7652 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7653 [section setCount:count];
7654 [filtered_ addObject:section];
7657 [self updateNavigationItem];
7662 - (void) editButtonClicked {
7663 [self setEditing:![self isEditing] animated:YES];
7669 /* Changes Controller {{{ */
7670 @interface ChangesController : CyteViewController <
7671 CyteWebViewDelegate,
7672 UITableViewDataSource,
7675 _transient Database *database_;
7677 _H<NSMutableArray> packages_;
7678 _H<NSMutableArray> sections_;
7679 _H<UITableView, 2> list_;
7680 _H<CyteWebView, 1> dickbar_;
7682 _H<IndirectDelegate, 1> indirect_;
7683 _H<CydiaObject> cydia_;
7686 - (id) initWithDatabase:(Database *)database;
7690 @implementation ChangesController
7692 - (NSURL *) navigationURL {
7693 return [NSURL URLWithString:@"cydia://changes"];
7696 - (void) viewDidAppear:(BOOL)animated {
7697 [super viewDidAppear:animated];
7698 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7701 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7702 NSInteger count([sections_ count]);
7703 return count == 0 ? 1 : count;
7706 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7707 if ([sections_ count] == 0)
7709 return [[sections_ objectAtIndex:section] name];
7712 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7713 if ([sections_ count] == 0)
7715 return [[sections_ objectAtIndex:section] count];
7718 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7719 @synchronized (database_) {
7720 if ([database_ era] != era_)
7723 NSUInteger sectionIndex([path section]);
7724 if (sectionIndex >= [sections_ count])
7726 Section *section([sections_ objectAtIndex:sectionIndex]);
7727 NSInteger row([path row]);
7728 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7731 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7732 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7734 cell = [[[PackageCell alloc] init] autorelease];
7736 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7737 [cell setPackage:package asSummary:false];
7741 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7742 Package *package([self packageAtIndexPath:path]);
7743 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[NSString stringWithFormat:@"%@/#!/changes/", UI_]] autorelease]);
7744 [view setDelegate:delegate_];
7745 [[self navigationController] pushViewController:view animated:YES];
7749 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7750 NSString *context([alert context]);
7752 if ([context isEqualToString:@"norefresh"])
7753 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7756 - (void) refreshButtonClicked {
7757 if (IsReachable("cydia.saurik.com")) {
7758 [delegate_ beginUpdate];
7759 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7761 UIAlertView *alert = [[[UIAlertView alloc]
7762 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
7763 message:@"Host Unreachable" // XXX: Localize
7765 cancelButtonTitle:UCLocalize("OK")
7766 otherButtonTitles:nil
7769 [alert setContext:@"norefresh"];
7774 - (void) upgradeButtonClicked {
7775 [delegate_ distUpgrade];
7776 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7780 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7781 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7782 [self setView:view];
7784 list_ = [[[UITableView alloc] initWithFrame:[view bounds] style:UITableViewStylePlain] autorelease];
7785 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7786 [list_ setRowHeight:73];
7787 [(UITableView *) list_ setDataSource:self];
7788 [list_ setDelegate:self];
7789 [view addSubview:list_];
7791 if (AprilFools_ && kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
7792 CGRect dickframe([view bounds]);
7793 dickframe.size.height = 44;
7795 dickbar_ = [[[CyteWebView alloc] initWithFrame:dickframe] autorelease];
7796 [dickbar_ setDelegate:self];
7797 [view addSubview:dickbar_];
7799 [dickbar_ setBackgroundColor:[UIColor clearColor]];
7800 [dickbar_ setScalesPageToFit:YES];
7802 UIWebDocumentView *document([dickbar_ _documentView]);
7803 [document setBackgroundColor:[UIColor clearColor]];
7804 [document setDrawsBackground:NO];
7806 WebView *webview([document webView]);
7807 [webview setShouldUpdateWhileOffscreen:NO];
7809 UIScrollView *scroller([dickbar_ scrollView]);
7810 [scroller setScrollingEnabled:NO];
7811 [scroller setFixedBackgroundPattern:YES];
7812 [scroller setBackgroundColor:[UIColor clearColor]];
7814 WebPreferences *preferences([webview preferences]);
7815 [preferences setCacheModel:WebCacheModelDocumentBrowser];
7816 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
7817 [preferences setOfflineWebApplicationCacheEnabled:YES];
7819 [dickbar_ loadRequest:[NSURLRequest
7820 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/dickbar/", UI_]]]
7821 cachePolicy:NSURLRequestUseProtocolCachePolicy
7825 UIEdgeInsets inset = {44, 0, 0, 0};
7826 [list_ setContentInset:inset];
7828 [dickbar_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7832 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7833 NSURL *url([request URL]);
7837 if ([frame isEqualToString:@"_open"])
7838 [delegate_ openURL:url];
7840 WebFrame *frame(nil);
7841 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7842 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7844 frame = [view mainFrame];
7846 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7848 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7849 [controller setDelegate:delegate_];
7850 [[self navigationController] pushViewController:controller animated:YES];
7856 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7857 return [CydiaWebViewController requestWithHeaders:request];
7860 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7861 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7864 - (void) setDelegate:(id)delegate {
7865 [super setDelegate:delegate];
7866 [cydia_ setDelegate:delegate];
7869 - (void) viewDidLoad {
7870 [super viewDidLoad];
7872 [[self navigationItem] setTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES"))];
7875 - (void) releaseSubviews {
7882 [super releaseSubviews];
7885 - (id) initWithDatabase:(Database *)database {
7886 if ((self = [super init]) != nil) {
7887 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7888 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7889 database_ = database;
7893 - (NSMutableArray *) _reloadPackages {
7894 @synchronized (database_) {
7895 era_ = [database_ era];
7896 NSArray *packages([database_ packages]);
7898 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7901 _profile(ChangesController$_reloadPackages$Filter)
7902 for (Package *package in packages)
7903 if ([package upgradableAndEssential:YES] || [package visible])
7904 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7907 _profile(ChangesController$_reloadPackages$radixSort)
7908 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7915 - (void) _reloadData {
7916 NSMutableArray *packages;
7920 UIProgressHUD *hud([delegate_ addProgressHUD]);
7921 [hud setText:UCLocalize("LOADING")];
7922 //NSLog(@"HUD:%@::%@", delegate_, hud);
7923 packages = [self yieldToSelector:@selector(_reloadPackages)];
7924 [delegate_ removeProgressHUD:hud];
7926 packages = [self _reloadPackages];
7929 @synchronized (database_) {
7930 if (era_ != [database_ era])
7933 packages_ = packages;
7934 sections_ = [NSMutableArray arrayWithCapacity:16];
7936 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7937 Section *ignored = nil;
7938 Section *section = nil;
7942 bool unseens = false;
7944 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7946 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7947 Package *package = [packages_ objectAtIndex:offset];
7949 BOOL uae = [package upgradableAndEssential:YES];
7953 time_t seen([package seen]);
7955 if (section == nil || last != seen) {
7959 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7962 _profile(ChangesController$reloadData$Allocate)
7963 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7964 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7965 [sections_ addObject:section];
7969 [section addToCount];
7970 } else if ([package ignored]) {
7971 if (ignored == nil) {
7972 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7974 [ignored addToCount];
7977 [upgradable addToCount];
7982 CFRelease(formatter);
7985 Section *last = [sections_ lastObject];
7986 size_t count = [last count];
7987 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7988 [sections_ removeLastObject];
7991 if ([ignored count] != 0)
7992 [sections_ insertObject:ignored atIndex:0];
7994 [sections_ insertObject:upgradable atIndex:0];
7998 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7999 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
8000 style:UIBarButtonItemStylePlain
8002 action:@selector(upgradeButtonClicked)
8003 ] autorelease]) animated:YES];
8005 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
8006 initWithTitle:UCLocalize("REFRESH")
8007 style:UIBarButtonItemStylePlain
8009 action:@selector(refreshButtonClicked)
8010 ] autorelease]) animated:YES];
8015 - (void) reloadData {
8017 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
8022 /* Search Controller {{{ */
8023 @interface SearchController : FilteredPackageListController <
8026 _H<UISearchBar, 1> search_;
8030 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
8031 - (void) reloadData;
8035 @implementation SearchController
8037 - (NSURL *) referrerURL {
8038 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
8041 - (NSURL *) navigationURL {
8042 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
8043 return [NSURL URLWithString:@"cydia://search"];
8045 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
8048 - (NSArray *) termsForQuery:(NSString *)query {
8049 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
8050 for (NSString *component in [query componentsSeparatedByString:@" "])
8051 if ([component length] != 0)
8052 [terms addObject:component];
8057 - (void) useSearch {
8058 [self setObject:[self termsForQuery:[search_ text]] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
8063 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
8064 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8069 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
8070 [search_ resignFirstResponder];
8074 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
8075 [search_ setText:@""];
8076 [self searchBarButtonClicked:searchBar];
8079 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
8080 [self searchBarButtonClicked:searchBar];
8083 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
8084 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8088 - (bool) shouldYield {
8092 - (bool) shouldBlock {
8093 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
8096 - (bool) isSummarized {
8097 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
8100 - (bool) showsSections {
8104 - (NSMutableArray *) _reloadPackages {
8105 NSMutableArray *packages([super _reloadPackages]);
8106 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8107 [packages radixSortUsingSelector:@selector(rank)];
8111 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
8112 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[self termsForQuery:query]])) {
8113 search_ = [[[UISearchBar alloc] init] autorelease];
8114 [search_ setDelegate:self];
8117 [search_ setText:query];
8121 - (void) viewDidAppear:(BOOL)animated {
8122 [super viewDidAppear:animated];
8124 if (!searchloaded_) {
8125 searchloaded_ = YES;
8126 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
8127 [search_ layoutSubviews];
8128 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
8130 UITextField *textField;
8131 if ([search_ respondsToSelector:@selector(searchField)])
8132 textField = [search_ searchField];
8134 textField = MSHookIvar<UITextField *>(search_, "_searchField");
8136 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8137 [textField setEnablesReturnKeyAutomatically:NO];
8138 [[self navigationItem] setTitleView:textField];
8141 if ([self isSummarized])
8142 [search_ becomeFirstResponder];
8145 - (void) reloadData {
8146 id object([search_ text]);
8147 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8148 object = [self termsForQuery:object];
8150 [self setObject:object];
8156 - (void) didSelectPackage:(Package *)package {
8157 [search_ resignFirstResponder];
8158 [super didSelectPackage:package];
8163 /* Package Settings Controller {{{ */
8164 @interface PackageSettingsController : CyteViewController <
8165 UITableViewDataSource,
8168 _transient Database *database_;
8170 _H<Package> package_;
8171 _H<UITableView, 2> table_;
8172 _H<UISwitch> subscribedSwitch_;
8173 _H<UISwitch> ignoredSwitch_;
8174 _H<UITableViewCell> subscribedCell_;
8175 _H<UITableViewCell> ignoredCell_;
8178 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
8182 @implementation PackageSettingsController
8184 - (NSURL *) navigationURL {
8185 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
8188 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8189 if (package_ == nil)
8192 if ([package_ installed] == nil)
8198 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8199 if (package_ == nil)
8202 // both sections contain just one item right now.
8206 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8210 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8212 return UCLocalize("SHOW_ALL_CHANGES_EX");
8214 return UCLocalize("IGNORE_UPGRADES_EX");
8217 - (void) onSubscribed:(id)control {
8218 bool value([control isOn]);
8219 if (package_ == nil)
8221 if ([package_ setSubscribed:value])
8222 [delegate_ updateData];
8225 - (void) _updateIgnored {
8226 const char *package([name_ UTF8String]);
8227 bool on([ignoredSwitch_ isOn]);
8229 pid_t pid(ExecFork());
8231 FILE *dpkg(popen("dpkg --set-selections", "w"));
8232 fwrite(package, strlen(package), 1, dpkg);
8235 fwrite(" hold\n", 6, 1, dpkg);
8237 fwrite(" install\n", 9, 1, dpkg);
8248 - (void) onIgnored:(id)control {
8249 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8250 [invocation setTarget:self];
8251 [invocation setSelector:@selector(_updateIgnored)];
8253 [delegate_ reloadDataWithInvocation:invocation];
8256 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8257 if (package_ == nil)
8260 switch ([indexPath section]) {
8261 case 0: return subscribedCell_;
8262 case 1: return ignoredCell_;
8271 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8272 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8273 [self setView:view];
8275 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8276 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8277 [(UITableView *) table_ setDataSource:self];
8278 [table_ setDelegate:self];
8279 [view addSubview:table_];
8281 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8282 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8283 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8285 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8286 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8287 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8289 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8290 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8291 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8292 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8294 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8295 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8296 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8297 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8300 - (void) viewDidLoad {
8301 [super viewDidLoad];
8303 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8306 - (void) releaseSubviews {
8308 subscribedCell_ = nil;
8310 ignoredSwitch_ = nil;
8311 subscribedSwitch_ = nil;
8313 [super releaseSubviews];
8316 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8317 if ((self = [super init]) != nil) {
8318 database_ = database;
8323 - (void) reloadData {
8326 package_ = [database_ packageWithName:name_];
8328 if (package_ != nil) {
8329 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8330 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8331 } // XXX: what now, G?
8333 [table_ reloadData];
8339 /* Installed Controller {{{ */
8340 @interface InstalledController : FilteredPackageListController {
8344 - (id) initWithDatabase:(Database *)database;
8346 - (void) updateRoleButton;
8347 - (void) queueStatusDidChange;
8351 @implementation InstalledController
8353 - (NSURL *) referrerURL {
8354 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8357 - (NSURL *) navigationURL {
8358 return [NSURL URLWithString:@"cydia://installed"];
8361 - (id) initWithDatabase:(Database *)database {
8362 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8363 [self updateRoleButton];
8364 [self queueStatusDidChange];
8369 - (void) queueButtonClicked {
8374 - (void) queueStatusDidChange {
8378 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8379 initWithTitle:UCLocalize("QUEUE")
8380 style:UIBarButtonItemStyleDone
8382 action:@selector(queueButtonClicked)
8385 [[self navigationItem] setLeftBarButtonItem:nil];
8391 - (void) updateRoleButton {
8392 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8393 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8394 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8395 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8397 action:@selector(roleButtonClicked)
8401 - (void) roleButtonClicked {
8402 [self setObject:[NSNumber numberWithBool:expert_]];
8406 [self updateRoleButton];
8412 /* Source Cell {{{ */
8413 @interface SourceCell : CyteTableViewCell <
8414 CyteTableViewCellDelegate
8418 _H<NSString> origin_;
8419 _H<NSString> label_;
8422 - (void) setSource:(Source *)source;
8426 @implementation SourceCell
8428 - (void) _setImage:(NSArray *)data {
8429 if ([url_ isEqual:[data objectAtIndex:0]]) {
8430 icon_ = [data objectAtIndex:1];
8431 [content_ setNeedsDisplay];
8435 - (void) _setSource:(NSURL *) url {
8436 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8438 if (NSData *data = [NSURLConnection
8439 sendSynchronousRequest:[NSURLRequest
8441 cachePolicy:NSURLRequestUseProtocolCachePolicy
8445 returningResponse:NULL
8448 if (UIImage *image = [UIImage imageWithData:data])
8449 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8454 - (void) setSource:(Source *)source {
8455 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8457 origin_ = [source name];
8458 label_ = [source rooturi];
8460 [content_ setNeedsDisplay];
8462 url_ = [source iconURL];
8463 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8466 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8467 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8468 UIView *content([self contentView]);
8469 CGRect bounds([content bounds]);
8471 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8472 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8473 [content_ setBackgroundColor:[UIColor whiteColor]];
8474 [content addSubview:content_];
8476 [content_ setDelegate:self];
8477 [content_ setOpaque:YES];
8479 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8483 - (NSString *) accessibilityLabel {
8487 - (void) drawContentRect:(CGRect)rect {
8488 bool highlighted(highlighted_);
8489 float width(rect.size.width);
8493 rect.size = [(UIImage *) icon_ size];
8495 while (rect.size.width > 32 || rect.size.height > 32) {
8496 rect.size.width /= 2;
8497 rect.size.height /= 2;
8500 rect.origin.x = 25 - rect.size.width / 2;
8501 rect.origin.y = 25 - rect.size.height / 2;
8503 [icon_ drawInRect:rect];
8511 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 65) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8515 [label_ drawAtPoint:CGPointMake(48, 29) forWidth:(width - 65) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8520 /* Source Controller {{{ */
8521 @interface SourceController : FilteredPackageListController {
8522 _transient Source *source_;
8526 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8530 @implementation SourceController
8532 - (NSURL *) referrerURL {
8533 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sources/%@", UI_, [key_ stringByAddingPercentEscapesIncludingReserved]]];
8536 - (NSURL *) navigationURL {
8537 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8540 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8541 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8543 key_ = [source key];
8547 - (void) reloadData {
8548 source_ = [database_ sourceWithKey:key_];
8549 key_ = [source_ key];
8550 [self setObject:source_];
8552 [[self navigationItem] setTitle:[source_ label]];
8559 /* Sources Controller {{{ */
8560 @interface SourcesController : CyteViewController <
8561 UITableViewDataSource,
8564 _transient Database *database_;
8567 _H<UITableView, 2> list_;
8568 _H<NSMutableArray> sources_;
8572 _H<UIProgressHUD> hud_;
8575 //NSURLConnection *installer_;
8576 NSURLConnection *trivial_;
8577 NSURLConnection *trivial_bz2_;
8578 NSURLConnection *trivial_gz_;
8579 //NSURLConnection *automatic_;
8584 - (id) initWithDatabase:(Database *)database;
8585 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8589 @implementation SourcesController
8591 - (void) _releaseConnection:(NSURLConnection *)connection {
8592 if (connection != nil) {
8593 [connection cancel];
8594 //[connection setDelegate:nil];
8595 [connection release];
8600 //[self _releaseConnection:installer_];
8601 [self _releaseConnection:trivial_];
8602 [self _releaseConnection:trivial_gz_];
8603 [self _releaseConnection:trivial_bz2_];
8604 //[self _releaseConnection:automatic_];
8609 - (NSURL *) navigationURL {
8610 return [NSURL URLWithString:@"cydia://sources"];
8613 - (void) viewDidAppear:(BOOL)animated {
8614 [super viewDidAppear:animated];
8615 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8618 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8622 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8626 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8627 return [sources_ count];
8630 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8631 @synchronized (database_) {
8632 if ([database_ era] != era_)
8635 NSUInteger index([indexPath row]);
8636 return index < [sources_ count] ? [sources_ objectAtIndex:index] : nil;
8639 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8640 static NSString *cellIdentifier = @"SourceCell";
8642 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8643 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8644 [cell setSource:[self sourceAtIndexPath:indexPath]];
8645 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8650 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8651 Source *source = [self sourceAtIndexPath:indexPath];
8652 if (source == nil) return;
8654 SourceController *controller = [[[SourceController alloc]
8655 initWithDatabase:database_
8659 [controller setDelegate:delegate_];
8661 [[self navigationController] pushViewController:controller animated:YES];
8664 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8665 Source *source = [self sourceAtIndexPath:indexPath];
8666 return [source record] != nil;
8669 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8670 if (editingStyle == UITableViewCellEditingStyleDelete) {
8671 Source *source = [self sourceAtIndexPath:indexPath];
8672 if (source == nil) return;
8674 [Sources_ removeObjectForKey:[source key]];
8675 [delegate_ _saveConfig];
8676 [delegate_ reloadDataWithInvocation:nil];
8681 [delegate_ addTrivialSource:href_];
8684 [delegate_ syncData];
8687 - (NSString *) getWarning {
8688 NSString *href(href_);
8689 NSRange colon([href rangeOfString:@"://"]);
8690 if (colon.location != NSNotFound)
8691 href = [href substringFromIndex:(colon.location + 3)];
8692 href = [href stringByAddingPercentEscapes];
8693 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8695 NSURL *url([NSURL URLWithString:href]);
8697 NSStringEncoding encoding;
8698 NSError *error(nil);
8700 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8701 return [warning length] == 0 ? nil : warning;
8705 - (void) _endConnection:(NSURLConnection *)connection {
8706 // XXX: the memory management in this method is horribly awkward
8708 NSURLConnection **field = NULL;
8709 if (connection == trivial_)
8711 else if (connection == trivial_bz2_)
8712 field = &trivial_bz2_;
8713 else if (connection == trivial_gz_)
8714 field = &trivial_gz_;
8715 _assert(field != NULL);
8716 [connection release];
8721 trivial_bz2_ == nil &&
8724 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8726 [delegate_ releaseNetworkActivityIndicator];
8728 [delegate_ removeProgressHUD:hud_];
8732 if (warning != nil) {
8733 UIAlertView *alert = [[[UIAlertView alloc]
8734 initWithTitle:UCLocalize("SOURCE_WARNING")
8737 cancelButtonTitle:UCLocalize("CANCEL")
8739 UCLocalize("ADD_ANYWAY"),
8743 [alert setContext:@"warning"];
8744 [alert setNumberOfRows:1];
8747 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8753 } else if (error_ != nil) {
8754 UIAlertView *alert = [[[UIAlertView alloc]
8755 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8756 message:[error_ localizedDescription]
8758 cancelButtonTitle:UCLocalize("OK")
8759 otherButtonTitles:nil
8762 [alert setContext:@"urlerror"];
8767 UIAlertView *alert = [[[UIAlertView alloc]
8768 initWithTitle:UCLocalize("NOT_REPOSITORY")
8769 message:UCLocalize("NOT_REPOSITORY_EX")
8771 cancelButtonTitle:UCLocalize("OK")
8772 otherButtonTitles:nil
8775 [alert setContext:@"trivial"];
8785 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8786 switch ([response statusCode]) {
8792 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8793 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8795 [self _endConnection:connection];
8798 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8799 [self _endConnection:connection];
8802 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8803 NSURL *url([NSURL URLWithString:href]);
8805 NSMutableURLRequest *request = [NSMutableURLRequest
8807 cachePolicy:NSURLRequestUseProtocolCachePolicy
8811 [request setHTTPMethod:method];
8813 if (Machine_ != NULL)
8814 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8816 if (UniqueID_ != nil)
8817 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8819 if ([url isCydiaSecure]) {
8820 if (UniqueID_ != nil)
8821 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8824 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8827 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8828 NSString *context([alert context]);
8830 if ([context isEqualToString:@"source"]) {
8833 NSString *href = [[alert textField] text];
8835 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8837 if (![href hasSuffix:@"/"])
8838 href_ = [href stringByAppendingString:@"/"];
8842 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8843 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8844 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8845 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8849 // XXX: this is stupid
8850 hud_ = [delegate_ addProgressHUD];
8851 [hud_ setText:UCLocalize("VERIFYING_URL")];
8852 [delegate_ retainNetworkActivityIndicator];
8861 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8862 } else if ([context isEqualToString:@"trivial"])
8863 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8864 else if ([context isEqualToString:@"urlerror"])
8865 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8866 else if ([context isEqualToString:@"warning"]) {
8869 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8878 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8883 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8884 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8885 [list_ setRowHeight:53];
8886 [(UITableView *) list_ setDataSource:self];
8887 [list_ setDelegate:self];
8888 [self setView:list_];
8891 - (void) viewDidLoad {
8892 [super viewDidLoad];
8894 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8895 [self updateButtonsForEditingStatusAnimated:NO];
8898 - (void) viewWillAppear:(BOOL)animated {
8899 [super viewWillAppear:animated];
8901 [list_ setEditing:NO];
8902 [self updateButtonsForEditingStatusAnimated:NO];
8905 - (void) releaseSubviews {
8910 [super releaseSubviews];
8913 - (id) initWithDatabase:(Database *)database {
8914 if ((self = [super init]) != nil) {
8915 database_ = database;
8919 - (void) reloadData {
8922 @synchronized (database_) {
8923 era_ = [database_ era];
8925 sources_ = [NSMutableArray arrayWithCapacity:16];
8926 [sources_ addObjectsFromArray:[database_ sources]];
8928 [sources_ sortUsingSelector:@selector(compareByName:)];
8931 int count([sources_ count]);
8933 for (int i = 0; i != count; i++) {
8934 if ([[sources_ objectAtIndex:i] record] == nil)
8942 - (void) showAddSourcePrompt {
8943 UIAlertView *alert = [[[UIAlertView alloc]
8944 initWithTitle:UCLocalize("ENTER_APT_URL")
8947 cancelButtonTitle:UCLocalize("CANCEL")
8949 UCLocalize("ADD_SOURCE"),
8953 [alert setContext:@"source"];
8955 [alert setNumberOfRows:1];
8956 [alert addTextFieldWithValue:@"http://" label:@""];
8958 UITextInputTraits *traits = [[alert textField] textInputTraits];
8959 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8960 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8961 [traits setKeyboardType:UIKeyboardTypeURL];
8962 // XXX: UIReturnKeyDone
8963 [traits setReturnKeyType:UIReturnKeyNext];
8968 - (void) addButtonClicked {
8969 [self showAddSourcePrompt];
8972 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8973 BOOL editing([list_ isEditing]);
8975 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8976 initWithTitle:UCLocalize("ADD")
8977 style:UIBarButtonItemStylePlain
8979 action:@selector(addButtonClicked)
8980 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8982 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8983 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8984 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8986 action:@selector(editButtonClicked)
8987 ] autorelease] animated:animated];
8989 if (IsWildcat_ && !editing)
8990 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8991 initWithTitle:UCLocalize("SETTINGS")
8992 style:UIBarButtonItemStylePlain
8994 action:@selector(settingsButtonClicked)
8998 - (void) settingsButtonClicked {
8999 [delegate_ showSettings];
9002 - (void) editButtonClicked {
9003 [list_ setEditing:![list_ isEditing] animated:YES];
9004 [self updateButtonsForEditingStatusAnimated:YES];
9010 /* Settings Controller {{{ */
9011 @interface SettingsController : CyteViewController <
9012 UITableViewDataSource,
9015 _transient Database *database_;
9016 // XXX: ok, "roledelegate_"?...
9017 _transient id roledelegate_;
9018 _H<UITableView, 2> table_;
9019 _H<UISegmentedControl> segment_;
9020 _H<UIView> container_;
9023 - (void) showDoneButton;
9024 - (void) resizeSegmentedControl;
9028 @implementation SettingsController
9031 table_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
9032 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9033 [table_ setDelegate:self];
9034 [(UITableView *) table_ setDataSource:self];
9035 [self setView:table_];
9037 NSArray *items = [NSArray arrayWithObjects:
9039 UCLocalize("HACKER"),
9040 UCLocalize("DEVELOPER"),
9042 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
9043 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
9044 [container_ addSubview:segment_];
9047 - (void) viewDidLoad {
9048 [super viewDidLoad];
9050 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
9053 if ([Role_ isEqualToString:@"User"]) index = 0;
9054 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
9055 if ([Role_ isEqualToString:@"Developer"]) index = 2;
9057 [segment_ setSelectedSegmentIndex:index];
9058 [self showDoneButton];
9061 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
9062 [self resizeSegmentedControl];
9065 - (void) releaseSubviews {
9070 [super releaseSubviews];
9073 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
9074 if ((self = [super init]) != nil) {
9075 database_ = database;
9076 roledelegate_ = delegate;
9080 - (void) resizeSegmentedControl {
9081 CGFloat width = [[self view] frame].size.width;
9082 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
9085 - (void) viewWillAppear:(BOOL)animated {
9086 [super viewWillAppear:animated];
9087 [self resizeSegmentedControl];
9090 - (void) viewDidAppear:(BOOL)animated {
9091 [super viewDidAppear:animated];
9092 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
9093 [self resizeSegmentedControl];
9096 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
9097 [self resizeSegmentedControl];
9100 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
9101 [self resizeSegmentedControl];
9105 NSString *role(nil);
9107 switch ([segment_ selectedSegmentIndex]) {
9108 case 0: role = @"User"; break;
9109 case 1: role = @"Hacker"; break;
9110 case 2: role = @"Developer"; break;
9115 if (![role isEqualToString:Role_]) {
9116 bool rolling(Role_ == nil);
9119 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
9123 [Metadata_ setObject:Settings_ forKey:@"Settings"];
9127 [roledelegate_ loadData];
9129 [roledelegate_ updateData];
9133 - (void) segmentChanged:(UISegmentedControl *)control {
9134 [self showDoneButton];
9137 - (void) saveAndClose {
9140 [[self navigationItem] setRightBarButtonItem:nil];
9141 [[self navigationController] dismissModalViewControllerAnimated:YES];
9144 - (void) doneButtonClicked {
9145 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
9146 [spinner startAnimating];
9147 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
9148 [[self navigationItem] setRightBarButtonItem:spinItem];
9150 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
9153 - (void) showDoneButton {
9154 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
9155 initWithTitle:UCLocalize("DONE")
9156 style:UIBarButtonItemStyleDone
9158 action:@selector(doneButtonClicked)
9159 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
9162 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
9163 // XXX: For not having a single cell in the table, this sure is a lot of sections.
9167 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
9171 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
9172 return nil; // This method is required by the protocol.
9175 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
9177 return UCLocalize("ROLE_EX");
9179 return [NSString stringWithFormat:
9180 @"%@: %@\n%@: %@\n%@: %@",
9181 UCLocalize("USER"), UCLocalize("USER_EX"),
9182 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
9183 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
9188 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
9189 return section == 3 ? 44.0f : 0;
9192 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
9193 return section == 3 ? container_ : nil;
9196 - (void) reloadData {
9199 [table_ reloadData];
9204 /* Stash Controller {{{ */
9205 @interface StashController : CyteViewController {
9206 _H<UIActivityIndicatorView> spinner_;
9207 _H<UILabel> status_;
9208 _H<UILabel> caption_;
9213 @implementation StashController
9216 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
9217 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
9218 [self setView:view];
9220 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
9222 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
9223 CGRect spinrect = [spinner_ frame];
9224 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
9225 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
9226 [spinner_ setFrame:spinrect];
9227 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
9228 [view addSubview:spinner_];
9229 [spinner_ startAnimating];
9232 captrect.size.width = [[self view] frame].size.width;
9233 captrect.size.height = 40.0f;
9234 captrect.origin.x = 0;
9235 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
9236 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
9237 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
9238 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9239 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
9240 [caption_ setTextColor:[UIColor whiteColor]];
9241 [caption_ setBackgroundColor:[UIColor clearColor]];
9242 [caption_ setShadowColor:[UIColor blackColor]];
9243 [caption_ setTextAlignment:UITextAlignmentCenter];
9244 [view addSubview:caption_];
9247 statusrect.size.width = [[self view] frame].size.width;
9248 statusrect.size.height = 30.0f;
9249 statusrect.origin.x = 0;
9250 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
9251 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
9252 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9253 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
9254 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
9255 [status_ setTextColor:[UIColor whiteColor]];
9256 [status_ setBackgroundColor:[UIColor clearColor]];
9257 [status_ setShadowColor:[UIColor blackColor]];
9258 [status_ setTextAlignment:UITextAlignmentCenter];
9259 [view addSubview:status_];
9262 - (void) releaseSubviews {
9267 [super releaseSubviews];
9273 @interface CYURLCache : SDURLCache {
9278 @implementation CYURLCache
9280 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
9283 else if ([event isEqualToString:@"no-cache"])
9285 else if ([event isEqualToString:@"store"])
9287 else if ([event isEqualToString:@"invalid"])
9289 else if ([event isEqualToString:@"memory"])
9291 else if ([event isEqualToString:@"disk"])
9293 else if ([event isEqualToString:@"miss"])
9296 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
9300 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
9301 if (NSURLResponse *response = [cached response])
9302 if (NSString *mime = [response MIMEType])
9303 if ([mime isEqualToString:@"text/cache-manifest"]) {
9304 NSURL *url([response URL]);
9307 NSLog(@"###: %@", [url absoluteString]);
9310 @synchronized (HostConfig_) {
9311 [CachedURLs_ addObject:url];
9315 [super storeCachedResponse:cached forRequest:request];
9320 @interface Cydia : UIApplication <
9321 ConfirmationControllerDelegate,
9324 UINavigationControllerDelegate,
9325 UITabBarControllerDelegate
9327 _H<UIWindow> window_;
9328 _H<CYTabBarController> tabbar_;
9329 _H<CydiaLoadingViewController> emulated_;
9331 _H<NSMutableArray> essential_;
9332 _H<NSMutableArray> broken_;
9334 Database *database_;
9336 _H<NSURL> starturl_;
9341 _H<StashController> stash_;
9350 @implementation Cydia
9352 - (void) lockSuspend {
9353 if (locked_++ == 0) {
9354 if ($SBSSetInterceptsMenuButtonForever != NULL)
9355 (*$SBSSetInterceptsMenuButtonForever)(true);
9359 - (void) unlockSuspend {
9360 if (--locked_ == 0) {
9361 if ($SBSSetInterceptsMenuButtonForever != NULL)
9362 (*$SBSSetInterceptsMenuButtonForever)(false);
9366 - (void) beginUpdate {
9367 [tabbar_ beginUpdate];
9371 return [tabbar_ updating];
9375 if ([broken_ count] != 0) {
9376 int count = [broken_ count];
9378 UIAlertView *alert = [[[UIAlertView alloc]
9379 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9380 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9382 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9384 UCLocalize("TEMPORARY_IGNORE"),
9388 [alert setContext:@"fixhalf"];
9389 [alert setNumberOfRows:2];
9391 } else if (!Ignored_ && [essential_ count] != 0) {
9392 int count = [essential_ count];
9394 UIAlertView *alert = [[[UIAlertView alloc]
9395 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9396 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9398 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9400 UCLocalize("UPGRADE_ESSENTIAL"),
9401 UCLocalize("COMPLETE_UPGRADE"),
9405 [alert setContext:@"upgrade"];
9410 - (void) returnToCydia {
9414 - (void) _saveConfig {
9415 @synchronized (database_) {
9422 NSString *error(nil);
9424 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9426 NSError *error(nil);
9427 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9428 NSLog(@"failure to save metadata data: %@", error);
9433 NSLog(@"failure to serialize metadata: %@", error);
9437 CydiaWriteSources();
9440 // Navigation controller for the queuing badge.
9441 - (UINavigationController *) queueNavigationController {
9442 NSArray *controllers = [tabbar_ viewControllers];
9443 return [controllers objectAtIndex:3];
9446 - (void) unloadData {
9447 [tabbar_ unloadData];
9450 - (void) _updateData {
9454 UINavigationController *navigation = [self queueNavigationController];
9456 id queuedelegate = nil;
9457 if ([[navigation viewControllers] count] > 0)
9458 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9460 [queuedelegate queueStatusDidChange];
9461 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9464 - (void) _refreshIfPossible:(NSDate *)update {
9465 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9467 bool recently = false;
9468 if (update != nil) {
9469 NSTimeInterval interval([update timeIntervalSinceNow]);
9470 if (interval <= 0 && interval > -(15*60))
9474 // Don't automatic refresh if:
9475 // - We already refreshed recently.
9476 // - We already auto-refreshed this launch.
9477 // - Auto-refresh is disabled.
9478 // - Cydia's server is not reachable
9479 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9480 // If we are cancelling, we need to make sure it knows it's already loaded.
9483 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9485 // We are going to load, so remember that.
9488 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9494 - (void) refreshIfPossible {
9495 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9498 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9499 @synchronized (self) {
9500 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9501 [hud setText:UCLocalize("RELOADING_DATA")];
9503 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9507 [essential_ removeAllObjects];
9508 [broken_ removeAllObjects];
9510 NSArray *packages([database_ packages]);
9511 for (Package *package in packages) {
9513 [broken_ addObject:package];
9514 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9515 if ([package essential] && [package installed] != nil)
9516 [essential_ addObject:package];
9521 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9524 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9525 [changesItem setBadgeValue:badge];
9526 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9527 [self setApplicationIconBadgeNumber:changes];
9530 [changesItem setBadgeValue:nil];
9531 [changesItem setAnimatedBadge:NO];
9532 [self setApplicationIconBadgeNumber:0];
9538 [self removeProgressHUD:hud];
9541 - (void) updateData {
9545 - (void) updateDataAndLoad {
9547 if ([database_ progressDelegate] == nil)
9553 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9556 - (void) disemulate {
9557 if (emulated_ == nil)
9560 [window_ addSubview:[tabbar_ view]];
9561 [[emulated_ view] removeFromSuperview];
9563 [window_ setUserInteractionEnabled:YES];
9566 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9567 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9569 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9571 UIViewController *parent;
9572 if (emulated_ == nil)
9581 [parent presentModalViewController:navigation animated:YES];
9584 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9585 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9587 if (navigation != nil)
9588 [navigation pushViewController:progress animated:YES];
9590 [self presentModalViewController:progress force:YES];
9592 [progress invoke:invocation withTitle:title];
9596 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9597 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9600 - (void) repairWithInvocation:(NSInvocation *)invocation {
9602 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9606 - (void) repairWithSelector:(SEL)selector {
9607 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9610 - (void) reloadData {
9611 [self reloadDataWithInvocation:nil];
9612 if ([database_ progressDelegate] == nil)
9618 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9621 - (void) addSource:(NSDictionary *) source {
9622 CydiaAddSource(source);
9625 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9626 CydiaAddSource(href, distribution, sections);
9629 - (void) addTrivialSource:(NSString *)href {
9630 CydiaAddSource(href, @"./");
9633 - (void) updateValues {
9638 pkgProblemResolver *resolver = [database_ resolver];
9640 resolver->InstallProtect();
9641 if (!resolver->Resolve(true))
9646 // XXX: this is a really crappy way of doing this.
9647 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9648 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9649 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9650 if ([tabbar_ updating])
9651 [tabbar_ cancelUpdate];
9653 if (![database_ prepare])
9656 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9657 [page setDelegate:self];
9658 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9661 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9662 [tabbar_ presentModalViewController:confirm_ animated:YES];
9668 @synchronized (self) {
9673 - (void) clearPackage:(Package *)package {
9674 @synchronized (self) {
9681 - (void) installPackages:(NSArray *)packages {
9682 @synchronized (self) {
9683 for (Package *package in packages)
9690 - (void) installPackage:(Package *)package {
9691 @synchronized (self) {
9698 - (void) removePackage:(Package *)package {
9699 @synchronized (self) {
9706 - (void) distUpgrade {
9707 @synchronized (self) {
9708 if (![database_ upgrade])
9716 system("su -c /usr/bin/uicache mobile");
9721 UIProgressHUD *hud([self addProgressHUD]);
9722 [hud setText:UCLocalize("LOADING")];
9723 [self yieldToSelector:@selector(_uicache)];
9724 [self removeProgressHUD:hud];
9728 [database_ perform];
9729 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9730 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9733 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9736 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9737 [self unlockSuspend];
9740 - (void) showSettings {
9741 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9744 - (void) retainNetworkActivityIndicator {
9745 if (activity_++ == 0)
9746 [self setNetworkActivityIndicatorVisible:YES];
9749 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9753 - (void) releaseNetworkActivityIndicator {
9754 if (--activity_ == 0)
9755 [self setNetworkActivityIndicatorVisible:NO];
9758 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9763 - (void) cancelAndClear:(bool)clear {
9764 @synchronized (self) {
9776 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9777 NSString *context([alert context]);
9779 if ([context isEqualToString:@"conffile"]) {
9780 FILE *input = [database_ input];
9781 if (button == [alert cancelButtonIndex])
9782 fprintf(input, "N\n");
9783 else if (button == [alert firstOtherButtonIndex])
9784 fprintf(input, "Y\n");
9787 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9788 } else if ([context isEqualToString:@"fixhalf"]) {
9789 if (button == [alert cancelButtonIndex]) {
9790 @synchronized (self) {
9791 for (Package *broken in (id) broken_) {
9794 NSString *id = [broken id];
9795 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9796 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9797 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9798 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9804 } else if (button == [alert firstOtherButtonIndex]) {
9805 [broken_ removeAllObjects];
9809 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9810 } else if ([context isEqualToString:@"upgrade"]) {
9811 if (button == [alert firstOtherButtonIndex]) {
9812 @synchronized (self) {
9813 for (Package *essential in (id) essential_)
9814 [essential install];
9819 } else if (button == [alert firstOtherButtonIndex] + 1) {
9821 } else if (button == [alert cancelButtonIndex]) {
9825 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9829 - (void) system:(NSString *)command {
9830 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9833 system([command UTF8String]);
9839 - (void) applicationWillSuspend {
9841 [super applicationWillSuspend];
9844 - (BOOL) isSafeToSuspend {
9847 NSLog(@"isSafeToSuspend: locked_ != 0");
9852 // Use external process status API internally.
9853 // This is probably a really bad idea.
9854 // XXX: what is the point of this? does this solve anything at all?
9855 uint64_t status = 0;
9857 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9858 notify_get_state(notify_token, &status);
9859 notify_cancel(notify_token);
9864 NSLog(@"isSafeToSuspend: status != 0");
9870 NSLog(@"isSafeToSuspend: -> true");
9875 - (void) applicationSuspend:(__GSEvent *)event {
9876 if ([self isSafeToSuspend])
9877 [super applicationSuspend:event];
9880 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9881 if ([self isSafeToSuspend])
9882 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9885 - (void) _setSuspended:(BOOL)value {
9886 if ([self isSafeToSuspend])
9887 [super _setSuspended:value];
9890 - (UIProgressHUD *) addProgressHUD {
9891 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9892 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9894 [window_ setUserInteractionEnabled:NO];
9896 UIViewController *target(tabbar_);
9897 if (UIViewController *modal = [target modalViewController])
9900 [hud showInView:[target view]];
9906 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9907 [self unlockSuspend];
9909 [hud removeFromSuperview];
9910 [window_ setUserInteractionEnabled:YES];
9913 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9914 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9917 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9918 NSString *scheme([[url scheme] lowercaseString]);
9919 if ([[url absoluteString] length] <= [scheme length] + 3)
9921 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9922 NSArray *components([path componentsSeparatedByString:@"/"]);
9924 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9925 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9926 if (controller != nil)
9927 [controller setDelegate:self];
9931 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9934 NSString *base([components objectAtIndex:0]);
9936 CyteViewController *controller = nil;
9938 if ([base isEqualToString:@"url"]) {
9939 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9940 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9941 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9942 } else if (!external && [components count] == 1) {
9943 if ([base isEqualToString:@"manage"]) {
9944 controller = [[[ManageController alloc] init] autorelease];
9947 if ([base isEqualToString:@"storage"]) {
9948 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9951 if ([base isEqualToString:@"sources"]) {
9952 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9955 if ([base isEqualToString:@"home"]) {
9956 controller = [[[HomeController alloc] init] autorelease];
9959 if ([base isEqualToString:@"sections"]) {
9960 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9963 if ([base isEqualToString:@"search"]) {
9964 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9967 if ([base isEqualToString:@"changes"]) {
9968 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9971 if ([base isEqualToString:@"installed"]) {
9972 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9974 } else if ([components count] == 2) {
9975 NSString *argument = [components objectAtIndex:1];
9977 if ([base isEqualToString:@"package"]) {
9978 controller = [self pageForPackage:argument withReferrer:referrer];
9981 if (!external && [base isEqualToString:@"search"]) {
9982 controller = [[[SearchController alloc] initWithDatabase:database_ query:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9985 if (!external && [base isEqualToString:@"sections"]) {
9986 if ([argument isEqualToString:@"all"])
9988 controller = [[[SectionController alloc] initWithDatabase:database_ section:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9991 if (!external && [base isEqualToString:@"sources"]) {
9992 if ([argument isEqualToString:@"add"]) {
9993 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9994 [(SourcesController *)controller showAddSourcePrompt];
9996 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9997 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
10001 if (!external && [base isEqualToString:@"launch"]) {
10002 [self launchApplicationWithIdentifier:argument suspended:NO];
10005 } else if (!external && [components count] == 3) {
10006 NSString *arg1 = [components objectAtIndex:1];
10007 NSString *arg2 = [components objectAtIndex:2];
10009 if ([base isEqualToString:@"package"]) {
10010 if ([arg2 isEqualToString:@"settings"]) {
10011 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
10012 } else if ([arg2 isEqualToString:@"files"]) {
10013 if (Package *package = [database_ packageWithName:arg1]) {
10014 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
10015 [(FileTable *)controller setPackage:package];
10021 [controller setDelegate:self];
10025 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
10026 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
10029 [tabbar_ setUnselectedViewController:page];
10031 return page != nil;
10034 - (void) applicationOpenURL:(NSURL *)url {
10035 [super applicationOpenURL:url];
10040 [self openCydiaURL:url forExternal:YES];
10043 - (void) applicationWillResignActive:(UIApplication *)application {
10044 // Stop refreshing if you get a phone call or lock the device.
10045 if ([tabbar_ updating])
10046 [tabbar_ cancelUpdate];
10048 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
10049 [super applicationWillResignActive:application];
10052 - (void) saveState {
10053 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
10054 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
10055 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
10058 [self _saveConfig];
10061 - (void) applicationWillTerminate:(UIApplication *)application {
10065 - (void) setConfigurationData:(NSString *)data {
10066 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
10068 if (!conffile_r(data)) {
10069 lprintf("E:invalid conffile\n");
10073 NSString *ofile = conffile_r[1];
10074 //NSString *nfile = conffile_r[2];
10076 UIAlertView *alert = [[[UIAlertView alloc]
10077 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
10078 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
10080 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
10082 UCLocalize("ACCEPT_NEW_COPY"),
10083 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
10087 [alert setContext:@"conffile"];
10088 [alert setNumberOfRows:2];
10092 - (void) addStashController {
10093 [self lockSuspend];
10094 stash_ = [[[StashController alloc] init] autorelease];
10095 [window_ addSubview:[stash_ view]];
10098 - (void) removeStashController {
10099 [[stash_ view] removeFromSuperview];
10101 [self unlockSuspend];
10105 [self setIdleTimerDisabled:YES];
10107 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
10108 UpdateExternalStatus(1);
10109 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
10110 UpdateExternalStatus(0);
10112 [self removeStashController];
10114 pid_t pid(ExecFork());
10116 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
10117 perror("launchctl stop");
10124 - (void) setupViewControllers {
10125 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
10127 NSMutableArray *items([NSMutableArray arrayWithObjects:
10128 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
10129 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
10130 [[[UITabBarItem alloc] initWithTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES")) image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
10131 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
10135 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
10136 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10138 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10141 NSMutableArray *controllers([NSMutableArray array]);
10142 for (UITabBarItem *item in items) {
10143 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
10144 [controller setTabBarItem:item];
10145 [controllers addObject:controller];
10147 [tabbar_ setViewControllers:controllers];
10149 [tabbar_ setUpdateDelegate:self];
10152 - (void) _sendMemoryWarningNotification {
10153 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
10154 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
10156 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
10159 - (void) _sendMemoryWarningNotifications {
10161 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
10167 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
10169 [[NSURLCache sharedURLCache] removeAllCachedResponses];
10172 - (void) applicationDidFinishLaunching:(id)unused {
10173 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
10176 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
10177 [self setApplicationSupportsShakeToEdit:NO];
10179 @synchronized (HostConfig_) {
10180 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
10183 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
10184 initWithMemoryCapacity:524288
10185 diskCapacity:10485760
10186 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
10189 [CydiaWebViewController _initialize];
10191 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
10193 // this would disallow http{,s} URLs from accessing this data
10194 //[WebView registerURLSchemeAsLocal:@"cydia"];
10196 Font12_ = [UIFont systemFontOfSize:12];
10197 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
10198 Font14_ = [UIFont systemFontOfSize:14];
10199 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
10200 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
10202 essential_ = [NSMutableArray arrayWithCapacity:4];
10203 broken_ = [NSMutableArray arrayWithCapacity:4];
10205 // XXX: I really need this thing... like, seriously... I'm sorry
10206 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
10208 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
10209 [window_ orderFront:self];
10210 [window_ makeKey:self];
10211 [window_ setHidden:NO];
10213 if (false) stash: {
10214 [self addStashController];
10215 // XXX: this would be much cleaner as a yieldToSelector:
10216 // that way the removeStashController could happen right here inline
10217 // we also could no longer require the useless stash_ field anymore
10218 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
10223 int error(stat("/", &root));
10224 _assert(error != -1);
10226 #define Stash_(path) do { \
10227 struct stat folder; \
10228 int error(lstat((path), &folder)); \
10229 if (error != -1 && ( \
10230 folder.st_dev == root.st_dev && \
10231 S_ISDIR(folder.st_mode) \
10232 ) || error == -1 && ( \
10233 errno == ENOENT || \
10238 Stash_("/Applications");
10239 Stash_("/Library/Ringtones");
10240 Stash_("/Library/Wallpaper");
10241 //Stash_("/usr/bin");
10242 Stash_("/usr/include");
10243 Stash_("/usr/lib/pam");
10244 Stash_("/usr/libexec");
10245 Stash_("/usr/share");
10246 //Stash_("/var/lib");
10248 database_ = [Database sharedInstance];
10249 [database_ setDelegate:self];
10251 [window_ setUserInteractionEnabled:NO];
10252 [self setupViewControllers];
10254 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
10255 [window_ addSubview:[emulated_ view]];
10257 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
10261 - (NSArray *) defaultStartPages {
10262 NSMutableArray *standard = [NSMutableArray array];
10263 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
10264 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
10265 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
10267 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
10269 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
10270 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
10272 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10276 - (void) loadData {
10278 if (Role_ == nil) {
10279 [window_ setUserInteractionEnabled:YES];
10280 [self showSettings];
10283 if ([emulated_ modalViewController] != nil)
10284 [emulated_ dismissModalViewControllerAnimated:YES];
10285 [window_ setUserInteractionEnabled:NO];
10288 [self reloadDataWithInvocation:nil];
10289 [self refreshIfPossible];
10294 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
10295 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
10296 int standardIndex = 0;
10297 NSArray *standard = [self defaultStartPages];
10304 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
10305 if (valid && closed != nil) {
10306 NSTimeInterval interval([closed timeIntervalSinceNow]);
10307 // XXX: Is 30 minutes the optimal time here?
10308 if (interval <= -(30*60))
10312 if (valid && [saved count] != [standard count])
10316 for (unsigned int i = 0; i < [standard count]; i++) {
10317 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10318 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10319 // but it's good enough for now.
10320 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10327 NSArray *items = nil;
10329 [tabbar_ setSelectedIndex:savedIndex];
10332 [tabbar_ setSelectedIndex:standardIndex];
10336 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10337 NSArray *stack = [items objectAtIndex:tab];
10338 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10339 NSMutableArray *current = [NSMutableArray array];
10341 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10342 NSString *addr = [stack objectAtIndex:nav];
10343 NSURL *url = [NSURL URLWithString:addr];
10344 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10346 [current addObject:page];
10349 [navigation setViewControllers:current];
10352 // (Try to) show the startup URL.
10353 if (starturl_ != nil) {
10354 [self openCydiaURL:starturl_ forExternal:NO];
10359 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10360 if (item != nil && IsWildcat_) {
10361 [sheet showFromBarButtonItem:item animated:YES];
10363 [sheet showInView:window_];
10367 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10368 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10369 [progress setTitle:task];
10370 [progress addProgressEvent:event];
10373 - (void) addProgressEventForTask:(NSArray *)data {
10374 CydiaProgressEvent *event([data objectAtIndex:0]);
10375 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10376 [self addProgressEvent:event forTask:task];
10379 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10380 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10386 id Alloc_(id self, SEL selector) {
10387 id object = alloc_(self, selector);
10388 lprintf("[%s]A-%p\n", self->isa->name, object);
10393 id Dealloc_(id self, SEL selector) {
10394 id object = dealloc_(self, selector);
10395 lprintf("[%s]D-%p\n", self->isa->name, object);
10399 static NSSet *MobilizedFiles_;
10401 static NSURL *MobilizeURL(NSURL *url) {
10402 NSString *path([url path]);
10403 if ([path hasPrefix:@"/var/root/"]) {
10404 NSString *file([path substringFromIndex:10]);
10405 if ([MobilizedFiles_ containsObject:file])
10406 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10412 Class $CFXPreferencesPropertyListSource;
10413 @class CFXPreferencesPropertyListSource;
10415 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10416 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10417 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10418 url = MobilizeURL(url);
10419 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10420 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10426 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10427 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10428 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10429 url = MobilizeURL(url);
10430 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10431 //NSLog(@"%@ %@", [url absoluteString], value);
10437 Class $NSURLConnection;
10439 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10440 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10442 NSURL *url([copy URL]);
10444 NSString *host([url host]);
10445 NSString *scheme([[url scheme] lowercaseString]);
10447 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10449 @synchronized (HostConfig_) {
10450 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10451 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10452 [copy setHTTPShouldUsePipelining:YES];
10454 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10455 if ([control isEqualToString:@"max-age=0"])
10456 if ([CachedURLs_ containsObject:url]) {
10458 NSLog(@"~~~: %@", url);
10461 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10463 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10464 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10465 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10469 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10475 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10476 CGSize size([[UIScreen mainScreen] bounds].size);
10477 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10478 if ([$WAKWindow hasLandscapeOrientation])
10479 std::swap(size.width, size.height);*/
10483 int main(int argc, char *argv[]) {
10484 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10488 UpdateExternalStatus(0);
10490 if (Class $UIDevice = objc_getClass("UIDevice")) {
10491 UIDevice *device([$UIDevice currentDevice]);
10492 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10494 IsWildcat_ = false;
10496 UIScreen *screen([UIScreen mainScreen]);
10497 if ([screen respondsToSelector:@selector(scale)])
10498 ScreenScale_ = [screen scale];
10502 UIDevice *device([UIDevice currentDevice]);
10503 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10504 Idiom_ = @"iphone";
10506 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10507 if (idiom == UIUserInterfaceIdiomPhone)
10508 Idiom_ = @"iphone";
10509 else if (idiom == UIUserInterfaceIdiomPad)
10512 NSLog(@"unknown UIUserInterfaceIdiom!");
10515 Pcre pattern("^([0-9]+\\.[0-9]+)");
10517 if (pattern([device systemVersion]))
10518 Firmware_ = pattern[1];
10519 if (pattern(Cydia_))
10520 Major_ = pattern[1];
10522 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10524 HostConfig_ = [[[NSObject alloc] init] autorelease];
10525 @synchronized (HostConfig_) {
10526 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10527 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10528 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10529 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10530 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10533 NSString *ui(@"ui/ios");
10535 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10536 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10537 UI_ = CydiaURL(ui);
10539 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10541 MobilizedFiles_ = [NSMutableSet setWithObjects:
10542 @"Library/Preferences/com.apple.Accessibility.plist",
10543 @"Library/Preferences/com.apple.preferences.sounds.plist",
10546 /* Library Hacks {{{ */
10547 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10549 $WAKWindow = objc_getClass("WAKWindow");
10550 if ($WAKWindow != NULL)
10551 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10552 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10554 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10556 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10557 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10558 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10559 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10562 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10563 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10564 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10565 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10568 $NSURLConnection = objc_getClass("NSURLConnection");
10569 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10570 if (NSURLConnection$init$ != NULL) {
10571 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10572 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10575 /* Set Locale {{{ */
10576 Locale_ = CFLocaleCopyCurrent();
10577 Languages_ = [NSLocale preferredLanguages];
10579 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10580 //NSLog(@"%@", [Languages_ description]);
10583 if (Locale_ != NULL)
10584 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10585 else if (Languages_ != nil && [Languages_ count] != 0)
10586 lang = [[Languages_ objectAtIndex:0] UTF8String];
10588 // XXX: consider just setting to C and then falling through?
10591 if (lang != NULL) {
10592 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10593 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10596 NSLog(@"Setting Language: %s", lang);
10598 if (lang != NULL) {
10599 setenv("LANG", lang, true);
10600 std::setlocale(LC_ALL, lang);
10604 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10606 /* Parse Arguments {{{ */
10607 bool substrate(false);
10613 for (int argi(1); argi != argc; ++argi)
10614 if (strcmp(argv[argi], "--") == 0) {
10616 argv[argi] = argv[0];
10622 for (int argi(1); argi != arge; ++argi)
10623 if (strcmp(args[argi], "--substrate") == 0)
10626 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10630 App_ = [[NSBundle mainBundle] bundlePath];
10636 system("mkdir -p /var/root/Library/Keyboard; cp -af /var/mobile/Library/Keyboard/UserDictionary.sqlite /var/root/Library/Keyboard/");
10638 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10639 alloc_ = alloc->method_imp;
10640 alloc->method_imp = (IMP) &Alloc_;*/
10642 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10643 dealloc_ = dealloc->method_imp;
10644 dealloc->method_imp = (IMP) &Dealloc_;*/
10646 /* System Information {{{ */
10650 size = sizeof(maxproc);
10651 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10652 perror("sysctlbyname(\"kern.maxproc\", ?)");
10653 else if (maxproc < 64) {
10655 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10656 perror("sysctlbyname(\"kern.maxproc\", #)");
10659 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10660 char *osversion = new char[size];
10661 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10662 perror("sysctlbyname(\"kern.osversion\", ?)");
10664 System_ = [NSString stringWithUTF8String:osversion];
10666 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10667 char *machine = new char[size];
10668 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10669 perror("sysctlbyname(\"hw.machine\", ?)");
10671 Machine_ = machine;
10673 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10674 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10675 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10677 UniqueID_ = [device uniqueIdentifier];
10679 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10680 Product_ = [info objectForKey:@"SafariProductVersion"];
10681 Safari_ = [info objectForKey:@"CFBundleVersion"];
10684 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10686 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10687 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10688 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10689 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10690 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10691 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10693 UserAgent_ = agent;
10695 /* Load Database {{{ */
10697 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10699 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10701 if (Metadata_ == NULL)
10702 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10704 Settings_ = [Metadata_ objectForKey:@"Settings"];
10706 Packages_ = [Metadata_ objectForKey:@"Packages"];
10708 Values_ = [Metadata_ objectForKey:@"Values"];
10709 Sections_ = [Metadata_ objectForKey:@"Sections"];
10710 Sources_ = [Metadata_ objectForKey:@"Sources"];
10712 Token_ = [Metadata_ objectForKey:@"Token"];
10714 Version_ = [Metadata_ objectForKey:@"Version"];
10717 if (Settings_ != nil)
10718 Role_ = [Settings_ objectForKey:@"Role"];
10720 if (Values_ == nil) {
10721 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10722 [Metadata_ setObject:Values_ forKey:@"Values"];
10725 if (Sections_ == nil) {
10726 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10727 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10730 if (Sources_ == nil) {
10731 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10732 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10735 if (Version_ == nil) {
10736 Version_ = [NSNumber numberWithUnsignedInt:0];
10737 [Metadata_ setObject:Version_ forKey:@"Version"];
10740 if ([Version_ unsignedIntValue] == 0) {
10741 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10742 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10743 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10744 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10746 Version_ = [NSNumber numberWithUnsignedInt:1];
10747 [Metadata_ setObject:Version_ forKey:@"Version"];
10749 [Metadata_ removeObjectForKey:@"LastUpdate"];
10755 CydiaWriteSources();
10758 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10761 if (Packages_ != nil) {
10763 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10767 [Metadata_ removeObjectForKey:@"Packages"];
10773 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10775 #define MobileSubstrate_(name) \
10776 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10777 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10778 if (handle == NULL) \
10779 NSLog(@"%s", dlerror()); \
10782 MobileSubstrate_(Activator)
10783 MobileSubstrate_(libstatusbar)
10784 MobileSubstrate_(SimulatedKeyEvents)
10785 MobileSubstrate_(WinterBoard)
10787 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10788 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10790 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10792 if (access("/User", F_OK) != 0 || version != 6) {
10794 system("/usr/libexec/cydia/firmware.sh");
10798 _assert([[NSFileManager defaultManager]
10799 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10800 withIntermediateDirectories:YES
10805 if (access("/tmp/cydia.chk", F_OK) == 0) {
10806 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10807 _assert(errno == ENOENT);
10808 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10809 _assert(errno == ENOENT);
10812 /* APT Initialization {{{ */
10813 _assert(pkgInitConfig(*_config));
10814 _assert(pkgInitSystem(*_config, _system));
10817 _config->Set("APT::Acquire::Translation", lang);
10819 // XXX: this timeout might be important :(
10820 //_config->Set("Acquire::http::Timeout", 15);
10822 _config->Set("Acquire::http::MaxParallel", 3);
10824 /* Color Choices {{{ */
10825 space_ = CGColorSpaceCreateDeviceRGB();
10827 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10828 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10829 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10830 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10831 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10832 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10833 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10834 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10835 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10837 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10838 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10840 /* UIKit Configuration {{{ */
10841 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10842 if ($GSFontSetUseLegacyFontMetrics != NULL)
10843 $GSFontSetUseLegacyFontMetrics(YES);
10845 // XXX: I have a feeling this was important
10846 //UIKeyboardDisableAutomaticAppearance();
10849 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10851 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemHasCapability"));
10852 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10854 ShowPromoted_ = fast;
10855 PulseInterval_ = fast ? 50000 : 500000;
10857 Colon_ = UCLocalize("COLON_DELIMITED");
10858 Elision_ = UCLocalize("ELISION");
10859 Error_ = UCLocalize("ERROR");
10860 Warning_ = UCLocalize("WARNING");
10863 AprilFools_ = true;
10865 CFGregorianDate date(CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem()));
10866 AprilFools_ = date.month == 4 && date.day == 1;
10870 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10872 CGColorSpaceRelease(space_);
10873 CFRelease(Locale_);