1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2012 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 NSString *Cache_;
265 static bool AprilFools_;
267 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
269 static bool IsReachable(const char *name) {
270 SCNetworkReachabilityFlags flags; {
271 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
272 SCNetworkReachabilityGetFlags(reachability, &flags);
273 CFRelease(reachability);
276 // XXX: this elaborate mess is what Apple is using to determine this? :(
277 // XXX: do we care if the user has to intervene? maybe that's ok?
279 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
280 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
281 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
282 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
283 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
284 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
289 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
291 static _finline NSString *CydiaURL(NSString *path) {
293 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
294 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
295 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
296 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
297 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
299 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
302 static void ReapZombie(pid_t pid) {
305 if (waitpid(pid, &status, 0) == -1)
311 static _finline void UpdateExternalStatus(uint64_t newStatus) {
313 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
314 notify_set_state(notify_token, newStatus);
315 notify_cancel(notify_token);
317 notify_post("com.saurik.Cydia.status");
320 static CGFloat CYStatusBarHeight() {
321 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
322 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
325 /* NSForcedOrderingSearch doesn't work on the iPhone */
326 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
327 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
328 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
330 /* Insertion Sort {{{ */
332 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
333 const char *ptr = (const char *)list;
335 CFIndex half = count / 2;
336 const char *probe = ptr + elementSize * half;
337 CFComparisonResult cr = comparator(element, probe, context);
338 if (0 == cr) return (probe - (const char *)list) / elementSize;
339 ptr = (cr < 0) ? ptr : probe + elementSize;
340 count = (cr < 0) ? half : (half + (count & 1) - 1);
342 return (ptr - (const char *)list) / elementSize;
345 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
346 const char *ptr = (const char *)list;
348 CFIndex half = count / 2;
349 const char *probe = ptr + elementSize * half;
350 CFComparisonResult cr = comparator(element, probe, context);
351 if (0 == cr) return (probe - (const char *)list) / elementSize;
352 ptr = (cr < 0) ? ptr : probe + elementSize;
353 count = (cr < 0) ? half : (half + (count & 1) - 1);
355 return (ptr - (const char *)list) / elementSize;
358 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
359 if (range.length == 0)
361 const void **values(new const void *[range.length]);
362 CFArrayGetValues(array, range, values);
364 #if HistogramInsertionSort > 0
365 uint32_t total(0), *offsets(new uint32_t[range.length]);
368 for (CFIndex index(1); index != range.length; ++index) {
369 const void *value(values[index]);
370 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
371 CFIndex correct(index);
372 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
373 #if HistogramInsertionSort > 1
374 NSLog(@"%@ < %@", value, values[correct - 1]);
379 if (correct != index) {
380 size_t offset(index - correct);
381 #if HistogramInsertionSort
385 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
387 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
388 values[correct] = value;
392 CFArrayReplaceValues(array, range, values, range.length);
395 #if HistogramInsertionSort > 0
396 for (CFIndex index(0); index != range.length; ++index)
397 if (offsets[index] != 0)
398 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
399 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
406 /* Apple Bug Fixes {{{ */
407 @implementation UIWebDocumentView (Cydia)
409 - (void) _setScrollerOffset:(CGPoint)offset {
410 UIScroller *scroller([self _scroller]);
412 CGSize size([scroller contentSize]);
413 CGSize bounds([scroller bounds].size);
416 max.x = size.width - bounds.width;
417 max.y = size.height - bounds.height;
425 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
426 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
428 [scroller setOffset:offset];
434 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
435 size_t length([self length] - state->state);
438 else if (length > count)
440 for (size_t i(0); i != length; ++i)
441 objects[i] = [self item:state->state++];
442 state->itemsPtr = objects;
443 state->mutationsPtr = (unsigned long *) self;
447 /* Cydia NSString Additions {{{ */
448 @interface NSString (Cydia)
449 - (NSComparisonResult) compareByPath:(NSString *)other;
450 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
453 @implementation NSString (Cydia)
455 - (NSComparisonResult) compareByPath:(NSString *)other {
456 NSString *prefix = [self commonPrefixWithString:other options:0];
457 size_t length = [prefix length];
459 NSRange lrange = NSMakeRange(length, [self length] - length);
460 NSRange rrange = NSMakeRange(length, [other length] - length);
462 lrange = [self rangeOfString:@"/" options:0 range:lrange];
463 rrange = [other rangeOfString:@"/" options:0 range:rrange];
465 NSComparisonResult value;
467 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
468 value = NSOrderedSame;
469 else if (lrange.location == NSNotFound)
470 value = NSOrderedAscending;
471 else if (rrange.location == NSNotFound)
472 value = NSOrderedDescending;
474 value = NSOrderedSame;
476 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
477 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
478 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
479 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
481 NSComparisonResult result = [lpath compare:rpath];
482 return result == NSOrderedSame ? value : result;
485 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
486 return [(id)CFURLCreateStringByAddingPercentEscapes(
491 kCFStringEncodingUTF8
498 /* C++ NSString Wrapper Cache {{{ */
499 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
500 return size == 0 ? NULL :
501 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
502 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
505 static _finline CFStringRef CYStringCreate(const char *data) {
506 return CYStringCreate(data, strlen(data));
515 _finline void clear_() {
516 if (cache_ != NULL) {
523 _finline bool empty() const {
527 _finline size_t size() const {
531 _finline char *data() const {
535 _finline void clear() {
540 _finline CYString() :
547 _finline ~CYString() {
551 void operator =(const CYString &rhs) {
555 if (rhs.cache_ == nil)
558 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
561 void copy(apr_pool_t *pool) {
562 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
563 memcpy(temp, data_, size_);
568 void set(apr_pool_t *pool, const char *data, size_t size) {
574 data_ = const_cast<char *>(data);
582 _finline void set(apr_pool_t *pool, const char *data) {
583 set(pool, data, data == NULL ? 0 : strlen(data));
586 _finline void set(apr_pool_t *pool, const std::string &rhs) {
587 set(pool, rhs.data(), rhs.size());
590 bool operator ==(const CYString &rhs) const {
591 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
594 _finline operator CFStringRef() {
596 cache_ = CYStringCreate(data_, size_);
600 _finline operator id() {
601 return (NSString *) static_cast<CFStringRef>(*this);
604 _finline operator const char *() {
605 return reinterpret_cast<const char *>(data_);
609 /* C++ NSString Algorithm Adapters {{{ */
611 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
614 struct NSStringMapHash :
615 std::unary_function<NSString *, size_t>
617 _finline size_t operator ()(NSString *value) const {
618 return CFStringHashNSString((CFStringRef) value);
622 struct NSStringMapLess :
623 std::binary_function<NSString *, NSString *, bool>
625 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
626 return [lhs compare:rhs] == NSOrderedAscending;
630 struct NSStringMapEqual :
631 std::binary_function<NSString *, NSString *, bool>
633 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
634 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
635 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
636 //[lhs isEqualToString:rhs];
641 /* CoreGraphics Primitives {{{ */
646 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
647 CGFloat color[] = {red, green, blue, alpha};
648 return CGColorCreate(space, color);
657 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
658 color_(Create_(space, red, green, blue, alpha))
660 Set(space, red, green, blue, alpha);
665 CGColorRelease(color_);
672 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
674 color_ = Create_(space, red, green, blue, alpha);
677 operator CGColorRef() {
683 /* Random Global Variables {{{ */
684 static int PulseInterval_ = 500000;
686 static const NSString *UI_;
689 static bool RestartSubstrate_;
690 static NSArray *Finishes_;
692 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
693 #define NotifyConfig_ "/etc/notify.conf"
695 static bool Queuing_;
697 static CYColor Blue_;
698 static CYColor Blueish_;
699 static CYColor Black_;
701 static CYColor White_;
702 static CYColor Gray_;
703 static CYColor Green_;
704 static CYColor Purple_;
705 static CYColor Purplish_;
707 static UIColor *InstallingColor_;
708 static UIColor *RemovingColor_;
710 static NSString *App_;
712 static BOOL Advanced_;
713 static BOOL Ignored_;
715 static _H<UIFont> Font12_;
716 static _H<UIFont> Font12Bold_;
717 static _H<UIFont> Font14_;
718 static _H<UIFont> Font18Bold_;
719 static _H<UIFont> Font22Bold_;
721 static const char *Machine_ = NULL;
722 static _H<NSString> System_;
723 static NSString *SerialNumber_ = nil;
724 static NSString *ChipID_ = nil;
725 static NSString *BBSNum_ = nil;
726 static _H<NSString> Token_;
727 static NSString *UniqueID_ = nil;
728 static _H<NSString> UserAgent_;
729 static _H<NSString> Product_;
730 static _H<NSString> Safari_;
732 static CFLocaleRef Locale_;
733 static NSArray *Languages_;
734 static CGColorSpaceRef space_;
736 static NSDictionary *SectionMap_;
737 static NSMutableDictionary *Metadata_;
738 static _transient NSMutableDictionary *Settings_;
739 static _transient NSString *Role_;
740 static _transient NSMutableDictionary *Packages_;
741 static _transient NSMutableDictionary *Values_;
742 static _transient NSMutableDictionary *Sections_;
743 _H<NSMutableDictionary> Sources_;
744 static _transient NSNumber *Version_;
749 static CGFloat ScreenScale_;
750 static NSString *Idiom_;
751 static _H<NSString> Firmware_;
752 static NSString *Major_;
754 static _H<NSMutableDictionary> SessionData_;
755 static _H<NSObject> HostConfig_;
756 static _H<NSMutableSet> BridgedHosts_;
757 static _H<NSMutableSet> TokenHosts_;
758 static _H<NSMutableSet> InsecureHosts_;
759 static _H<NSMutableSet> PipelinedHosts_;
760 static _H<NSMutableSet> CachedURLs_;
762 static NSString *kCydiaProgressEventTypeError = @"Error";
763 static NSString *kCydiaProgressEventTypeInformation = @"Information";
764 static NSString *kCydiaProgressEventTypeStatus = @"Status";
765 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
768 /* Display Helpers {{{ */
769 inline float Interpolate(float begin, float end, float fraction) {
770 return (end - begin) * fraction + begin;
773 static _finline const char *StripVersion_(const char *version) {
774 const char *colon(strchr(version, ':'));
775 return colon == NULL ? version : colon + 1;
778 NSString *LocalizeSection(NSString *section) {
779 static Pcre title_r("^(.*?) \\((.*)\\)$");
780 if (title_r(section)) {
781 NSString *parent(title_r[1]);
782 NSString *child(title_r[2]);
784 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
785 LocalizeSection(parent),
786 LocalizeSection(child)
790 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
793 NSString *Simplify(NSString *title) {
794 const char *data = [title UTF8String];
795 size_t size = [title length];
797 static Pcre square_r("^\\[(.*)\\]$");
798 if (square_r(data, size))
799 return Simplify(square_r[1]);
801 static Pcre paren_r("^\\((.*)\\)$");
802 if (paren_r(data, size))
803 return Simplify(paren_r[1]);
805 static Pcre title_r("^(.*?) \\((.*)\\)$");
806 if (title_r(data, size))
807 return Simplify(title_r[1]);
813 NSString *GetLastUpdate() {
814 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
817 return UCLocalize("NEVER_OR_UNKNOWN");
819 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
820 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
822 CFRelease(formatter);
824 return [(NSString *) formatted autorelease];
827 bool isSectionVisible(NSString *section) {
828 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
829 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
830 return hidden == nil || ![hidden boolValue];
833 static NSObject *CYIOGetValue(const char *path, NSString *property) {
834 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
835 if (entry == MACH_PORT_NULL)
838 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
839 IOObjectRelease(entry);
843 return [(id) value autorelease];
846 static NSString *CYHex(NSData *data, bool reverse = false) {
850 size_t length([data length]);
851 uint8_t bytes[length];
852 [data getBytes:bytes];
854 char string[length * 2 + 1];
855 for (size_t i(0); i != length; ++i)
856 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
858 return [NSString stringWithUTF8String:string];
863 /* Delegate Prototypes {{{ */
866 @class CydiaProgressEvent;
868 @protocol DatabaseDelegate
869 - (void) repairWithSelector:(SEL)selector;
870 - (void) setConfigurationData:(NSString *)data;
871 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
874 @class CYPackageController;
876 @protocol CydiaDelegate
877 - (void) returnToCydia;
879 - (void) retainNetworkActivityIndicator;
880 - (void) releaseNetworkActivityIndicator;
881 - (void) clearPackage:(Package *)package;
882 - (void) installPackage:(Package *)package;
883 - (void) installPackages:(NSArray *)packages;
884 - (void) removePackage:(Package *)package;
885 - (void) beginUpdate;
887 - (void) distUpgrade;
890 - (void) _saveConfig;
892 - (void) addSource:(NSDictionary *)source;
893 - (void) addTrivialSource:(NSString *)href;
894 - (void) showSettings;
895 - (UIProgressHUD *) addProgressHUD;
896 - (void) removeProgressHUD:(UIProgressHUD *)hud;
897 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
898 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
902 /* Status Delegation {{{ */
904 public pkgAcquireStatus
907 _transient NSObject<ProgressDelegate> *delegate_;
917 void setDelegate(NSObject<ProgressDelegate> *delegate) {
918 delegate_ = delegate;
921 NSObject<ProgressDelegate> *getDelegate() const {
925 virtual bool MediaChange(std::string media, std::string drive) {
929 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
933 virtual void Fetch(pkgAcquire::ItemDesc &item) {
934 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
935 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
936 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
939 virtual void Done(pkgAcquire::ItemDesc &item) {
940 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
941 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
942 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
945 virtual void Fail(pkgAcquire::ItemDesc &item) {
947 item.Owner->Status == pkgAcquire::Item::StatIdle ||
948 item.Owner->Status == pkgAcquire::Item::StatDone
952 std::string &error(item.Owner->ErrorText);
956 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
957 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
960 virtual bool Pulse(pkgAcquire *Owner) {
961 bool value = pkgAcquireStatus::Pulse(Owner);
964 double(CurrentBytes + CurrentItems) /
965 double(TotalBytes + TotalItems)
968 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
969 [NSNumber numberWithDouble:percent], @"Percent",
971 [NSNumber numberWithDouble:CurrentBytes], @"Current",
972 [NSNumber numberWithDouble:TotalBytes], @"Total",
973 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
974 nil] waitUntilDone:YES];
976 if (value && ![delegate_ isProgressCancelled])
984 _finline bool WasCancelled() const {
988 virtual void Start() {
989 pkgAcquireStatus::Start();
990 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
993 virtual void Stop() {
994 pkgAcquireStatus::Stop();
995 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
996 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1000 /* Database Interface {{{ */
1001 typedef std::map< unsigned long, _H<Source> > SourceMap;
1003 @interface Database : NSObject {
1009 pkgCacheFile cache_;
1010 pkgDepCache::Policy *policy_;
1011 pkgRecords *records_;
1012 pkgProblemResolver *resolver_;
1013 pkgAcquire *fetcher_;
1015 SPtr<pkgPackageManager> manager_;
1016 pkgSourceList *list_;
1018 SourceMap sourceMap_;
1019 _H<NSMutableArray> sourceList_;
1021 CFMutableArrayRef packages_;
1023 _transient NSObject<DatabaseDelegate> *delegate_;
1024 _transient NSObject<ProgressDelegate> *progress_;
1032 std::map<const char *, _H<NSString> > sections_;
1035 + (Database *) sharedInstance;
1038 - (void) _readCydia:(NSNumber *)fd;
1039 - (void) _readStatus:(NSNumber *)fd;
1040 - (void) _readOutput:(NSNumber *)fd;
1044 - (Package *) packageWithName:(NSString *)name;
1046 - (pkgCacheFile &) cache;
1047 - (pkgDepCache::Policy *) policy;
1048 - (pkgRecords *) records;
1049 - (pkgProblemResolver *) resolver;
1050 - (pkgAcquire &) fetcher;
1051 - (pkgSourceList &) list;
1052 - (NSArray *) packages;
1053 - (NSArray *) sources;
1054 - (Source *) sourceWithKey:(NSString *)key;
1055 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1063 - (void) updateWithStatus:(Status &)status;
1065 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1067 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1068 - (NSObject<ProgressDelegate> *) progressDelegate;
1070 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1072 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1076 /* ProgressEvent Implementation {{{ */
1077 @implementation CydiaProgressEvent
1079 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1080 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1083 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1084 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1085 [event setPackage:package];
1089 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1090 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1092 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1093 NSArray *fields([description componentsSeparatedByString:@" "]);
1094 [event setItem:fields];
1096 if ([fields count] > 3) {
1097 [event setPackage:[fields objectAtIndex:2]];
1098 [event setVersion:[fields objectAtIndex:3]];
1101 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1106 + (NSArray *) _attributeKeys {
1107 return [NSArray arrayWithObjects:
1117 - (NSArray *) attributeKeys {
1118 return [[self class] _attributeKeys];
1121 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1122 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1125 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1126 if ((self = [super init]) != nil) {
1132 - (NSString *) message {
1136 - (NSString *) type {
1140 - (NSArray *) item {
1141 return (id) item_ ?: [NSNull null];
1144 - (void) setItem:(NSArray *)item {
1148 - (NSString *) package {
1149 return (id) package_ ?: [NSNull null];
1152 - (void) setPackage:(NSString *)package {
1156 - (NSString *) url {
1157 return (id) url_ ?: [NSNull null];
1160 - (void) setURL:(NSString *)url {
1164 - (void) setVersion:(NSString *)version {
1168 - (NSString *) version {
1169 return (id) version_ ?: [NSNull null];
1172 - (NSString *) compound:(NSString *)value {
1174 NSString *mode(nil); {
1175 NSString *type([self type]);
1176 if ([type isEqualToString:kCydiaProgressEventTypeError])
1177 mode = UCLocalize("ERROR");
1178 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1179 mode = UCLocalize("WARNING");
1183 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1189 - (NSString *) compoundMessage {
1190 return [self compound:[self message]];
1193 - (NSString *) compoundTitle {
1196 if (package_ == nil)
1198 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1199 title = [package name];
1203 return [self compound:title];
1209 // Cytore Definitions {{{
1210 struct PackageValue :
1213 Cytore::Offset<PackageValue> next_;
1215 uint32_t index_ : 23;
1216 uint32_t subscribed_ : 1;
1233 Cytore::Offset<PackageValue> packages_[1 << 16];
1236 static Cytore::File<MetaValue> MetaFile_;
1238 // Cytore Helper Functions {{{
1239 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1240 SplitHash nhash = { hashlittle(name, length) };
1242 PackageValue *metadata;
1244 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1245 offset: if (offset->IsNull()) {
1246 *offset = MetaFile_.New<PackageValue>(length + 1);
1247 metadata = &MetaFile_.Get(*offset);
1249 if (metadata == NULL) {
1253 metadata = new PackageValue();
1254 memset(metadata, 0, sizeof(*metadata));
1257 memcpy(metadata->name_, name, length + 1);
1258 metadata->nhash_ = nhash.u16[1];
1260 metadata = &MetaFile_.Get(*offset);
1262 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1263 offset = &metadata->next_;
1271 static void PackageImport(const void *key, const void *value, void *context) {
1272 bool &fail(*reinterpret_cast<bool *>(context));
1275 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1276 NSLog(@"failed to import package %@", key);
1280 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1281 NSDictionary *package((NSDictionary *) value);
1283 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1284 if ([subscribed boolValue] && !metadata->subscribed_)
1285 metadata->subscribed_ = true;
1287 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1288 time_t time([date timeIntervalSince1970]);
1289 if (metadata->first_ > time || metadata->first_ == 0)
1290 metadata->first_ = time;
1293 NSDate *date([package objectForKey:@"LastSeen"]);
1294 NSString *version([package objectForKey:@"LastVersion"]);
1296 if (date != nil && version != nil) {
1297 time_t time([date timeIntervalSince1970]);
1298 if (metadata->last_ < time || metadata->last_ == 0)
1299 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1300 size_t length(strlen(buffer));
1301 uint16_t vhash(hashlittle(buffer, length));
1303 size_t capped(std::min<size_t>(8, length));
1304 char *latest(buffer + length - capped);
1306 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1307 metadata->vhash_ = vhash;
1309 metadata->last_ = time;
1315 /* Source Class {{{ */
1316 @interface Source : NSObject {
1318 Database *database_;
1321 CYString depiction_;
1322 CYString description_;
1328 CYString distribution_;
1334 _H<NSString> authority_;
1336 CYString defaultIcon_;
1338 _H<NSMutableDictionary> record_;
1342 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1344 - (NSComparisonResult) compareByName:(Source *)source;
1346 - (NSString *) depictionForPackage:(NSString *)package;
1347 - (NSString *) supportForPackage:(NSString *)package;
1349 - (metaIndex *) metaIndex;
1350 - (NSDictionary *) record;
1353 - (NSString *) rooturi;
1354 - (NSString *) distribution;
1355 - (NSString *) type;
1358 - (NSString *) host;
1360 - (NSString *) name;
1361 - (NSString *) shortDescription;
1362 - (NSString *) label;
1363 - (NSString *) origin;
1364 - (NSString *) version;
1366 - (NSString *) defaultIcon;
1367 - (NSURL *) iconURL;
1371 @implementation Source
1375 distribution_.clear();
1380 description_.clear();
1386 defaultIcon_.clear();
1393 + (NSString *) webScriptNameForSelector:(SEL)selector {
1395 else if (selector == @selector(addSection:))
1396 return @"addSection";
1397 else if (selector == @selector(getField:))
1399 else if (selector == @selector(removeSection:))
1400 return @"removeSection";
1401 else if (selector == @selector(remove))
1407 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1408 return [self webScriptNameForSelector:selector] == nil;
1411 + (NSArray *) _attributeKeys {
1412 return [NSArray arrayWithObjects:
1423 @"shortDescription",
1430 - (NSArray *) attributeKeys {
1431 return [[self class] _attributeKeys];
1434 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1435 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1438 - (metaIndex *) metaIndex {
1442 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1445 trusted_ = index->IsTrusted();
1447 uri_.set(pool, index->GetURI());
1448 distribution_.set(pool, index->GetDist());
1449 type_.set(pool, index->GetType());
1451 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1452 if (dindex != NULL) {
1453 base_.set(pool, dindex->MetaIndexURI(""));
1456 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1459 pkgTagFile tags(&fd);
1461 pkgTagSection section;
1468 {"default-icon", &defaultIcon_},
1469 {"depiction", &depiction_},
1470 {"description", &description_},
1472 {"origin", &origin_},
1473 {"support", &support_},
1474 {"version", &version_},
1477 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1478 const char *start, *end;
1480 if (section.Find(names[i].name_, start, end)) {
1481 CYString &value(*names[i].value_);
1482 value.set(pool, start, end - start);
1488 record_ = [Sources_ objectForKey:[self key]];
1490 NSURL *url([NSURL URLWithString:uri_]);
1494 host_ = [host_ lowercaseString];
1499 authority_ = [url path];
1502 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1503 if ((self = [super init]) != nil) {
1504 era_ = [database era];
1505 database_ = database;
1508 [self setMetaIndex:index inPool:pool];
1512 - (NSString *) getField:(NSString *)name {
1513 @synchronized (database_) {
1514 if ([database_ era] != era_ || index_ == NULL)
1517 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1522 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1527 pkgTagFile tags(&fd);
1529 pkgTagSection section;
1532 const char *start, *end;
1533 if (!section.Find([name UTF8String], start, end))
1534 return (NSString *) [NSNull null];
1536 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1539 - (NSComparisonResult) compareByName:(Source *)source {
1540 NSString *lhs = [self name];
1541 NSString *rhs = [source name];
1543 if ([lhs length] != 0 && [rhs length] != 0) {
1544 unichar lhc = [lhs characterAtIndex:0];
1545 unichar rhc = [rhs characterAtIndex:0];
1547 if (isalpha(lhc) && !isalpha(rhc))
1548 return NSOrderedAscending;
1549 else if (!isalpha(lhc) && isalpha(rhc))
1550 return NSOrderedDescending;
1553 return [lhs compare:rhs options:LaxCompareOptions_];
1556 - (NSString *) depictionForPackage:(NSString *)package {
1557 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1560 - (NSString *) supportForPackage:(NSString *)package {
1561 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1564 - (NSArray *) sections {
1565 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1568 - (void) _addSection:(NSString *)section {
1571 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1572 if (![sections containsObject:section]) {
1573 [sections addObject:section];
1577 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1582 - (bool) addSection:(NSString *)section {
1586 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1590 - (void) _removeSection:(NSString *)section {
1594 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1595 if ([sections containsObject:section]) {
1596 [sections removeObject:section];
1601 - (bool) removeSection:(NSString *)section {
1605 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1610 [Sources_ removeObjectForKey:[self key]];
1615 bool value(record_ != nil);
1616 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1620 - (NSDictionary *) record {
1628 - (NSString *) rooturi {
1632 - (NSString *) distribution {
1633 return distribution_;
1636 - (NSString *) type {
1640 - (NSString *) baseuri {
1641 return base_.empty() ? nil : (id) base_;
1644 - (NSString *) iconuri {
1645 if (NSString *base = [self baseuri])
1646 return [base stringByAppendingString:@"CydiaIcon.png"];
1651 - (NSURL *) iconURL {
1652 if (NSString *uri = [self iconuri])
1653 return [NSURL URLWithString:uri];
1657 - (NSString *) key {
1658 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1661 - (NSString *) host {
1665 - (NSString *) name {
1666 return origin_.empty() ? (id) authority_ : origin_;
1669 - (NSString *) shortDescription {
1670 return description_;
1673 - (NSString *) label {
1674 return label_.empty() ? (id) authority_ : label_;
1677 - (NSString *) origin {
1681 - (NSString *) version {
1685 - (NSString *) defaultIcon {
1686 return defaultIcon_;
1691 /* CydiaOperation Class {{{ */
1692 @interface CydiaOperation : NSObject {
1693 _H<NSString> operator_;
1694 _H<NSString> value_;
1697 - (NSString *) operator;
1698 - (NSString *) value;
1702 @implementation CydiaOperation
1704 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1705 if ((self = [super init]) != nil) {
1706 operator_ = [NSString stringWithUTF8String:_operator];
1707 value_ = [NSString stringWithUTF8String:value];
1711 + (NSArray *) _attributeKeys {
1712 return [NSArray arrayWithObjects:
1718 - (NSArray *) attributeKeys {
1719 return [[self class] _attributeKeys];
1722 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1723 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1726 - (NSString *) operator {
1730 - (NSString *) value {
1736 /* CydiaClause Class {{{ */
1737 @interface CydiaClause : NSObject {
1738 _H<NSString> package_;
1739 _H<CydiaOperation> version_;
1742 - (NSString *) package;
1743 - (CydiaOperation *) version;
1747 @implementation CydiaClause
1749 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1750 if ((self = [super init]) != nil) {
1751 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1753 if (const char *version = dep.TargetVer())
1754 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1756 version_ = (id) [NSNull null];
1760 + (NSArray *) _attributeKeys {
1761 return [NSArray arrayWithObjects:
1767 - (NSArray *) attributeKeys {
1768 return [[self class] _attributeKeys];
1771 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1772 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1775 - (NSString *) package {
1779 - (CydiaOperation *) version {
1785 /* CydiaRelation Class {{{ */
1786 @interface CydiaRelation : NSObject {
1787 _H<NSString> relationship_;
1788 _H<NSMutableArray> clauses_;
1791 - (NSString *) relationship;
1792 - (NSArray *) clauses;
1796 @implementation CydiaRelation
1798 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1799 if ((self = [super init]) != nil) {
1800 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1801 clauses_ = [NSMutableArray arrayWithCapacity:8];
1803 pkgCache::DepIterator start;
1804 pkgCache::DepIterator end;
1805 dep.GlobOr(start, end); // ++dep
1808 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1810 // yes, seriously. (wtf?)
1818 + (NSArray *) _attributeKeys {
1819 return [NSArray arrayWithObjects:
1825 - (NSArray *) attributeKeys {
1826 return [[self class] _attributeKeys];
1829 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1830 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1833 - (NSString *) relationship {
1834 return relationship_;
1837 - (NSArray *) clauses {
1841 - (void) addClause:(CydiaClause *)clause {
1842 [clauses_ addObject:clause];
1847 /* Package Class {{{ */
1848 struct ParsedPackage {
1852 CYString architecture_;
1855 CYString depiction_;
1865 @interface Package : NSObject {
1868 uint32_t essential_ : 1;
1869 uint32_t obsolete_ : 1;
1870 uint32_t ignored_ : 1;
1871 uint32_t pooled_ : 1;
1877 _transient Database *database_;
1879 pkgCache::VerIterator version_;
1880 pkgCache::PkgIterator iterator_;
1881 pkgCache::VerFileIterator file_;
1887 CYString installed_;
1889 const char *section_;
1890 _transient NSString *section$_;
1894 PackageValue *metadata_;
1895 ParsedPackage *parsed_;
1897 _H<NSMutableArray> tags_;
1900 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1901 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1903 - (pkgCache::PkgIterator) iterator;
1906 - (NSString *) section;
1907 - (NSString *) simpleSection;
1909 - (NSString *) longSection;
1910 - (NSString *) shortSection;
1914 - (MIMEAddress *) maintainer;
1916 - (NSString *) longDescription;
1917 - (NSString *) shortDescription;
1920 - (PackageValue *) metadata;
1923 - (bool) subscribed;
1924 - (bool) setSubscribed:(bool)subscribed;
1928 - (NSString *) latest;
1929 - (NSString *) installed;
1930 - (BOOL) uninstalled;
1933 - (BOOL) upgradableAndEssential:(BOOL)essential;
1936 - (BOOL) unfiltered;
1940 - (BOOL) halfConfigured;
1941 - (BOOL) halfInstalled;
1943 - (NSString *) mode;
1946 - (NSString *) name;
1948 - (NSString *) homepage;
1949 - (NSString *) depiction;
1950 - (MIMEAddress *) author;
1952 - (NSString *) support;
1954 - (NSArray *) files;
1955 - (NSArray *) warnings;
1956 - (NSArray *) applications;
1958 - (Source *) source;
1961 - (BOOL) matches:(NSArray *)query;
1963 - (bool) hasSupportingRole;
1964 - (BOOL) hasTag:(NSString *)tag;
1965 - (NSString *) primaryPurpose;
1966 - (NSArray *) purposes;
1967 - (bool) isCommercial;
1969 - (void) setIndex:(size_t)index;
1971 - (CYString &) cyname;
1973 - (uint32_t) compareBySection:(NSArray *)sections;
1978 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1979 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1980 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1981 - (bool) isVisibleInSection:(NSString *)section;
1982 - (bool) isVisibleInSource:(Source *)source;
1986 uint32_t PackageChangesRadix(Package *self, void *) {
1991 uint32_t timestamp : 30;
1992 uint32_t ignored : 1;
1993 uint32_t upgradable : 1;
1997 bool upgradable([self upgradableAndEssential:YES]);
1998 value.bits.upgradable = upgradable ? 1 : 0;
2001 value.bits.timestamp = 0;
2002 value.bits.ignored = [self ignored] ? 0 : 1;
2003 value.bits.upgradable = 1;
2005 value.bits.timestamp = [self seen] >> 2;
2006 value.bits.ignored = 0;
2007 value.bits.upgradable = 0;
2010 return _not(uint32_t) - value.key;
2013 uint32_t PackagePrefixRadix(Package *self, void *context) {
2014 size_t offset(reinterpret_cast<size_t>(context));
2015 CYString &name([self cyname]);
2017 size_t size(name.size());
2020 char *text(name.data());
2023 if (!isdigit(text[0]))
2027 while (size != digits && isdigit(text[digits]))
2035 if (offset == 0 && zeros != 0) {
2036 memset(data, '0', zeros);
2037 memcpy(data + zeros, text, 4 - zeros);
2039 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2040 if (size <= offset - zeros)
2043 text += offset - zeros;
2044 size -= offset - zeros;
2047 memcpy(data, text, 4);
2049 memcpy(data, text, size);
2050 memset(data + size, 0, 4 - size);
2053 for (size_t i(0); i != 4; ++i)
2054 if (isalpha(data[i]))
2062 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2064 /* XXX: ntohl may be more honest */
2065 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2068 CYString &(*PackageName)(Package *self, SEL sel);
2070 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2071 _profile(PackageNameCompare)
2072 CYString &lhi(PackageName(lhs, @selector(cyname)));
2073 CYString &rhi(PackageName(rhs, @selector(cyname)));
2074 CFStringRef lhn(lhi), rhn(rhi);
2077 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2078 else if (rhn == NULL)
2079 return NSOrderedDescending;
2081 _profile(PackageNameCompare$NumbersLast)
2082 if (!lhi.empty() && !rhi.empty()) {
2083 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2084 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2085 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2086 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2087 return lha ? NSOrderedAscending : NSOrderedDescending;
2091 CFIndex length = CFStringGetLength(lhn);
2093 _profile(PackageNameCompare$Compare)
2094 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2099 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2100 return PackageNameCompare(*lhs, *rhs, context);
2103 struct PackageNameOrdering :
2104 std::binary_function<Package *, Package *, bool>
2106 _finline bool operator ()(Package *lhs, Package *rhs) const {
2107 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2111 @implementation Package
2113 - (NSString *) description {
2114 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2119 apr_pool_destroy(pool_);
2120 if (parsed_ != NULL)
2125 + (NSString *) webScriptNameForSelector:(SEL)selector {
2127 else if (selector == @selector(clear))
2129 else if (selector == @selector(getField:))
2131 else if (selector == @selector(hasTag:))
2133 else if (selector == @selector(install))
2135 else if (selector == @selector(remove))
2141 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2142 return [self webScriptNameForSelector:selector] == nil;
2145 + (NSArray *) _attributeKeys {
2146 return [NSArray arrayWithObjects:
2167 @"shortDescription",
2180 - (NSArray *) attributeKeys {
2181 return [[self class] _attributeKeys];
2184 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2185 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2188 - (NSArray *) relations {
2189 @synchronized (database_) {
2190 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2191 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2192 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2196 - (NSString *) architecture {
2198 @synchronized (database_) {
2199 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2202 - (NSString *) getField:(NSString *)name {
2203 @synchronized (database_) {
2204 if ([database_ era] != era_ || file_.end())
2207 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2209 const char *start, *end;
2210 if (!parser.Find([name UTF8String], start, end))
2211 return (NSString *) [NSNull null];
2213 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2217 if (parsed_ != NULL)
2219 @synchronized (database_) {
2220 if ([database_ era] != era_ || file_.end())
2223 ParsedPackage *parsed(new ParsedPackage);
2226 _profile(Package$parse)
2227 pkgRecords::Parser *parser;
2229 _profile(Package$parse$Lookup)
2230 parser = &[database_ records]->Lookup(file_);
2235 _profile(Package$parse$Find)
2240 {"architecture", &parsed->architecture_},
2241 {"icon", &parsed->icon_},
2242 {"depiction", &parsed->depiction_},
2243 {"homepage", &parsed->homepage_},
2244 {"website", &website},
2245 {"bugs", &parsed->bugs_},
2246 {"support", &parsed->support_},
2247 {"sponsor", &parsed->sponsor_},
2248 {"author", &parsed->author_},
2249 {"md5sum", &parsed->md5sum_},
2252 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2253 const char *start, *end;
2255 if (parser->Find(names[i].name_, start, end)) {
2256 CYString &value(*names[i].value_);
2257 _profile(Package$parse$Value)
2258 value.set(pool_, start, end - start);
2264 _profile(Package$parse$Tagline)
2265 const char *start, *end;
2266 if (parser->ShortDesc(start, end)) {
2267 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2270 while (stop != start && stop[-1] == '\r')
2272 parsed->tagline_.set(pool_, start, stop - start);
2276 _profile(Package$parse$Retain)
2277 if (parsed->homepage_.empty())
2278 parsed->homepage_ = website;
2279 if (parsed->homepage_ == parsed->depiction_)
2280 parsed->homepage_.clear();
2285 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2286 if ((self = [super init]) != nil) {
2287 _profile(Package$initWithVersion)
2289 apr_pool_create(&pool_, NULL);
2295 database_ = database;
2296 era_ = [database era];
2300 pkgCache::PkgIterator iterator(version.ParentPkg());
2301 iterator_ = iterator;
2303 _profile(Package$initWithVersion$Version)
2304 if (!version_.end())
2305 file_ = version_.FileList();
2307 pkgCache &cache([database_ cache]);
2308 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2312 _profile(Package$initWithVersion$Cache)
2313 name_.set(NULL, iterator.Display());
2315 latest_.set(NULL, StripVersion_(version_.VerStr()));
2317 pkgCache::VerIterator current(iterator.CurrentVer());
2319 installed_.set(NULL, StripVersion_(current.VerStr()));
2322 _profile(Package$initWithVersion$Tags)
2323 pkgCache::TagIterator tag(iterator.TagList());
2325 tags_ = [NSMutableArray arrayWithCapacity:8];
2327 goto tag; for (; !tag.end(); ++tag) tag: {
2328 const char *name(tag.Name());
2329 NSString *string((NSString *) CYStringCreate(name));
2333 [tags_ addObject:[string autorelease]];
2335 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2336 if (strcmp(name + 6, "enduser") == 0)
2338 else if (strcmp(name + 6, "hacker") == 0)
2340 else if (strcmp(name + 6, "developer") == 0)
2342 else if (strcmp(name + 6, "cydia") == 0)
2348 if (strncmp(name, "cydia::", 7) == 0) {
2349 if (strcmp(name + 7, "essential") == 0)
2351 else if (strcmp(name + 7, "obsolete") == 0)
2358 _profile(Package$initWithVersion$Metadata)
2359 const char *mixed(iterator.Name());
2360 size_t size(strlen(mixed));
2361 char lower[size + 1];
2363 for (size_t i(0); i != size; ++i)
2364 lower[i] = mixed[i] | 0x20;
2367 PackageValue *metadata(PackageFind(lower, size));
2368 metadata_ = metadata;
2370 id_.set(NULL, metadata->name_, size);
2372 const char *latest(version_.VerStr());
2373 size_t length(strlen(latest));
2375 uint16_t vhash(hashlittle(latest, length));
2377 size_t capped(std::min<size_t>(8, length));
2378 latest = latest + length - capped;
2380 if (metadata->first_ == 0)
2381 metadata->first_ = now_;
2383 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2384 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2385 metadata->vhash_ = vhash;
2386 metadata->last_ = now_;
2387 } else if (metadata->last_ == 0)
2388 metadata->last_ = metadata->first_;
2391 _profile(Package$initWithVersion$Section)
2392 section_ = version_.Section();
2395 _profile(Package$initWithVersion$Flags)
2396 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2397 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2402 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2403 pkgCache::VerIterator version;
2405 _profile(Package$packageWithIterator$GetCandidateVer)
2406 version = [database policy]->GetCandidateVer(iterator);
2414 _profile(Package$packageWithIterator$Allocate)
2415 package = [Package allocWithZone:zone];
2418 _profile(Package$packageWithIterator$Initialize)
2420 initWithVersion:version
2427 _profile(Package$packageWithIterator$Autorelease)
2428 package = [package autorelease];
2434 - (pkgCache::PkgIterator) iterator {
2438 - (NSString *) section {
2439 if (section$_ == nil) {
2440 if (section_ == NULL)
2443 _profile(Package$section$mappedSectionForPointer)
2444 section$_ = [database_ mappedSectionForPointer:section_];
2449 - (NSString *) simpleSection {
2450 if (NSString *section = [self section])
2451 return Simplify(section);
2456 - (NSString *) longSection {
2457 return LocalizeSection([self section]);
2460 - (NSString *) shortSection {
2461 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2464 - (NSString *) uri {
2467 pkgIndexFile *index;
2468 pkgCache::PkgFileIterator file(file_.File());
2469 if (![database_ list].FindIndex(file, index))
2471 return [NSString stringWithUTF8String:iterator_->Path];
2472 //return [NSString stringWithUTF8String:file.Site()];
2473 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2477 - (MIMEAddress *) maintainer {
2478 @synchronized (database_) {
2479 if ([database_ era] != era_ || file_.end())
2482 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2483 const std::string &maintainer(parser->Maintainer());
2484 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2487 - (NSString *) md5sum {
2488 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2492 @synchronized (database_) {
2493 if ([database_ era] != era_ || version_.end())
2496 return version_->InstalledSize;
2499 - (NSString *) longDescription {
2500 @synchronized (database_) {
2501 if ([database_ era] != era_ || file_.end())
2504 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2505 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2507 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2508 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2509 if ([lines count] < 2)
2512 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2513 for (size_t i(1), e([lines count]); i != e; ++i) {
2514 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2515 [trimmed addObject:trim];
2518 return [trimmed componentsJoinedByString:@"\n"];
2521 - (NSString *) shortDescription {
2522 if (parsed_ != NULL)
2523 return static_cast<NSString *>(parsed_->tagline_);
2525 @synchronized (database_) {
2526 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2528 const char *start, *end;
2529 if (!parser.ShortDesc(start, end))
2532 if (end - start > 200)
2536 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2539 while (end != start && end[-1] == '\r')
2543 return [(id) CYStringCreate(start, end - start) autorelease];
2547 _profile(Package$index)
2548 CFStringRef name((CFStringRef) [self name]);
2549 if (CFStringGetLength(name) == 0)
2551 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2552 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2554 return toupper(character);
2558 - (PackageValue *) metadata {
2563 PackageValue *metadata([self metadata]);
2564 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2567 - (bool) subscribed {
2568 return [self metadata]->subscribed_;
2571 - (bool) setSubscribed:(bool)subscribed {
2572 PackageValue *metadata([self metadata]);
2573 if (metadata->subscribed_ == subscribed)
2575 metadata->subscribed_ = subscribed;
2583 - (NSString *) latest {
2587 - (NSString *) installed {
2591 - (BOOL) uninstalled {
2592 return installed_.empty();
2596 return !version_.end();
2599 - (BOOL) upgradableAndEssential:(BOOL)essential {
2600 _profile(Package$upgradableAndEssential)
2601 pkgCache::VerIterator current(iterator_.CurrentVer());
2603 return essential && essential_;
2605 return !version_.end() && version_ != current;
2609 - (BOOL) essential {
2614 return [database_ cache][iterator_].InstBroken();
2617 - (BOOL) unfiltered {
2618 _profile(Package$unfiltered$obsolete)
2619 if (_unlikely(obsolete_))
2623 _profile(Package$unfiltered$hasSupportingRole)
2624 if (_unlikely(![self hasSupportingRole]))
2632 if (![self unfiltered])
2637 _profile(Package$visible$section)
2638 section = [self section];
2641 _profile(Package$visible$isSectionVisible)
2642 if (!isSectionVisible(section))
2650 unsigned char current(iterator_->CurrentState);
2651 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2654 - (BOOL) halfConfigured {
2655 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2658 - (BOOL) halfInstalled {
2659 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2663 @synchronized (database_) {
2664 if ([database_ era] != era_ || iterator_.end())
2667 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2668 return state.Mode != pkgDepCache::ModeKeep;
2671 - (NSString *) mode {
2672 @synchronized (database_) {
2673 if ([database_ era] != era_ || iterator_.end())
2676 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2678 switch (state.Mode) {
2679 case pkgDepCache::ModeDelete:
2680 if ((state.iFlags & pkgDepCache::Purge) != 0)
2684 case pkgDepCache::ModeKeep:
2685 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2686 return @"REINSTALL";
2687 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2691 case pkgDepCache::ModeInstall:
2692 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2693 return @"REINSTALL";
2694 else*/ switch (state.Status) {
2696 return @"DOWNGRADE";
2702 return @"NEW_INSTALL";
2713 - (NSString *) name {
2714 return name_.empty() ? id_ : name_;
2717 - (UIImage *) icon {
2718 NSString *section = [self simpleSection];
2721 if (parsed_ != NULL)
2722 if (NSString *href = parsed_->icon_)
2723 if ([href hasPrefix:@"file:///"])
2724 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2725 if (icon == nil) if (section != nil)
2726 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2727 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2728 if ([dicon hasPrefix:@"file:///"])
2729 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2731 icon = [UIImage applicationImageNamed:@"unknown.png"];
2735 - (NSString *) homepage {
2736 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2739 - (NSString *) depiction {
2740 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2743 - (MIMEAddress *) sponsor {
2744 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2747 - (MIMEAddress *) author {
2748 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2751 - (NSString *) support {
2752 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2755 - (NSArray *) files {
2756 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2757 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2760 fin.open([path UTF8String]);
2765 while (std::getline(fin, line))
2766 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2771 - (NSString *) state {
2772 @synchronized (database_) {
2773 if ([database_ era] != era_ || file_.end())
2776 switch (iterator_->CurrentState) {
2777 case pkgCache::State::NotInstalled:
2778 return @"NotInstalled";
2779 case pkgCache::State::UnPacked:
2781 case pkgCache::State::HalfConfigured:
2782 return @"HalfConfigured";
2783 case pkgCache::State::HalfInstalled:
2784 return @"HalfInstalled";
2785 case pkgCache::State::ConfigFiles:
2786 return @"ConfigFiles";
2787 case pkgCache::State::Installed:
2788 return @"Installed";
2789 case pkgCache::State::TriggersAwaited:
2790 return @"TriggersAwaited";
2791 case pkgCache::State::TriggersPending:
2792 return @"TriggersPending";
2795 return (NSString *) [NSNull null];
2798 - (NSString *) selection {
2799 @synchronized (database_) {
2800 if ([database_ era] != era_ || file_.end())
2803 switch (iterator_->SelectedState) {
2804 case pkgCache::State::Unknown:
2806 case pkgCache::State::Install:
2808 case pkgCache::State::Hold:
2810 case pkgCache::State::DeInstall:
2811 return @"DeInstall";
2812 case pkgCache::State::Purge:
2816 return (NSString *) [NSNull null];
2819 - (NSArray *) warnings {
2820 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2821 const char *name(iterator_.Name());
2823 size_t length(strlen(name));
2824 if (length < 2) invalid:
2825 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2826 else for (size_t i(0); i != length; ++i)
2828 /* XXX: technically this is not allowed */
2829 (name[i] < 'A' || name[i] > 'Z') &&
2830 (name[i] < 'a' || name[i] > 'z') &&
2831 (name[i] < '0' || name[i] > '9') &&
2832 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2835 if (strcmp(name, "cydia") != 0) {
2838 bool _private = false;
2841 bool repository = [[self section] isEqualToString:@"Repositories"];
2843 if (NSArray *files = [self files])
2844 for (NSString *file in files)
2845 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2847 else if (!user && [file isEqualToString:@"/User"])
2849 else if (!_private && [file isEqualToString:@"/private"])
2851 else if (!stash && [file isEqualToString:@"/var/stash"])
2854 /* XXX: this is not sensitive enough. only some folders are valid. */
2855 if (cydia && !repository)
2856 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2858 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2860 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2862 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2865 return [warnings count] == 0 ? nil : warnings;
2868 - (NSArray *) applications {
2869 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2871 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2873 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2874 if (NSArray *files = [self files])
2875 for (NSString *file in files)
2876 if (application_r(file)) {
2877 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2878 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2879 if ([id isEqualToString:me])
2882 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2884 display = application_r[1];
2886 NSString *bundle([file stringByDeletingLastPathComponent]);
2887 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2888 // XXX: maybe this should check if this is really a string, not just for length
2889 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
2891 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2893 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2894 [applications addObject:application];
2896 [application addObject:id];
2897 [application addObject:display];
2898 [application addObject:url];
2901 return [applications count] == 0 ? nil : applications;
2904 - (Source *) source {
2905 if (source_ == nil) {
2906 @synchronized (database_) {
2907 if ([database_ era] != era_ || file_.end())
2908 source_ = (Source *) [NSNull null];
2910 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2914 return source_ == (Source *) [NSNull null] ? nil : source_;
2921 - (BOOL) matches:(NSArray *)query {
2922 if (query == nil || [query count] == 0)
2931 string = [self name];
2932 length = [string length];
2934 for (NSString *term in query) {
2935 range = [string rangeOfString:term options:MatchCompareOptions_];
2936 if (range.location != NSNotFound)
2937 rank_ -= 6 * 1000000 / length;
2942 length = [string length];
2944 for (NSString *term in query) {
2945 range = [string rangeOfString:term options:MatchCompareOptions_];
2946 if (range.location != NSNotFound)
2947 rank_ -= 6 * 1000000 / length;
2951 string = [self shortDescription];
2952 length = [string length];
2953 NSUInteger stop(std::min<NSUInteger>(length, 200));
2955 for (NSString *term in query) {
2956 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2957 if (range.location != NSNotFound)
2958 rank_ -= 2 * 100000;
2964 - (bool) hasSupportingRole {
2969 if ([Role_ isEqualToString:@"User"])
2973 if ([Role_ isEqualToString:@"Hacker"])
2977 if ([Role_ isEqualToString:@"Developer"])
2982 - (NSArray *) tags {
2986 - (BOOL) hasTag:(NSString *)tag {
2987 return tags_ == nil ? NO : [tags_ containsObject:tag];
2990 - (NSString *) primaryPurpose {
2991 for (NSString *tag in (NSArray *) tags_)
2992 if ([tag hasPrefix:@"purpose::"])
2993 return [tag substringFromIndex:9];
2997 - (NSArray *) purposes {
2998 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2999 for (NSString *tag in (NSArray *) tags_)
3000 if ([tag hasPrefix:@"purpose::"])
3001 [purposes addObject:[tag substringFromIndex:9]];
3002 return [purposes count] == 0 ? nil : purposes;
3005 - (bool) isCommercial {
3006 return [self hasTag:@"cydia::commercial"];
3009 - (void) setIndex:(size_t)index {
3010 if (metadata_->index_ != index)
3011 metadata_->index_ = index;
3014 - (CYString &) cyname {
3015 return name_.empty() ? id_ : name_;
3018 - (uint32_t) compareBySection:(NSArray *)sections {
3019 NSString *section([self section]);
3020 for (size_t i(0), e([sections count]); i != e; ++i) {
3021 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3025 return _not(uint32_t);
3029 @synchronized (database_) {
3030 pkgProblemResolver *resolver = [database_ resolver];
3031 resolver->Clear(iterator_);
3033 pkgCacheFile &cache([database_ cache]);
3034 cache->SetReInstall(iterator_, false);
3035 cache->MarkKeep(iterator_, false);
3039 @synchronized (database_) {
3040 pkgProblemResolver *resolver = [database_ resolver];
3041 resolver->Clear(iterator_);
3042 resolver->Protect(iterator_);
3044 pkgCacheFile &cache([database_ cache]);
3045 cache->SetReInstall(iterator_, false);
3046 cache->MarkInstall(iterator_, false);
3048 pkgDepCache::StateCache &state((*cache)[iterator_]);
3049 if (!state.Install())
3050 cache->SetReInstall(iterator_, true);
3054 @synchronized (database_) {
3055 pkgProblemResolver *resolver = [database_ resolver];
3056 resolver->Clear(iterator_);
3057 resolver->Remove(iterator_);
3058 resolver->Protect(iterator_);
3060 pkgCacheFile &cache([database_ cache]);
3061 cache->SetReInstall(iterator_, false);
3062 cache->MarkDelete(iterator_, true);
3065 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3066 _profile(Package$isUnfilteredAndSearchedForBy)
3069 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3070 value &= [self unfiltered];
3073 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3074 value &= [self matches:query];
3081 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3082 if ([search length] == 0)
3085 _profile(Package$isUnfilteredAndSelectedForBy)
3088 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3089 value &= [self unfiltered];
3092 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3093 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3100 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3101 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3104 - (bool) isVisibleInSection:(NSString *)name {
3105 NSString *section([self section]);
3109 section == nil && [name length] == 0 ||
3110 [name isEqualToString:section]
3111 ) && [self visible];
3114 - (bool) isVisibleInSource:(Source *)source {
3115 return [self source] == source && [self visible];
3120 /* Section Class {{{ */
3121 @interface Section : NSObject {
3126 _H<NSString> localized_;
3129 - (NSComparisonResult) compareByLocalized:(Section *)section;
3130 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3131 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3132 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3133 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3134 - (NSString *) name;
3141 - (void) addToCount;
3143 - (void) setCount:(size_t)count;
3144 - (NSString *) localized;
3148 @implementation Section
3150 - (NSComparisonResult) compareByLocalized:(Section *)section {
3151 NSString *lhs(localized_);
3152 NSString *rhs([section localized]);
3154 /*if ([lhs length] != 0 && [rhs length] != 0) {
3155 unichar lhc = [lhs characterAtIndex:0];
3156 unichar rhc = [rhs characterAtIndex:0];
3158 if (isalpha(lhc) && !isalpha(rhc))
3159 return NSOrderedAscending;
3160 else if (!isalpha(lhc) && isalpha(rhc))
3161 return NSOrderedDescending;
3164 return [lhs compare:rhs options:LaxCompareOptions_];
3167 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3168 if ((self = [self initWithName:name localize:NO]) != nil) {
3169 if (localized != nil)
3170 localized_ = localized;
3174 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3175 return [self initWithName:name row:0 localize:localize];
3178 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3179 if ((self = [super init]) != nil) {
3184 localized_ = LocalizeSection(name_);
3188 /* XXX: localize the index thingees */
3189 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3190 if ((self = [super init]) != nil) {
3191 name_ = [NSString stringWithCharacters:&index length:1];
3197 - (NSString *) name {
3217 - (void) addToCount {
3221 - (void) setCount:(size_t)count {
3225 - (NSString *) localized {
3232 class CydiaLogCleaner :
3233 public pkgArchiveCleaner
3236 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3241 /* Database Implementation {{{ */
3242 @implementation Database
3244 + (Database *) sharedInstance {
3245 static _H<Database> instance;
3246 if (instance == nil)
3247 instance = [[[Database alloc] init] autorelease];
3255 - (void) releasePackages {
3256 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3257 CFArrayRemoveAllValues(packages_);
3261 // XXX: actually implement this thing
3263 [self releasePackages];
3264 apr_pool_destroy(pool_);
3265 NSRecycleZone(zone_);
3269 - (void) _readCydia:(NSNumber *)fd {
3270 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3271 std::istream is(&ib);
3274 static Pcre finish_r("^finish:([^:]*)$");
3276 while (std::getline(is, line)) {
3277 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3279 const char *data(line.c_str());
3280 size_t size = line.size();
3281 lprintf("C:%s\n", data);
3283 if (finish_r(data, size)) {
3284 NSString *finish = finish_r[1];
3285 int index = [Finishes_ indexOfObject:finish];
3286 if (index != INT_MAX && index > Finish_)
3296 - (void) _readStatus:(NSNumber *)fd {
3297 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3298 std::istream is(&ib);
3301 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3302 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3304 while (std::getline(is, line)) {
3305 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3307 const char *data(line.c_str());
3308 size_t size(line.size());
3309 lprintf("S:%s\n", data);
3311 if (conffile_r(data, size)) {
3312 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3313 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3314 } else if (strncmp(data, "status: ", 8) == 0) {
3315 // status: <package>: {unpacked,half-configured,installed}
3316 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3317 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3318 } else if (strncmp(data, "processing: ", 12) == 0) {
3319 // processing: configure: config-test
3320 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3321 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3322 } else if (pmstatus_r(data, size)) {
3323 std::string type([pmstatus_r[1] UTF8String]);
3325 NSString *package = pmstatus_r[2];
3326 if ([package isEqualToString:@"dpkg-exec"])
3329 float percent([pmstatus_r[3] floatValue]);
3330 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3332 NSString *string = pmstatus_r[4];
3334 if (type == "pmerror") {
3335 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3336 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3337 } else if (type == "pmstatus") {
3338 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3339 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3340 } else if (type == "pmconffile")
3341 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3343 lprintf("E:unknown pmstatus\n");
3345 lprintf("E:unknown status\n");
3353 - (void) _readOutput:(NSNumber *)fd {
3354 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3355 std::istream is(&ib);
3358 while (std::getline(is, line)) {
3359 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3361 lprintf("O:%s\n", line.c_str());
3363 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3364 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3376 - (Package *) packageWithName:(NSString *)name {
3379 @synchronized (self) {
3380 if (static_cast<pkgDepCache *>(cache_) == NULL)
3382 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3383 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3387 if ((self = [super init]) != nil) {
3394 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3395 apr_pool_create(&pool_, NULL);
3397 size_t capacity(MetaFile_->active_);
3403 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3404 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3408 _assert(pipe(fds) != -1);
3411 _config->Set("APT::Keep-Fds::", cydiafd_);
3412 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3415 detachNewThreadSelector:@selector(_readCydia:)
3417 withObject:[NSNumber numberWithInt:fds[0]]
3420 _assert(pipe(fds) != -1);
3424 detachNewThreadSelector:@selector(_readStatus:)
3426 withObject:[NSNumber numberWithInt:fds[0]]
3429 _assert(pipe(fds) != -1);
3430 _assert(dup2(fds[0], 0) != -1);
3431 _assert(close(fds[0]) != -1);
3433 input_ = fdopen(fds[1], "a");
3435 _assert(pipe(fds) != -1);
3436 _assert(dup2(fds[1], 1) != -1);
3437 _assert(close(fds[1]) != -1);
3440 detachNewThreadSelector:@selector(_readOutput:)
3442 withObject:[NSNumber numberWithInt:fds[0]]
3447 - (pkgCacheFile &) cache {
3451 - (pkgDepCache::Policy *) policy {
3455 - (pkgRecords *) records {
3459 - (pkgProblemResolver *) resolver {
3463 - (pkgAcquire &) fetcher {
3467 - (pkgSourceList &) list {
3471 - (NSArray *) packages {
3472 return (NSArray *) packages_;
3475 - (NSArray *) sources {
3479 - (Source *) sourceWithKey:(NSString *)key {
3480 for (Source *source in [self sources]) {
3481 if ([[source key] isEqualToString:key])
3486 - (bool) popErrorWithTitle:(NSString *)title {
3489 while (!_error->empty()) {
3491 bool warning(!_error->PopMessage(error));
3496 size_t size(error.size());
3497 if (size == 0 || error[size - 1] != '\n')
3499 error.resize(size - 1);
3502 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3504 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3505 if (warning && no_pubkey(error.c_str()))
3508 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3514 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3515 return [self popErrorWithTitle:title] || !success;
3518 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3519 @synchronized (self) {
3522 [self releasePackages];
3525 [sourceList_ removeAllObjects];
3545 apr_pool_clear(pool_);
3547 NSRecycleZone(zone_);
3548 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3550 int chk(creat("/tmp/cydia.chk", 0644));
3554 if (invocation != nil)
3555 [invocation invoke];
3557 NSString *title(UCLocalize("DATABASE"));
3559 list_ = new pkgSourceList();
3560 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3563 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3564 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3565 [sourceList_ addObject:object];
3569 OpProgress progress;
3571 if (!cache_.Open(progress, true)) {
3572 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3573 while (!_error->empty()) {
3575 bool warning(!_error->PopMessage(error));
3577 lprintf("cache_.Open():[%s]\n", error.c_str());
3579 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3583 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3584 repair = @selector(configure);
3585 //else if (error == "The package lists or status file could not be parsed or opened.")
3586 // repair = @selector(update);
3587 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3588 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3589 // else if (error == "Malformed Status line")
3590 // else if (error == "The list of sources could not be read.")
3592 if (repair != NULL) {
3594 [delegate_ repairWithSelector:repair];
3603 unlink("/tmp/cydia.chk");
3605 now_ = [[NSDate date] timeIntervalSince1970];
3607 policy_ = new pkgDepCache::Policy();
3608 records_ = new pkgRecords(cache_);
3609 resolver_ = new pkgProblemResolver(cache_);
3610 fetcher_ = new pkgAcquire(&status_);
3613 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3614 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3618 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3621 if (cache_->BrokenCount() != 0) {
3622 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3625 if (cache_->BrokenCount() != 0) {
3626 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3630 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3634 for (Source *object in (id) sourceList_) {
3635 metaIndex *source([object metaIndex]);
3636 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3637 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3638 // XXX: this could be more intelligent
3639 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3640 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3642 sourceMap_[cached->ID] = object;
3647 /*std::vector<Package *> packages;
3648 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3653 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3654 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3655 //packages.push_back(package);
3656 CFArrayAppendValue(packages_, CFRetain(package));
3660 /*if (packages.empty())
3661 packages_ = [[NSArray alloc] init];
3663 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3666 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3667 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3668 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3676 /*if (!packages.empty())
3677 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3678 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3680 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3682 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3684 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3688 size_t count(CFArrayGetCount(packages_));
3689 MetaFile_->active_ = count;
3691 for (size_t index(0); index != count; ++index)
3692 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3699 @synchronized (self) {
3701 resolver_ = new pkgProblemResolver(cache_);
3703 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3704 if (!cache_[iterator].Keep())
3705 cache_->MarkKeep(iterator, false);
3706 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3707 cache_->SetReInstall(iterator, false);
3710 - (void) configure {
3711 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3713 system([dpkg UTF8String]);
3718 @synchronized (self) {
3719 // XXX: I don't remember this condition
3724 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3726 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3728 if ([self popErrorWithTitle:title])
3732 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3734 CydiaLogCleaner cleaner;
3735 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3742 fetcher_->Shutdown();
3744 pkgRecords records(cache_);
3746 lock_ = new FileFd();
3747 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3749 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3751 if ([self popErrorWithTitle:title])
3755 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3758 manager_ = (_system->CreatePM(cache_));
3759 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3766 bool substrate(RestartSubstrate_);
3767 RestartSubstrate_ = false;
3769 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3771 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3773 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3775 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3776 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3779 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3781 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3783 [self popErrorWithTitle:title];
3787 bool failed = false;
3788 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3789 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3791 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3794 std::string uri = (*item)->DescURI();
3795 std::string error = (*item)->ErrorText;
3797 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3800 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3801 [delegate_ addProgressEventOnMainThread:event forTask:title];
3804 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3812 RestartSubstrate_ = true;
3815 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3816 if ([self popErrorWithTitle:title])
3819 if (result == pkgPackageManager::Failed) {
3824 if (result != pkgPackageManager::Completed) {
3829 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3831 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3833 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3834 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3837 if (![before isEqualToArray:after])
3842 NSString *title(UCLocalize("UPGRADE"));
3843 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3849 [self updateWithStatus:status_];
3852 - (void) updateWithStatus:(Status &)status {
3853 NSString *title(UCLocalize("REFRESHING_DATA"));
3856 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3860 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3861 if ([self popErrorWithTitle:title])
3864 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3866 bool success(ListUpdate(status, list, PulseInterval_));
3867 if (status.WasCancelled())
3870 [self popErrorWithTitle:title forOperation:success];
3871 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3875 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3878 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3879 delegate_ = delegate;
3882 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3883 progress_ = delegate;
3884 status_.setDelegate(delegate);
3887 - (NSObject<ProgressDelegate> *) progressDelegate {
3891 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3892 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3893 return i == sourceMap_.end() ? nil : i->second;
3896 - (NSString *) mappedSectionForPointer:(const char *)section {
3897 _H<NSString> *mapped;
3899 _profile(Database$mappedSectionForPointer$Cache)
3900 mapped = §ions_[section];
3903 if (*mapped == NULL) {
3904 size_t length(strlen(section));
3905 char spaced[length + 1];
3907 _profile(Database$mappedSectionForPointer$Replace)
3908 for (size_t index(0); index != length; ++index)
3909 spaced[index] = section[index] == '_' ? ' ' : section[index];
3910 spaced[length] = '\0';
3915 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3916 string = [NSString stringWithUTF8String:spaced];
3919 _profile(Database$mappedSectionForPointer$Map)
3920 string = [SectionMap_ objectForKey:string] ?: string;
3930 static _H<NSMutableSet> Diversions_;
3932 @interface Diversion : NSObject {
3935 _H<NSString> format_;
3940 @implementation Diversion
3942 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3943 if ((self = [super init]) != nil) {
3944 pattern_ = [from UTF8String];
3950 - (NSString *) divert:(NSString *)url {
3951 return !pattern_(url) ? nil : pattern_->*format_;
3954 + (NSURL *) divertURL:(NSURL *)url {
3956 NSString *href([url absoluteString]);
3958 for (Diversion *diversion in (id) Diversions_)
3959 if (NSString *diverted = [diversion divert:href]) {
3961 NSLog(@"div: %@", diverted);
3963 url = [NSURL URLWithString:diverted];
3970 - (NSString *) key {
3974 - (NSUInteger) hash {
3978 - (BOOL) isEqual:(Diversion *)object {
3979 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3984 @interface CydiaObject : NSObject {
3985 _H<CyteWebViewController> indirect_;
3986 _transient id delegate_;
3989 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3995 @interface CydiaWebViewController : CyteWebViewController {
3996 _H<CydiaObject> cydia_;
3999 + (void) addDiversion:(Diversion *)diversion;
4000 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4001 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4002 - (void) setDelegate:(id)delegate;
4006 /* Web Scripting {{{ */
4007 @implementation CydiaObject
4009 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4010 if ((self = [super init]) != nil) {
4011 indirect_ = (CyteWebViewController *) indirect;
4015 - (void) setDelegate:(id)delegate {
4016 delegate_ = delegate;
4019 + (NSArray *) _attributeKeys {
4020 return [NSArray arrayWithObjects:
4023 @"coreFoundationVersionNumber",
4040 - (NSArray *) attributeKeys {
4041 return [[self class] _attributeKeys];
4044 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4045 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4048 - (NSString *) version {
4052 - (NSString *) build {
4056 - (NSString *) coreFoundationVersionNumber {
4057 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4060 - (NSString *) device {
4061 return [[UIDevice currentDevice] uniqueIdentifier];
4064 - (NSString *) firmware {
4065 return [[UIDevice currentDevice] systemVersion];
4068 - (NSString *) hostname {
4069 return [[UIDevice currentDevice] name];
4072 - (NSString *) idiom {
4073 return (id) Idiom_ ?: [NSNull null];
4076 - (NSString *) mcc {
4077 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4078 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4082 - (NSString *) mnc {
4083 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4084 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4088 - (NSString *) operator {
4089 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4090 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4094 - (NSString *) bbsnum {
4095 return (id) BBSNum_ ?: [NSNull null];
4098 - (NSString *) ecid {
4099 return (id) ChipID_ ?: [NSNull null];
4102 - (NSString *) serial {
4103 return SerialNumber_;
4106 - (NSString *) role {
4107 return (id) Role_ ?: [NSNull null];
4110 - (NSString *) model {
4111 return [NSString stringWithUTF8String:Machine_];
4114 - (NSString *) token {
4115 return (id) Token_ ?: [NSNull null];
4118 + (NSString *) webScriptNameForSelector:(SEL)selector {
4120 else if (selector == @selector(addBridgedHost:))
4121 return @"addBridgedHost";
4122 else if (selector == @selector(addInsecureHost:))
4123 return @"addInsecureHost";
4124 else if (selector == @selector(addInternalRedirect::))
4125 return @"addInternalRedirect";
4126 else if (selector == @selector(addPipelinedHost:scheme:))
4127 return @"addPipelinedHost";
4128 else if (selector == @selector(addSource:::))
4129 return @"addSource";
4130 else if (selector == @selector(addTokenHost:))
4131 return @"addTokenHost";
4132 else if (selector == @selector(addTrivialSource:))
4133 return @"addTrivialSource";
4134 else if (selector == @selector(close))
4136 else if (selector == @selector(du:))
4138 else if (selector == @selector(stringWithFormat:arguments:))
4140 else if (selector == @selector(getAllSources))
4141 return @"getAllSources";
4142 else if (selector == @selector(getKernelNumber:))
4143 return @"getKernelNumber";
4144 else if (selector == @selector(getKernelString:))
4145 return @"getKernelString";
4146 else if (selector == @selector(getInstalledPackages))
4147 return @"getInstalledPackages";
4148 else if (selector == @selector(getIORegistryEntry::))
4149 return @"getIORegistryEntry";
4150 else if (selector == @selector(getLocaleIdentifier))
4151 return @"getLocaleIdentifier";
4152 else if (selector == @selector(getPreferredLanguages))
4153 return @"getPreferredLanguages";
4154 else if (selector == @selector(getPackageById:))
4155 return @"getPackageById";
4156 else if (selector == @selector(getMetadataKeys))
4157 return @"getMetadataKeys";
4158 else if (selector == @selector(getMetadataValue:))
4159 return @"getMetadataValue";
4160 else if (selector == @selector(getSessionValue:))
4161 return @"getSessionValue";
4162 else if (selector == @selector(installPackages:))
4163 return @"installPackages";
4164 else if (selector == @selector(isReachable:))
4165 return @"isReachable";
4166 else if (selector == @selector(localizedStringForKey:value:table:))
4168 else if (selector == @selector(popViewController:))
4169 return @"popViewController";
4170 else if (selector == @selector(refreshSources))
4171 return @"refreshSources";
4172 else if (selector == @selector(removeButton))
4173 return @"removeButton";
4174 else if (selector == @selector(saveConfig))
4175 return @"saveConfig";
4176 else if (selector == @selector(setMetadataValue::))
4177 return @"setMetadataValue";
4178 else if (selector == @selector(setSessionValue::))
4179 return @"setSessionValue";
4180 else if (selector == @selector(setShowPromoted:))
4181 return @"setShowPromoted";
4182 else if (selector == @selector(substitutePackageNames:))
4183 return @"substitutePackageNames";
4184 else if (selector == @selector(scrollToBottom:))
4185 return @"scrollToBottom";
4186 else if (selector == @selector(setAllowsNavigationAction:))
4187 return @"setAllowsNavigationAction";
4188 else if (selector == @selector(setBadgeValue:))
4189 return @"setBadgeValue";
4190 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4191 return @"setButtonImage";
4192 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4193 return @"setButtonTitle";
4194 else if (selector == @selector(setHidesBackButton:))
4195 return @"setHidesBackButton";
4196 else if (selector == @selector(setHidesNavigationBar:))
4197 return @"setHidesNavigationBar";
4198 else if (selector == @selector(setNavigationBarStyle:))
4199 return @"setNavigationBarStyle";
4200 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4201 return @"setNavigationBarTintColor";
4202 else if (selector == @selector(setPasteboardString:))
4203 return @"setPasteboardString";
4204 else if (selector == @selector(setPasteboardURL:))
4205 return @"setPasteboardURL";
4206 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4207 return @"setScrollAlwaysBounceVertical";
4208 else if (selector == @selector(setScrollIndicatorStyle:))
4209 return @"setScrollIndicatorStyle";
4210 else if (selector == @selector(setToken:))
4212 else if (selector == @selector(setViewportWidth:))
4213 return @"setViewportWidth";
4214 else if (selector == @selector(statfs:))
4216 else if (selector == @selector(supports:))
4218 else if (selector == @selector(unload))
4224 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4225 return [self webScriptNameForSelector:selector] == nil;
4228 - (BOOL) supports:(NSString *)feature {
4229 return [feature isEqualToString:@"window.open"];
4233 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4236 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4237 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4240 - (void) setScrollIndicatorStyle:(NSString *)style {
4241 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4244 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4245 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4248 - (NSNumber *) getKernelNumber:(NSString *)name {
4249 const char *string([name UTF8String]);
4252 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4253 return (id) [NSNull null];
4255 if (size != sizeof(int))
4256 return (id) [NSNull null];
4259 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4260 return (id) [NSNull null];
4262 return [NSNumber numberWithInt:value];
4265 - (NSString *) getKernelString:(NSString *)name {
4266 const char *string([name UTF8String]);
4269 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4270 return (id) [NSNull null];
4272 char value[size + 1];
4273 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4274 return (id) [NSNull null];
4276 // XXX: just in case you request something ludicrous
4279 return [NSString stringWithCString:value];
4282 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4283 NSObject *value(CYIOGetValue([path UTF8String], entry));
4286 if ([value isKindOfClass:[NSData class]])
4287 value = CYHex((NSData *) value);
4292 - (NSArray *) getMetadataKeys {
4293 @synchronized (Values_) {
4294 return [Values_ allKeys];
4297 - (void) _setShowPromoted:(NSNumber *)value {
4298 [Metadata_ setObject:value forKey:@"ShowPromoted"];
4302 - (void) setShowPromoted:(NSNumber *)value {
4303 [self performSelectorOnMainThread:@selector(_setShowPromoted:) withObject:value waitUntilDone:NO];
4306 - (id) getMetadataValue:(NSString *)key {
4307 @synchronized (Values_) {
4308 return [Values_ objectForKey:key];
4311 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4312 @synchronized (Values_) {
4313 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4314 [Values_ removeObjectForKey:key];
4316 [Values_ setObject:value forKey:key];
4318 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4321 - (id) getSessionValue:(NSString *)key {
4322 @synchronized (SessionData_) {
4323 return [SessionData_ objectForKey:key];
4326 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4327 @synchronized (SessionData_) {
4328 if (value == (id) [WebUndefined undefined])
4329 [SessionData_ removeObjectForKey:key];
4331 [SessionData_ setObject:value forKey:key];
4334 - (void) addBridgedHost:(NSString *)host {
4335 @synchronized (HostConfig_) {
4336 [BridgedHosts_ addObject:host];
4339 - (void) addInsecureHost:(NSString *)host {
4340 @synchronized (HostConfig_) {
4341 [InsecureHosts_ addObject:host];
4344 - (void) addTokenHost:(NSString *)host {
4345 @synchronized (HostConfig_) {
4346 [TokenHosts_ addObject:host];
4349 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4350 @synchronized (HostConfig_) {
4351 if (scheme != (id) [WebUndefined undefined])
4352 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4354 [PipelinedHosts_ addObject:host];
4357 - (void) popViewController:(NSNumber *)value {
4358 if (value == (id) [WebUndefined undefined])
4359 value = [NSNumber numberWithBool:YES];
4360 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4363 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4364 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4366 for (NSString *section in sections)
4367 [array addObject:section];
4369 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4372 distribution, @"Distribution",
4374 nil] waitUntilDone:NO];
4377 - (void) addTrivialSource:(NSString *)href {
4378 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4381 - (void) refreshSources {
4382 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4385 - (void) saveConfig {
4386 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4389 - (NSArray *) getAllSources {
4390 return [[Database sharedInstance] sources];
4393 - (NSArray *) getInstalledPackages {
4394 Database *database([Database sharedInstance]);
4395 @synchronized (database) {
4396 NSArray *packages([database packages]);
4397 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4398 for (Package *package in packages)
4399 if (![package uninstalled])
4400 [installed addObject:package];
4404 - (Package *) getPackageById:(NSString *)id {
4405 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4409 return (Package *) [NSNull null];
4412 - (NSString *) getLocaleIdentifier {
4413 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4416 - (NSArray *) getPreferredLanguages {
4420 - (NSArray *) statfs:(NSString *)path {
4423 if (path == nil || statfs([path UTF8String], &stat) == -1)
4426 return [NSArray arrayWithObjects:
4427 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4428 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4429 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4433 - (NSNumber *) du:(NSString *)path {
4434 NSNumber *value(nil);
4437 _assert(pipe(fds) != -1);
4439 pid_t pid(ExecFork());
4441 _assert(dup2(fds[1], 1) != -1);
4442 _assert(close(fds[0]) != -1);
4443 _assert(close(fds[1]) != -1);
4444 /* XXX: this should probably not use du */
4445 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4450 _assert(close(fds[1]) != -1);
4452 if (FILE *du = fdopen(fds[0], "r")) {
4454 while (fgets(line, sizeof(line), du) != NULL) {
4455 size_t length(strlen(line));
4456 while (length != 0 && line[length - 1] == '\n')
4457 line[--length] = '\0';
4458 if (char *tab = strchr(line, '\t')) {
4460 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4465 } else _assert(close(fds[0]));
4473 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4476 - (NSNumber *) isReachable:(NSString *)name {
4477 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4480 - (void) installPackages:(NSArray *)packages {
4481 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4484 - (NSString *) substitutePackageNames:(NSString *)message {
4485 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4486 for (size_t i(0), e([words count]); i != e; ++i) {
4487 NSString *word([words objectAtIndex:i]);
4488 if (Package *package = [[Database sharedInstance] packageWithName:word])
4489 [words replaceObjectAtIndex:i withObject:[package name]];
4492 return [words componentsJoinedByString:@" "];
4495 - (void) removeButton {
4496 [indirect_ removeButton];
4499 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4500 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4503 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4504 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4507 - (void) setBadgeValue:(id)value {
4508 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4511 - (void) setAllowsNavigationAction:(NSString *)value {
4512 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4515 - (void) setHidesBackButton:(NSString *)value {
4516 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4519 - (void) setHidesNavigationBar:(NSString *)value {
4520 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4523 - (void) setNavigationBarStyle:(NSString *)value {
4524 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4527 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4528 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4529 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4530 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4533 - (void) setPasteboardString:(NSString *)value {
4534 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4537 - (void) setPasteboardURL:(NSString *)value {
4538 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4541 - (void) _setToken:(NSString *)token {
4545 [Metadata_ removeObjectForKey:@"Token"];
4547 [Metadata_ setObject:Token_ forKey:@"Token"];
4552 - (void) setToken:(NSString *)token {
4553 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4556 - (void) scrollToBottom:(NSNumber *)animated {
4557 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4560 - (void) setViewportWidth:(float)width {
4561 [indirect_ setViewportWidthOnMainThread:width];
4564 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4565 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4566 unsigned count([arguments count]);
4568 for (unsigned i(0); i != count; ++i)
4569 values[i] = [arguments objectAtIndex:i];
4570 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4573 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4574 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4576 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4578 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4584 @interface NSURL (CydiaSecure)
4587 @implementation NSURL (CydiaSecure)
4589 - (bool) isCydiaSecure {
4590 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4593 @synchronized (HostConfig_) {
4594 if ([InsecureHosts_ containsObject:[self host]])
4603 /* Cydia Browser Controller {{{ */
4604 @implementation CydiaWebViewController
4606 - (NSURL *) navigationURL {
4607 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4610 + (void) _initialize {
4611 [super _initialize];
4613 Diversions_ = [NSMutableSet setWithCapacity:0];
4616 + (void) addDiversion:(Diversion *)diversion {
4617 [Diversions_ addObject:diversion];
4620 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4621 [super webView:view didClearWindowObject:window forFrame:frame];
4622 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4625 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4626 WebDataSource *source([frame dataSource]);
4627 NSURLResponse *response([source response]);
4628 NSURL *url([response URL]);
4629 NSString *scheme([[url scheme] lowercaseString]);
4631 bool bridged(false);
4633 @synchronized (HostConfig_) {
4634 if ([scheme isEqualToString:@"file"])
4636 else if ([scheme isEqualToString:@"https"])
4637 if ([BridgedHosts_ containsObject:[url host]])
4642 [window setValue:cydia forKey:@"cydia"];
4645 - (void) _setupMail:(MFMailComposeViewController *)controller {
4646 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4648 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4649 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4652 - (NSURL *) URLWithURL:(NSURL *)url {
4653 return [Diversion divertURL:url];
4656 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4657 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4660 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4661 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4663 NSURL *url([copy URL]);
4664 NSString *href([url absoluteString]);
4665 NSString *host([url host]);
4667 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4668 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4669 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4670 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4673 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4674 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4676 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4680 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4681 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4682 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4683 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4688 @synchronized (HostConfig_) {
4689 bridged = [BridgedHosts_ containsObject:host];
4690 token = [TokenHosts_ containsObject:host];
4693 if ([url isCydiaSecure]) {
4695 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4696 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4698 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4699 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4706 - (void) setDelegate:(id)delegate {
4707 [super setDelegate:delegate];
4708 [cydia_ setDelegate:delegate];
4711 - (NSString *) applicationNameForUserAgent {
4716 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4717 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4723 @interface AppCacheController : CydiaWebViewController {
4728 @implementation AppCacheController
4730 - (void) didReceiveMemoryWarning {
4731 // XXX: this doesn't work
4734 - (bool) retainsNetworkActivityIndicator {
4742 @interface NSObject (CydiaScript)
4743 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4746 @implementation NSObject (CydiaScript)
4748 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4754 @implementation NSArray (CydiaScript)
4756 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4757 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4758 for (size_t i(0), e([self count]); i != e; ++i)
4759 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4765 @implementation NSDictionary (CydiaScript)
4767 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4768 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4770 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4777 /* Confirmation Controller {{{ */
4778 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4779 if (!iterator.end())
4780 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4781 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4783 pkgCache::PkgIterator package(dep.TargetPkg());
4786 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4793 @protocol ConfirmationControllerDelegate
4794 - (void) cancelAndClear:(bool)clear;
4795 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4799 @interface ConfirmationController : CydiaWebViewController {
4800 _transient Database *database_;
4802 _H<UIAlertView> essential_;
4804 _H<NSDictionary> changes_;
4805 _H<NSMutableArray> issues_;
4806 _H<NSDictionary> sizes_;
4811 - (id) initWithDatabase:(Database *)database;
4815 @implementation ConfirmationController
4819 RestartSubstrate_ = true;
4820 [delegate_ confirmWithNavigationController:[self navigationController]];
4823 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4824 NSString *context([alert context]);
4826 if ([context isEqualToString:@"remove"]) {
4827 if (button == [alert cancelButtonIndex])
4828 [self dismissModalViewControllerAnimated:YES];
4829 else if (button == [alert firstOtherButtonIndex]) {
4830 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
4833 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4834 } else if ([context isEqualToString:@"unable"]) {
4835 [self dismissModalViewControllerAnimated:YES];
4836 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4838 [super alertView:alert clickedButtonAtIndex:button];
4842 - (void) _doContinue {
4843 [delegate_ cancelAndClear:NO];
4844 [self dismissModalViewControllerAnimated:YES];
4847 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4848 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4852 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4853 [super webView:view didClearWindowObject:window forFrame:frame];
4855 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4856 (id) changes_, @"changes",
4857 (id) issues_, @"issues",
4858 (id) sizes_, @"sizes",
4860 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4863 - (id) initWithDatabase:(Database *)database {
4864 if ((self = [super init]) != nil) {
4865 database_ = database;
4867 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4868 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4869 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4870 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4871 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4875 pkgCacheFile &cache([database_ cache]);
4876 NSArray *packages([database_ packages]);
4877 pkgDepCache::Policy *policy([database_ policy]);
4879 issues_ = [NSMutableArray arrayWithCapacity:4];
4881 for (Package *package in packages) {
4882 pkgCache::PkgIterator iterator([package iterator]);
4883 NSString *name([package id]);
4885 if ([package broken]) {
4886 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4888 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4890 reasons, @"reasons",
4893 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4897 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4898 pkgCache::DepIterator start;
4899 pkgCache::DepIterator end;
4900 dep.GlobOr(start, end); // ++dep
4902 if (!cache->IsImportantDep(end))
4904 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4907 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4909 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4910 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4911 clauses, @"clauses",
4915 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4917 pkgCache::PkgIterator target(start.TargetPkg());
4918 if (target->ProvidesList != 0)
4919 reason = @"missing";
4921 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4923 reason = @"installed";
4924 installed = [NSString stringWithUTF8String:ver.VerStr()];
4925 } else if (!cache[target].CandidateVerIter(cache).end())
4926 reason = @"uninstalled";
4927 else if (target->ProvidesList == 0)
4928 reason = @"uninstallable";
4930 reason = @"virtual";
4933 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4934 [NSString stringWithUTF8String:start.CompType()], @"operator",
4935 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4938 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4939 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4940 version, @"version",
4942 installed, @"installed",
4945 // yes, seriously. (wtf?)
4953 pkgDepCache::StateCache &state(cache[iterator]);
4955 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4957 if (state.NewInstall())
4958 [installs addObject:name];
4959 // XXX: else if (state.Install())
4960 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4961 [reinstalls addObject:name];
4962 // XXX: move before previous if
4963 else if (state.Upgrade())
4964 [upgrades addObject:name];
4965 else if (state.Downgrade())
4966 [downgrades addObject:name];
4967 else if (!state.Delete())
4968 // XXX: _assert(state.Keep());
4970 else if (special_r(name))
4971 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4972 [NSNull null], @"package",
4973 [NSArray arrayWithObjects:
4974 [NSDictionary dictionaryWithObjectsAndKeys:
4975 @"Conflicts", @"relationship",
4976 [NSArray arrayWithObjects:
4977 [NSDictionary dictionaryWithObjectsAndKeys:
4979 [NSNull null], @"version",
4980 @"installed", @"reason",
4987 if ([package essential])
4989 [removes addObject:name];
4992 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4993 substrate_ |= DepSubstrate(iterator.CurrentVer());
4998 else if (Advanced_) {
4999 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5001 essential_ = [[[UIAlertView alloc]
5002 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5003 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5005 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5007 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5011 [essential_ setContext:@"remove"];
5012 [essential_ setNumberOfRows:2];
5014 essential_ = [[[UIAlertView alloc]
5015 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5016 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5018 cancelButtonTitle:UCLocalize("OKAY")
5019 otherButtonTitles:nil
5022 [essential_ setContext:@"unable"];
5025 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5026 installs, @"installs",
5027 reinstalls, @"reinstalls",
5028 upgrades, @"upgrades",
5029 downgrades, @"downgrades",
5030 removes, @"removes",
5033 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5034 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5035 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5038 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5042 - (UIBarButtonItem *) leftButton {
5043 return [[[UIBarButtonItem alloc]
5044 initWithTitle:UCLocalize("CANCEL")
5045 style:UIBarButtonItemStylePlain
5047 action:@selector(cancelButtonClicked)
5052 - (void) applyRightButton {
5053 if ([issues_ count] == 0 && ![self isLoading])
5054 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5055 initWithTitle:UCLocalize("CONFIRM")
5056 style:UIBarButtonItemStyleDone
5058 action:@selector(confirmButtonClicked)
5061 [[self navigationItem] setRightBarButtonItem:nil];
5065 - (void) cancelButtonClicked {
5066 [delegate_ cancelAndClear:YES];
5067 [self dismissModalViewControllerAnimated:YES];
5071 - (void) confirmButtonClicked {
5072 if (essential_ != nil)
5082 /* Progress Data {{{ */
5083 @interface CydiaProgressData : NSObject {
5084 _transient id delegate_;
5093 _H<NSMutableArray> events_;
5094 _H<NSString> title_;
5096 _H<NSString> status_;
5097 _H<NSString> finish_;
5102 @implementation CydiaProgressData
5104 + (NSArray *) _attributeKeys {
5105 return [NSArray arrayWithObjects:
5117 - (NSArray *) attributeKeys {
5118 return [[self class] _attributeKeys];
5121 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5122 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5126 if ((self = [super init]) != nil) {
5127 events_ = [NSMutableArray arrayWithCapacity:32];
5135 - (void) setDelegate:(id)delegate {
5136 delegate_ = delegate;
5139 - (void) setPercent:(float)value {
5143 - (NSNumber *) percent {
5144 return [NSNumber numberWithFloat:percent_];
5147 - (void) setCurrent:(float)value {
5151 - (NSNumber *) current {
5152 return [NSNumber numberWithFloat:current_];
5155 - (void) setTotal:(float)value {
5159 - (NSNumber *) total {
5160 return [NSNumber numberWithFloat:total_];
5163 - (void) setSpeed:(float)value {
5167 - (NSNumber *) speed {
5168 return [NSNumber numberWithFloat:speed_];
5171 - (NSArray *) events {
5175 - (void) removeAllEvents {
5176 [events_ removeAllObjects];
5179 - (void) addEvent:(CydiaProgressEvent *)event {
5180 [events_ addObject:event];
5183 - (void) setTitle:(NSString *)text {
5187 - (NSString *) title {
5191 - (void) setFinish:(NSString *)text {
5195 - (NSString *) finish {
5196 return (id) finish_ ?: [NSNull null];
5199 - (void) setRunning:(bool)running {
5203 - (NSNumber *) running {
5204 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5209 /* Progress Controller {{{ */
5210 @interface ProgressController : CydiaWebViewController <
5213 _transient Database *database_;
5214 _H<CydiaProgressData, 1> progress_;
5218 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5220 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5222 - (void) setTitle:(NSString *)title;
5223 - (void) setCancellable:(bool)cancellable;
5227 @implementation ProgressController
5230 [database_ setProgressDelegate:nil];
5234 - (UIBarButtonItem *) leftButton {
5235 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5236 initWithTitle:UCLocalize("CANCEL")
5237 style:UIBarButtonItemStylePlain
5239 action:@selector(cancel)
5240 ] autorelease] : nil;
5243 - (void) updateCancel {
5244 [super applyLeftButton];
5247 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5248 if ((self = [super init]) != nil) {
5249 database_ = database;
5250 delegate_ = delegate;
5252 [database_ setProgressDelegate:self];
5254 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5255 [progress_ setDelegate:self];
5257 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5259 [scroller_ setBackgroundColor:[UIColor blackColor]];
5261 [[self navigationItem] setHidesBackButton:YES];
5263 [self updateCancel];
5267 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5268 [super webView:view didClearWindowObject:window forFrame:frame];
5269 [window setValue:progress_ forKey:@"cydiaProgress"];
5272 - (void) updateProgress {
5273 [self dispatchEvent:@"CydiaProgressUpdate"];
5276 - (void) viewWillAppear:(BOOL)animated {
5277 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5278 [super viewWillAppear:animated];
5281 - (void) reloadSpringBoard {
5282 pid_t pid(ExecFork());
5284 pid_t pid(ExecFork());
5286 execl("/usr/bin/sbreload", "sbreload", NULL);
5297 system("/usr/bin/killall SpringBoard");
5301 UpdateExternalStatus(0);
5304 [delegate_ saveState];
5308 [delegate_ returnToCydia];
5312 [delegate_ terminateWithSuccess];
5313 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5314 [delegate_ suspendWithAnimation:YES];
5316 [delegate_ suspend];*/
5328 UIProgressHUD *hud([delegate_ addProgressHUD]);
5329 [hud setText:UCLocalize("LOADING")];
5330 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5336 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5337 SBReboot(SBSSpringBoardServerPort());
5339 reboot2(RB_AUTOBOOT);
5346 - (void) setTitle:(NSString *)title {
5347 [progress_ setTitle:title];
5348 [self updateProgress];
5351 - (UIBarButtonItem *) rightButton {
5352 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5353 initWithTitle:UCLocalize("CLOSE")
5354 style:UIBarButtonItemStylePlain
5356 action:@selector(close)
5360 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5361 UpdateExternalStatus(1);
5363 [progress_ setRunning:true];
5364 [self setTitle:title];
5365 // implicit updateProgress
5367 SHA1SumValue notifyconf; {
5369 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5372 MMap mmap(file, MMap::ReadOnly);
5374 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5375 notifyconf = sha1.Result();
5379 SHA1SumValue springlist; {
5381 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5384 MMap mmap(file, MMap::ReadOnly);
5386 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5387 springlist = sha1.Result();
5391 if (invocation != nil) {
5392 [invocation yieldToSelector:@selector(invoke)];
5393 [self setTitle:@"COMPLETE"];
5398 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5401 MMap mmap(file, MMap::ReadOnly);
5403 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5404 if (!(notifyconf == sha1.Result()))
5411 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5414 MMap mmap(file, MMap::ReadOnly);
5416 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5417 if (!(springlist == sha1.Result()))
5423 if (RestartSubstrate_)
5427 RestartSubstrate_ = false;
5430 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5431 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5432 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5433 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5434 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5437 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5439 [progress_ setRunning:false];
5440 [self updateProgress];
5442 [self applyRightButton];
5445 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5446 [progress_ addEvent:event];
5447 [self updateProgress];
5450 - (bool) isProgressCancelled {
5451 return cancel_ == 2;
5456 [self updateCancel];
5459 - (void) setCancellable:(bool)cancellable {
5460 unsigned cancel(cancel_);
5464 else if (cancel_ == 0)
5467 if (cancel != cancel_)
5468 [self updateCancel];
5471 - (void) setProgressCancellable:(NSNumber *)cancellable {
5472 [self setCancellable:[cancellable boolValue]];
5475 - (void) setProgressPercent:(NSNumber *)percent {
5476 [progress_ setPercent:[percent floatValue]];
5477 [self updateProgress];
5480 - (void) setProgressStatus:(NSDictionary *)status {
5481 if (status == nil) {
5482 [progress_ setCurrent:0];
5483 [progress_ setTotal:0];
5484 [progress_ setSpeed:0];
5486 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5488 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5489 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5490 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5493 [self updateProgress];
5499 /* Package Cell {{{ */
5500 @interface PackageCell : CyteTableViewCell <
5501 CyteTableViewCellDelegate
5505 _H<NSString> description_;
5507 _H<NSString> source_;
5509 _H<UIImage> placard_;
5513 - (PackageCell *) init;
5514 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5516 - (void) drawContentRect:(CGRect)rect;
5520 @implementation PackageCell
5522 - (PackageCell *) init {
5523 CGRect frame(CGRectMake(0, 0, 320, 74));
5524 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5525 UIView *content([self contentView]);
5526 CGRect bounds([content bounds]);
5528 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5529 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5530 [content addSubview:content_];
5532 [content_ setDelegate:self];
5533 [content_ setOpaque:YES];
5537 - (NSString *) accessibilityLabel {
5541 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5542 summarized_ = summary;
5552 [content_ setBackgroundColor:[UIColor whiteColor]];
5556 Source *source = [package source];
5558 icon_ = [package icon];
5560 if (NSString *name = [package name])
5561 name_ = [NSString stringWithString:name];
5563 NSString *description(nil);
5565 if (description == nil && IsWildcat_)
5566 description = [package longDescription];
5567 if (description == nil)
5568 description = [package shortDescription];
5570 if (description != nil)
5571 description_ = [NSString stringWithString:description];
5573 commercial_ = [package isCommercial];
5575 NSString *label = nil;
5576 bool trusted = false;
5578 if (source != nil) {
5579 label = [source label];
5580 trusted = [source trusted];
5581 } else if ([[package id] isEqualToString:@"firmware"])
5582 label = UCLocalize("APPLE");
5584 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5586 NSString *from(label);
5588 NSString *section = [package simpleSection];
5589 if (section != nil && ![section isEqualToString:label]) {
5590 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5591 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5594 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5596 if (NSString *purpose = [package primaryPurpose])
5597 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5602 if (NSString *mode = [package mode]) {
5603 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5604 color = RemovingColor_;
5605 //placard = @"removing";
5607 color = InstallingColor_;
5608 //placard = @"installing";
5611 // XXX: the removing/installing placards are not @2x
5614 color = [UIColor whiteColor];
5616 if ([package installed] != nil)
5617 placard = @"installed";
5622 [content_ setBackgroundColor:color];
5625 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5628 [self setNeedsDisplay];
5629 [content_ setNeedsDisplay];
5632 - (void) drawSummaryContentRect:(CGRect)rect {
5633 bool highlighted(highlighted_);
5634 float width([self bounds].size.width);
5638 rect.size = [(UIImage *) icon_ size];
5640 while (rect.size.width > 16 || rect.size.height > 16) {
5641 rect.size.width /= 2;
5642 rect.size.height /= 2;
5645 rect.origin.x = 18 - rect.size.width / 2;
5646 rect.origin.y = 18 - rect.size.height / 2;
5648 [icon_ drawInRect:rect];
5651 if (badge_ != nil) {
5653 rect.size = [(UIImage *) badge_ size];
5655 rect.size.width /= 4;
5656 rect.size.height /= 4;
5658 rect.origin.x = 23 - rect.size.width / 2;
5659 rect.origin.y = 23 - rect.size.height / 2;
5661 [badge_ drawInRect:rect];
5668 UISetColor(commercial_ ? Purple_ : Black_);
5669 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5671 if (placard_ != nil)
5672 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5675 - (void) drawNormalContentRect:(CGRect)rect {
5676 bool highlighted(highlighted_);
5677 float width([self bounds].size.width);
5681 rect.size = [(UIImage *) icon_ size];
5683 while (rect.size.width > 32 || rect.size.height > 32) {
5684 rect.size.width /= 2;
5685 rect.size.height /= 2;
5688 rect.origin.x = 25 - rect.size.width / 2;
5689 rect.origin.y = 25 - rect.size.height / 2;
5691 [icon_ drawInRect:rect];
5694 if (badge_ != nil) {
5696 rect.size = [(UIImage *) badge_ size];
5698 rect.size.width /= 2;
5699 rect.size.height /= 2;
5701 rect.origin.x = 36 - rect.size.width / 2;
5702 rect.origin.y = 36 - rect.size.height / 2;
5704 [badge_ drawInRect:rect];
5711 UISetColor(commercial_ ? Purple_ : Black_);
5712 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5713 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5716 UISetColor(commercial_ ? Purplish_ : Gray_);
5717 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5719 if (placard_ != nil)
5720 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5723 - (void) drawContentRect:(CGRect)rect {
5725 [self drawSummaryContentRect:rect];
5727 [self drawNormalContentRect:rect];
5732 /* Section Cell {{{ */
5733 @interface SectionCell : CyteTableViewCell <
5734 CyteTableViewCellDelegate
5736 _H<NSString> basic_;
5737 _H<NSString> section_;
5739 _H<NSString> count_;
5741 _H<UISwitch> switch_;
5745 - (void) setSection:(Section *)section editing:(BOOL)editing;
5749 @implementation SectionCell
5751 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5752 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5753 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5754 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5755 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5757 UIView *content([self contentView]);
5758 CGRect bounds([content bounds]);
5760 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5761 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5762 [content addSubview:content_];
5763 [content_ setBackgroundColor:[UIColor whiteColor]];
5765 [content_ setDelegate:self];
5769 - (void) onSwitch:(id)sender {
5770 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5771 if (metadata == nil) {
5772 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5773 [Sections_ setObject:metadata forKey:basic_];
5776 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5780 - (void) setSection:(Section *)section editing:(BOOL)editing {
5781 if (editing != editing_) {
5783 [switch_ removeFromSuperview];
5785 [self addSubview:switch_];
5794 if (section == nil) {
5795 name_ = UCLocalize("ALL_PACKAGES");
5798 basic_ = [section name];
5799 section_ = [section localized];
5801 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5802 count_ = [NSString stringWithFormat:@"%d", [section count]];
5805 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5808 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5809 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5811 [content_ setNeedsDisplay];
5814 - (void) setFrame:(CGRect)frame {
5815 [super setFrame:frame];
5817 CGRect rect([switch_ frame]);
5818 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5821 - (NSString *) accessibilityLabel {
5825 - (void) drawContentRect:(CGRect)rect {
5826 bool highlighted(highlighted_ && !editing_);
5828 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5833 float width(rect.size.width);
5839 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5841 CGSize size = [count_ sizeWithFont:Font14_];
5845 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5851 /* File Table {{{ */
5852 @interface FileTable : CyteViewController <
5853 UITableViewDataSource,
5856 _transient Database *database_;
5857 _H<Package> package_;
5859 _H<NSMutableArray> files_;
5860 _H<UITableView, 2> list_;
5863 - (id) initWithDatabase:(Database *)database;
5864 - (void) setPackage:(Package *)package;
5868 @implementation FileTable
5870 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5871 return files_ == nil ? 0 : [files_ count];
5874 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5878 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5879 static NSString *reuseIdentifier = @"Cell";
5881 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5883 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5884 [cell setFont:[UIFont systemFontOfSize:16]];
5886 [cell setText:[files_ objectAtIndex:indexPath.row]];
5887 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5892 - (NSURL *) navigationURL {
5893 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5897 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5898 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5899 [list_ setRowHeight:24.0f];
5900 [(UITableView *) list_ setDataSource:self];
5901 [list_ setDelegate:self];
5902 [self setView:list_];
5905 - (void) viewDidLoad {
5906 [super viewDidLoad];
5908 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5911 - (void) releaseSubviews {
5917 [super releaseSubviews];
5920 - (id) initWithDatabase:(Database *)database {
5921 if ((self = [super init]) != nil) {
5922 database_ = database;
5926 - (void) setPackage:(Package *)package {
5930 files_ = [NSMutableArray arrayWithCapacity:32];
5932 if (package != nil) {
5934 name_ = [package id];
5936 if (NSArray *files = [package files])
5937 [files_ addObjectsFromArray:files];
5939 if ([files_ count] != 0) {
5940 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5941 [files_ removeObjectAtIndex:0];
5942 [files_ sortUsingSelector:@selector(compareByPath:)];
5944 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5945 [stack addObject:@"/"];
5947 for (int i(0), e([files_ count]); i != e; ++i) {
5948 NSString *file = [files_ objectAtIndex:i];
5949 while (![file hasPrefix:[stack lastObject]])
5950 [stack removeLastObject];
5951 NSString *directory = [stack lastObject];
5952 [stack addObject:[file stringByAppendingString:@"/"]];
5953 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5954 ([stack count] - 2) * 3, "",
5955 [file substringFromIndex:[directory length]]
5964 - (void) reloadData {
5967 [self setPackage:[database_ packageWithName:name_]];
5972 /* Package Controller {{{ */
5973 @interface CYPackageController : CydiaWebViewController <
5974 UIActionSheetDelegate
5976 _transient Database *database_;
5977 _H<Package> package_;
5980 _H<NSMutableArray> buttons_;
5981 _H<UIBarButtonItem> button_;
5984 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
5988 @implementation CYPackageController
5990 - (NSURL *) navigationURL {
5991 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5994 /* XXX: this is not safe at all... localization of /fail/ */
5995 - (void) _clickButtonWithName:(NSString *)name {
5996 if ([name isEqualToString:UCLocalize("CLEAR")])
5997 [delegate_ clearPackage:package_];
5998 else if ([name isEqualToString:UCLocalize("INSTALL")])
5999 [delegate_ installPackage:package_];
6000 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6001 [delegate_ installPackage:package_];
6002 else if ([name isEqualToString:UCLocalize("REMOVE")])
6003 [delegate_ removePackage:package_];
6004 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6005 [delegate_ installPackage:package_];
6006 else _assert(false);
6009 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6010 NSString *context([sheet context]);
6012 if ([context isEqualToString:@"modify"]) {
6013 if (button != [sheet cancelButtonIndex]) {
6014 NSString *buttonName = [buttons_ objectAtIndex:button];
6015 [self _clickButtonWithName:buttonName];
6018 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6022 - (bool) _allowJavaScriptPanel {
6027 - (void) _customButtonClicked {
6028 int count([buttons_ count]);
6033 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6035 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6036 [buttons addObjectsFromArray:buttons_];
6038 UIActionSheet *sheet = [[[UIActionSheet alloc]
6041 cancelButtonTitle:nil
6042 destructiveButtonTitle:nil
6043 otherButtonTitles:nil
6046 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6048 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6049 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6051 [sheet setContext:@"modify"];
6053 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6057 // We don't want to allow non-commercial packages to do custom things to the install button,
6058 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6059 - (void) customButtonClicked {
6061 [super customButtonClicked];
6063 [self _customButtonClicked];
6066 - (void) reloadButtonClicked {
6067 // Don't reload a commerical package by tapping the loading button,
6068 // but if it's not an Install button, we should forward it on.
6069 if (![package_ uninstalled])
6070 [self _customButtonClicked];
6073 - (void) applyLoadingTitle {
6074 // Don't show "Loading" as the title. Ever.
6077 - (UIBarButtonItem *) rightButton {
6082 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6083 if ((self = [super init]) != nil) {
6084 database_ = database;
6085 buttons_ = [NSMutableArray arrayWithCapacity:4];
6086 name_ = name == nil ? @"" : [NSString stringWithString:name];
6087 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6091 - (void) reloadData {
6094 package_ = [database_ packageWithName:name_];
6096 [buttons_ removeAllObjects];
6098 if (package_ != nil) {
6099 [(Package *) package_ parse];
6101 commercial_ = [package_ isCommercial];
6103 if ([package_ mode] != nil)
6104 [buttons_ addObject:UCLocalize("CLEAR")];
6105 if ([package_ source] == nil);
6106 else if ([package_ upgradableAndEssential:NO])
6107 [buttons_ addObject:UCLocalize("UPGRADE")];
6108 else if ([package_ uninstalled])
6109 [buttons_ addObject:UCLocalize("INSTALL")];
6111 [buttons_ addObject:UCLocalize("REINSTALL")];
6112 if (![package_ uninstalled])
6113 [buttons_ addObject:UCLocalize("REMOVE")];
6117 switch ([buttons_ count]) {
6118 case 0: title = nil; break;
6119 case 1: title = [buttons_ objectAtIndex:0]; break;
6120 default: title = UCLocalize("MODIFY"); break;
6123 button_ = [[[UIBarButtonItem alloc]
6125 style:UIBarButtonItemStylePlain
6127 action:@selector(customButtonClicked)
6131 - (bool) isLoading {
6132 return commercial_ ? [super isLoading] : false;
6138 /* Package List Controller {{{ */
6139 @interface PackageListController : CyteViewController <
6140 UITableViewDataSource,
6143 _transient Database *database_;
6145 _H<NSArray> packages_;
6146 _H<NSMutableArray> sections_;
6147 _H<UITableView, 2> list_;
6148 _H<NSMutableArray> index_;
6149 _H<NSMutableDictionary> indices_;
6150 _H<NSString> title_;
6151 unsigned reloading_;
6154 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6155 - (void) setDelegate:(id)delegate;
6156 - (void) resetCursor;
6161 @implementation PackageListController
6163 - (NSURL *) referrerURL {
6164 return [self navigationURL];
6167 - (bool) isSummarized {
6171 - (bool) showsSections {
6175 - (void) deselectWithAnimation:(BOOL)animated {
6176 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6179 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6180 CGRect base = [[self view] bounds];
6181 base.size.height -= bounds.size.height;
6182 base.origin = [list_ frame].origin;
6184 [UIView beginAnimations:nil context:NULL];
6185 [UIView setAnimationBeginsFromCurrentState:YES];
6186 [UIView setAnimationCurve:curve];
6187 [UIView setAnimationDuration:duration];
6188 [list_ setFrame:base];
6189 [UIView commitAnimations];
6192 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6193 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6196 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6197 [self resizeForKeyboardBounds:bounds duration:0];
6200 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6201 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6202 *curve = UIViewAnimationCurveEaseInOut;
6204 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6206 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6209 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6212 - (void) keyboardWillShow:(NSNotification *)notification {
6215 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6216 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6218 NSTimeInterval duration;
6219 UIViewAnimationCurve curve;
6220 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6222 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);
6223 UIViewController *base = self;
6224 while ([base parentOrPresentingViewController] != nil)
6225 base = [base parentOrPresentingViewController];
6226 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6227 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6229 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6230 intersection.size.height += CYStatusBarHeight();
6232 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6235 - (void) keyboardWillHide:(NSNotification *)notification {
6236 NSTimeInterval duration;
6237 UIViewAnimationCurve curve;
6238 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6240 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6243 - (void) viewWillAppear:(BOOL)animated {
6244 [super viewWillAppear:animated];
6246 [self resizeForKeyboardBounds:CGRectZero];
6247 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6248 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6251 - (void) viewWillDisappear:(BOOL)animated {
6252 [super viewWillDisappear:animated];
6254 [self resizeForKeyboardBounds:CGRectZero];
6255 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6256 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6259 - (void) viewDidAppear:(BOOL)animated {
6260 [super viewDidAppear:animated];
6261 [self deselectWithAnimation:animated];
6264 - (void) didSelectPackage:(Package *)package {
6265 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6266 [view setDelegate:delegate_];
6267 [[self navigationController] pushViewController:view animated:YES];
6270 #if TryIndexedCollation
6271 + (BOOL) hasIndexedCollation {
6272 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6276 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6277 NSInteger count([sections_ count]);
6278 return count == 0 ? 1 : count;
6281 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6282 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6284 return [[sections_ objectAtIndex:section] name];
6287 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6288 if ([sections_ count] == 0)
6290 return [[sections_ objectAtIndex:section] count];
6293 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6294 @synchronized (database_) {
6295 if ([database_ era] != era_)
6298 Section *section([sections_ objectAtIndex:[path section]]);
6299 NSInteger row([path row]);
6300 Package *package([packages_ objectAtIndex:([section row] + row)]);
6301 return [[package retain] autorelease];
6304 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6305 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6307 cell = [[[PackageCell alloc] init] autorelease];
6309 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6310 [cell setPackage:package asSummary:[self isSummarized]];
6314 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6315 Package *package([self packageAtIndexPath:path]);
6316 package = [database_ packageWithName:[package id]];
6317 [self didSelectPackage:package];
6320 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6321 if (![self showsSections])
6327 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6328 #if TryIndexedCollation
6329 if ([[self class] hasIndexedCollation]) {
6330 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6337 - (void) updateHeight {
6338 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6341 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6342 if ((self = [super init]) != nil) {
6343 database_ = database;
6344 title_ = [title copy];
6345 [[self navigationItem] setTitle:title_];
6350 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6351 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6352 [self setView:view];
6354 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6355 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6356 [view addSubview:list_];
6358 // XXX: is 20 the most optimal number here?
6359 [list_ setSectionIndexMinimumDisplayRowCount:20];
6361 [(UITableView *) list_ setDataSource:self];
6362 [list_ setDelegate:self];
6364 [self updateHeight];
6367 - (void) releaseSubviews {
6375 [super releaseSubviews];
6378 - (void) setDelegate:(id)delegate {
6379 delegate_ = delegate;
6382 - (bool) shouldYield {
6386 - (bool) shouldBlock {
6390 - (NSMutableArray *) _reloadPackages {
6391 @synchronized (database_) {
6392 era_ = [database_ era];
6393 NSArray *packages([database_ packages]);
6395 return [NSMutableArray arrayWithArray:packages];
6398 - (void) _reloadData {
6399 if (reloading_ != 0) {
6407 if ([self shouldYield]) {
6411 if (![self shouldBlock])
6414 hud = [delegate_ addProgressHUD];
6415 [hud setText:UCLocalize("LOADING")];
6419 packages = [self yieldToSelector:@selector(_reloadPackages)];
6422 [delegate_ removeProgressHUD:hud];
6423 } while (reloading_ == 2);
6425 packages = [self _reloadPackages];
6428 @synchronized (database_) {
6429 if (era_ != [database_ era])
6433 packages_ = packages;
6435 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6436 sections_ = [NSMutableArray arrayWithCapacity:16];
6438 Section *section = nil;
6440 #if TryIndexedCollation
6441 if ([[self class] hasIndexedCollation]) {
6442 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6444 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6445 NSArray *titles = [collation sectionIndexTitles];
6448 _profile(PackageTable$reloadData$Section)
6449 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6453 _profile(PackageTable$reloadData$Section$Package)
6454 package = [packages_ objectAtIndex:offset];
6455 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6458 while (secidx < index) {
6461 _profile(PackageTable$reloadData$Section$Allocate)
6462 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6465 _profile(PackageTable$reloadData$Section$Add)
6466 [sections_ addObject:section];
6470 [section addToCount];
6476 index_ = [NSMutableArray arrayWithCapacity:32];
6478 bool sectioned([self showsSections]);
6480 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6481 [sections_ addObject:section];
6484 _profile(PackageTable$reloadData$Section)
6485 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6489 _profile(PackageTable$reloadData$Section$Package)
6490 package = [packages_ objectAtIndex:offset];
6491 index = [package index];
6494 if (sectioned && (section == nil || [section index] != index)) {
6495 _profile(PackageTable$reloadData$Section$Allocate)
6496 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6499 [index_ addObject:[section name]];
6500 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6502 _profile(PackageTable$reloadData$Section$Add)
6503 [sections_ addObject:section];
6507 [section addToCount];
6512 [self updateHeight];
6514 _profile(PackageTable$reloadData$List)
6515 [(UITableView *) list_ setDataSource:self];
6520 - (void) reloadData {
6523 if ([self shouldYield])
6524 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6529 - (void) resetCursor {
6530 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6533 - (void) clearData {
6534 [self updateHeight];
6536 [list_ setDataSource:nil];
6544 /* Filtered Package List Controller {{{ */
6545 @interface FilteredPackageListController : PackageListController {
6548 _H<NSObject> object_;
6551 - (void) setObject:(id)object;
6552 - (void) setObject:(id)object forFilter:(SEL)filter;
6555 - (void) setFilter:(SEL)filter;
6557 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6561 @implementation FilteredPackageListController
6567 - (void) setFilter:(SEL)filter {
6568 @synchronized (self) {
6571 /* XXX: this is an unsafe optimization of doomy hell */
6572 Method method(class_getInstanceMethod([Package class], filter));
6573 _assert(method != NULL);
6574 imp_ = method_getImplementation(method);
6575 _assert(imp_ != NULL);
6578 - (void) setObject:(id)object {
6579 @synchronized (self) {
6583 - (void) setObject:(id)object forFilter:(SEL)filter {
6584 @synchronized (self) {
6585 [self setFilter:filter];
6586 [self setObject:object];
6589 - (NSMutableArray *) _reloadPackages {
6590 @synchronized (database_) {
6591 era_ = [database_ era];
6592 NSArray *packages([database_ packages]);
6594 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6598 _H<NSObject> object;
6600 @synchronized (self) {
6606 _profile(PackageTable$reloadData$Filter)
6607 for (Package *package in packages)
6608 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6609 [filtered addObject:package];
6615 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6616 if ((self = [super initWithDatabase:database title:title]) != nil) {
6617 [self setFilter:filter];
6618 [self setObject:object];
6625 /* Home Controller {{{ */
6626 @interface HomeController : CydiaWebViewController {
6627 CFRunLoopRef runloop_;
6628 SCNetworkReachabilityRef reachability_;
6633 @implementation HomeController
6635 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6636 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6640 if ((self = [super init]) != nil) {
6641 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6644 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6645 if (reachability_ != NULL) {
6646 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6647 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6649 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6650 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6657 if (reachability_ != NULL && runloop_ != NULL)
6658 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6662 - (NSURL *) navigationURL {
6663 return [NSURL URLWithString:@"cydia://home"];
6666 - (void) aboutButtonClicked {
6667 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6669 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6670 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6671 [alert setCancelButtonIndex:0];
6674 @"Copyright \u00a9 2008-2012\n"
6677 "Jay Freeman (saurik)\n"
6678 "saurik@saurik.com\n"
6679 "http://www.saurik.com/"
6685 - (UIBarButtonItem *) leftButton {
6686 return [[[UIBarButtonItem alloc]
6687 initWithTitle:UCLocalize("ABOUT")
6688 style:UIBarButtonItemStylePlain
6690 action:@selector(aboutButtonClicked)
6696 /* Manage Controller {{{ */
6697 @interface ManageController : CydiaWebViewController {
6700 - (void) queueStatusDidChange;
6704 @implementation ManageController
6707 if ((self = [super init]) != nil) {
6708 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6712 - (NSURL *) navigationURL {
6713 return [NSURL URLWithString:@"cydia://manage"];
6716 - (UIBarButtonItem *) leftButton {
6717 return [[[UIBarButtonItem alloc]
6718 initWithTitle:UCLocalize("SETTINGS")
6719 style:UIBarButtonItemStylePlain
6721 action:@selector(settingsButtonClicked)
6725 - (void) settingsButtonClicked {
6726 [delegate_ showSettings];
6729 - (void) queueButtonClicked {
6733 - (UIBarButtonItem *) rightButton {
6734 return Queuing_ ? [[[UIBarButtonItem alloc]
6735 initWithTitle:UCLocalize("QUEUE")
6736 style:UIBarButtonItemStyleDone
6738 action:@selector(queueButtonClicked)
6739 ] autorelease] : nil;
6742 - (void) queueStatusDidChange {
6743 [self applyRightButton];
6746 - (bool) isLoading {
6747 return !Queuing_ && [super isLoading];
6753 /* Refresh Bar {{{ */
6754 @interface RefreshBar : UINavigationBar {
6755 _H<UIProgressIndicator> indicator_;
6756 _H<UITextLabel> prompt_;
6757 _H<UIProgressBar> progress_;
6758 _H<UINavigationButton> cancel_;
6763 @implementation RefreshBar
6765 - (void) positionViews {
6766 CGRect frame = [cancel_ frame];
6767 frame.size = [cancel_ sizeThatFits:frame.size];
6768 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6769 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6770 [cancel_ setFrame:frame];
6772 CGSize prgsize = {75, 100};
6774 [self frame].size.width - prgsize.width - 10,
6775 ([self frame].size.height - prgsize.height) / 2
6777 [progress_ setFrame:prgrect];
6779 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6780 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6781 CGRect indrect = {{indoffset, indoffset}, indsize};
6782 [indicator_ setFrame:indrect];
6784 CGSize prmsize = {215, indsize.height + 4};
6786 indoffset * 2 + indsize.width,
6787 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6789 [prompt_ setFrame:prmrect];
6792 - (void) setFrame:(CGRect)frame {
6793 [super setFrame:frame];
6794 [self positionViews];
6797 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6798 if ((self = [super initWithFrame:frame]) != nil) {
6799 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6801 [self setBarStyle:UIBarStyleBlack];
6803 UIBarStyle barstyle([self _barStyle:NO]);
6804 bool ugly(barstyle == UIBarStyleDefault);
6806 UIProgressIndicatorStyle style = ugly ?
6807 UIProgressIndicatorStyleMediumBrown :
6808 UIProgressIndicatorStyleMediumWhite;
6810 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6811 [(UIProgressIndicator *) indicator_ setStyle:style];
6812 [indicator_ startAnimation];
6813 [self addSubview:indicator_];
6815 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6816 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6817 [prompt_ setBackgroundColor:[UIColor clearColor]];
6818 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6819 [self addSubview:prompt_];
6821 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6822 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6823 [(UIProgressBar *) progress_ setStyle:0];
6824 [self addSubview:progress_];
6826 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6827 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6828 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6829 [cancel_ setBarStyle:barstyle];
6831 [self positionViews];
6835 - (void) setCancellable:(bool)cancellable {
6837 [self addSubview:cancel_];
6839 [cancel_ removeFromSuperview];
6843 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6844 [progress_ setProgress:0];
6848 [self setCancellable:NO];
6851 - (void) setPrompt:(NSString *)prompt {
6852 [prompt_ setText:prompt];
6855 - (void) setProgress:(float)progress {
6856 [progress_ setProgress:progress];
6862 /* Cydia Navigation Controller Interface {{{ */
6863 @interface UINavigationController (Cydia)
6865 - (NSArray *) navigationURLCollection;
6866 - (void) unloadData;
6871 /* Cydia Tab Bar Controller {{{ */
6872 @interface CYTabBarController : UITabBarController <
6873 UITabBarControllerDelegate,
6876 _transient Database *database_;
6877 _H<RefreshBar, 1> refreshbar_;
6881 // XXX: ok, "updatedelegate_"?...
6882 _transient NSObject<CydiaDelegate> *updatedelegate_;
6884 _H<UIViewController> remembered_;
6885 _transient UIViewController *transient_;
6888 - (NSArray *) navigationURLCollection;
6889 - (void) dropBar:(BOOL)animated;
6890 - (void) beginUpdate;
6891 - (void) raiseBar:(BOOL)animated;
6893 - (void) unloadData;
6897 @implementation CYTabBarController
6899 - (void) didReceiveMemoryWarning {
6900 [super didReceiveMemoryWarning];
6902 // presenting a UINavigationController on 2.x does not update its transitionView
6903 // it thereby will not allow its topViewController to be unloaded by memory pressure
6904 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6905 UIViewController *selected([self selectedViewController]);
6906 for (UINavigationController *controller in [self viewControllers])
6907 if (controller != selected)
6908 if (UIViewController *top = [controller topViewController])
6913 - (void) setUnselectedViewController:(UIViewController *)transient {
6914 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6915 if (transient != nil) {
6916 [[[self viewControllers] objectAtIndex:0] pushViewController:transient animated:YES];
6917 [self setSelectedIndex:0];
6921 NSMutableArray *controllers = [[[self viewControllers] mutableCopy] autorelease];
6922 if (transient != nil) {
6923 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
6924 [navigation setViewControllers:[NSArray arrayWithObject:transient]];
6925 transient = navigation;
6927 if (transient_ == nil)
6928 remembered_ = [controllers objectAtIndex:0];
6929 transient_ = transient;
6930 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6931 [controllers replaceObjectAtIndex:0 withObject:transient_];
6932 [self setSelectedIndex:0];
6933 [self setViewControllers:controllers];
6934 [self concealTabBarSelection];
6935 } else if (remembered_ != nil) {
6936 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6937 transient_ = transient;
6938 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6940 [self setViewControllers:controllers];
6941 [self revealTabBarSelection];
6945 - (UIViewController *) unselectedViewController {
6949 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6950 if ([self unselectedViewController])
6951 [self setUnselectedViewController:nil];
6953 // presenting a UINavigationController on 2.x does not update its transitionView
6954 // if this view was unloaded, the tranitionView may currently be presenting nothing
6955 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6956 UINavigationController *navigation((UINavigationController *) viewController);
6957 [navigation pushViewController:[[[UIViewController alloc] init] autorelease] animated:NO];
6958 [navigation popViewControllerAnimated:NO];
6962 - (NSArray *) navigationURLCollection {
6963 NSMutableArray *items([NSMutableArray array]);
6965 // XXX: Should this deal with transient view controllers?
6966 for (id navigation in [self viewControllers]) {
6967 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6969 [items addObject:stack];
6975 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6976 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6977 [self setUnselectedViewController:nil];
6979 [super dismissModalViewControllerAnimated:YES];
6982 - (void) unloadData {
6985 for (UINavigationController *controller in [self viewControllers])
6986 [controller unloadData];
6988 if (UIViewController *selected = [self selectedViewController])
6989 [selected reloadData];
6991 if (UIViewController *unselected = [self unselectedViewController]) {
6992 [unselected unloadData];
6993 [unselected reloadData];
6998 [[NSNotificationCenter defaultCenter] removeObserver:self];
7003 - (id) initWithDatabase:(Database *)database {
7004 if ((self = [super init]) != nil) {
7005 database_ = database;
7006 [self setDelegate:self];
7008 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7009 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7011 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
7015 - (void) setUpdate:(NSDate *)date {
7019 - (void) beginUpdate {
7020 [(RefreshBar *) refreshbar_ start];
7023 [updatedelegate_ retainNetworkActivityIndicator];
7027 detachNewThreadSelector:@selector(performUpdate)
7033 - (void) performUpdate {
7034 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7037 status.setDelegate(self);
7038 [database_ updateWithStatus:status];
7041 performSelectorOnMainThread:@selector(completeUpdate)
7049 - (void) stopUpdateWithSelector:(SEL)selector {
7051 [updatedelegate_ releaseNetworkActivityIndicator];
7053 [self raiseBar:YES];
7056 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7059 - (void) completeUpdate {
7062 [self stopUpdateWithSelector:@selector(reloadData)];
7065 - (void) cancelUpdate {
7066 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7069 - (void) cancelPressed {
7070 [self cancelUpdate];
7077 - (void) addProgressEvent:(CydiaProgressEvent *)event {
7078 [refreshbar_ setPrompt:[event compoundMessage]];
7081 - (bool) isProgressCancelled {
7085 - (void) setProgressCancellable:(NSNumber *)cancellable {
7086 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
7089 - (void) setProgressPercent:(NSNumber *)percent {
7090 [refreshbar_ setProgress:[percent floatValue]];
7093 - (void) setProgressStatus:(NSDictionary *)status {
7095 [self setProgressPercent:[status objectForKey:@"Percent"]];
7098 - (void) setUpdateDelegate:(id)delegate {
7099 updatedelegate_ = delegate;
7102 - (UIView *) transitionView {
7103 if ([self respondsToSelector:@selector(_transitionView)])
7104 return [self _transitionView];
7106 return MSHookIvar<id>(self, "_viewControllerTransitionView");
7109 - (void) dropBar:(BOOL)animated {
7114 UIView *transition([self transitionView]);
7115 [[self view] addSubview:refreshbar_];
7117 CGRect barframe([refreshbar_ frame]);
7119 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
7120 barframe.origin.y = CYStatusBarHeight();
7122 barframe.origin.y = 0;
7124 [refreshbar_ setFrame:barframe];
7127 [UIView beginAnimations:nil context:NULL];
7129 CGRect viewframe = [transition frame];
7130 viewframe.origin.y += barframe.size.height;
7131 viewframe.size.height -= barframe.size.height;
7132 [transition setFrame:viewframe];
7135 [UIView commitAnimations];
7137 // Ensure bar has the proper width for our view, it might have changed
7138 barframe.size.width = viewframe.size.width;
7139 [refreshbar_ setFrame:barframe];
7142 - (void) raiseBar:(BOOL)animated {
7147 UIView *transition([self transitionView]);
7148 [refreshbar_ removeFromSuperview];
7150 CGRect barframe([refreshbar_ frame]);
7153 [UIView beginAnimations:nil context:NULL];
7155 CGRect viewframe = [transition frame];
7156 viewframe.origin.y -= barframe.size.height;
7157 viewframe.size.height += barframe.size.height;
7158 [transition setFrame:viewframe];
7161 [UIView commitAnimations];
7164 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7165 bool dropped(dropped_);
7170 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7176 - (void) statusBarFrameChanged:(NSNotification *)notification {
7186 /* Cydia Navigation Controller Implementation {{{ */
7187 @implementation UINavigationController (Cydia)
7189 - (NSArray *) navigationURLCollection {
7190 NSMutableArray *stack([NSMutableArray array]);
7192 for (CyteViewController *controller in [self viewControllers]) {
7193 NSString *url = [[controller navigationURL] absoluteString];
7195 [stack addObject:url];
7201 - (void) reloadData {
7204 UIViewController *visible([self visibleViewController]);
7206 [visible reloadData];
7208 // on the iPad, this view controller is ALSO visible. :(
7210 if (UIViewController *top = [self topViewController])
7215 - (void) unloadData {
7216 for (CyteViewController *page in [self viewControllers])
7225 /* Cydia:// Protocol {{{ */
7226 @interface CydiaURLProtocol : NSURLProtocol {
7231 @implementation CydiaURLProtocol
7233 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7234 NSURL *url([request URL]);
7238 NSString *scheme([[url scheme] lowercaseString]);
7239 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7241 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7247 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7251 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7252 id<NSURLProtocolClient> client([self client]);
7254 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7256 NSData *data(UIImagePNGRepresentation(icon));
7258 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7259 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7260 [client URLProtocol:self didLoadData:data];
7261 [client URLProtocolDidFinishLoading:self];
7265 - (void) startLoading {
7266 id<NSURLProtocolClient> client([self client]);
7267 NSURLRequest *request([self request]);
7269 NSURL *url([request URL]);
7270 NSString *href([url absoluteString]);
7271 NSString *scheme([[url scheme] lowercaseString]);
7275 if ([scheme isEqualToString:@"cydia"])
7276 path = [href substringFromIndex:8];
7277 else if ([scheme isEqualToString:@"about"])
7278 path = [href substringFromIndex:12];
7279 else _assert(false);
7281 NSRange slash([path rangeOfString:@"/"]);
7284 if (slash.location == NSNotFound) {
7288 command = [path substringToIndex:slash.location];
7289 path = [path substringFromIndex:(slash.location + 1)];
7292 Database *database([Database sharedInstance]);
7294 if ([command isEqualToString:@"package-icon"]) {
7297 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7298 Package *package([database packageWithName:path]);
7302 UIImage *icon([package icon]);
7303 [self _returnPNGWithImage:icon forRequest:request];
7304 } else if ([command isEqualToString:@"uikit-image"]) {
7307 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7308 UIImage *icon(_UIImageWithName(path));
7309 [self _returnPNGWithImage:icon forRequest:request];
7310 } else if ([command isEqualToString:@"section-icon"]) {
7313 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7314 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7316 icon = [UIImage applicationImageNamed:@"unknown.png"];
7317 [self _returnPNGWithImage:icon forRequest:request];
7319 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7323 - (void) stopLoading {
7329 /* Section Controller {{{ */
7330 @interface SectionController : FilteredPackageListController {
7331 _H<IndirectDelegate, 1> indirect_;
7332 _H<CydiaObject> cydia_;
7333 _H<NSString> section_;
7334 std::vector< _H<CyteWebViewTableViewCell, 1> > promoted_;
7337 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7341 @implementation SectionController
7343 - (NSURL *) referrerURL {
7344 NSString *name = section_;
7348 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@", UI_, [name stringByAddingPercentEscapesIncludingReserved]]];
7351 - (NSURL *) navigationURL {
7352 NSString *name = section_;
7356 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", [name stringByAddingPercentEscapesIncludingReserved]]];
7359 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7362 title = UCLocalize("ALL_PACKAGES");
7363 else if (![name isEqual:@""])
7364 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7366 title = UCLocalize("NO_SECTION");
7368 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7369 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7370 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7375 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7376 return [super numberOfSectionsInTableView:list] + 1;
7379 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7380 return section == 0 ? nil : [super tableView:list titleForHeaderInSection:(section - 1)];
7383 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7384 return section == 0 ? promoted_.size() : [super tableView:list numberOfRowsInSection:(section - 1)];
7387 + (NSIndexPath *) adjustedIndexPath:(NSIndexPath *)path {
7388 return [NSIndexPath indexPathForRow:[path row] inSection:([path section] - 1)];
7391 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7392 if ([path section] != 0)
7393 return [super tableView:table cellForRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7395 return promoted_[[path row]];
7398 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
7399 if ([path section] != 0)
7400 return [super tableView:table didSelectRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7403 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
7404 NSInteger section([super tableView:tableView sectionForSectionIndexTitle:title atIndex:index]);
7405 return section == 0 ? 0 : section + 1;
7408 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7409 NSURL *url([request URL]);
7413 if ([frame isEqualToString:@"_open"])
7414 [delegate_ openURL:url];
7416 WebFrame *frame(nil);
7417 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7418 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7420 frame = [view mainFrame];
7422 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7424 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7425 [controller setDelegate:delegate_];
7426 [[self navigationController] pushViewController:controller animated:YES];
7432 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7433 return [CydiaWebViewController requestWithHeaders:request];
7436 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7437 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7443 // XXX: this code is horrible. I mean, wtf Jay?
7444 if (ShowPromoted_ && [[Metadata_ objectForKey:@"ShowPromoted"] boolValue]) {
7445 promoted_.resize(1);
7447 for (unsigned i(0); i != promoted_.size(); ++i) {
7448 CyteWebViewTableViewCell *promoted([CyteWebViewTableViewCell cellWithRequest:[NSURLRequest
7449 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sectionhead/%u/%@",
7450 UI_, i, section_ == nil ? @"" : [section_ stringByAddingPercentEscapesIncludingReserved]]
7453 cachePolicy:NSURLRequestUseProtocolCachePolicy
7457 [promoted setDelegate:self];
7458 promoted_[i] = promoted;
7463 - (void) setDelegate:(id)delegate {
7464 [super setDelegate:delegate];
7465 [cydia_ setDelegate:delegate];
7468 - (void) releaseSubviews {
7470 [super releaseSubviews];
7475 /* Sections Controller {{{ */
7476 @interface SectionsController : CyteViewController <
7477 UITableViewDataSource,
7480 _transient Database *database_;
7481 _H<NSMutableArray> sections_;
7482 _H<NSMutableArray> filtered_;
7483 _H<UITableView, 2> list_;
7486 - (id) initWithDatabase:(Database *)database;
7487 - (void) editButtonClicked;
7491 @implementation SectionsController
7493 - (NSURL *) navigationURL {
7494 return [NSURL URLWithString:@"cydia://sections"];
7497 - (void) updateNavigationItem {
7498 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7499 if ([sections_ count] == 0) {
7500 [[self navigationItem] setRightBarButtonItem:nil];
7502 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7503 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7505 action:@selector(editButtonClicked)
7506 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7510 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7511 [super setEditing:editing animated:animated];
7516 [delegate_ updateData];
7518 [self updateNavigationItem];
7521 - (void) viewDidAppear:(BOOL)animated {
7522 [super viewDidAppear:animated];
7523 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7526 - (void) viewWillDisappear:(BOOL)animated {
7527 [super viewWillDisappear:animated];
7528 [self setEditing:NO];
7531 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7532 Section *section = nil;
7533 int index = [indexPath row];
7534 if (![self isEditing]) {
7537 section = [filtered_ objectAtIndex:index];
7539 section = [sections_ objectAtIndex:index];
7544 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7545 if ([self isEditing])
7546 return [sections_ count];
7548 return [filtered_ count] + 1;
7551 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7555 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7556 static NSString *reuseIdentifier = @"SectionCell";
7558 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7560 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7562 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7567 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7568 if ([self isEditing])
7571 Section *section = [self sectionAtIndexPath:indexPath];
7573 SectionController *controller = [[[SectionController alloc]
7574 initWithDatabase:database_
7575 section:[section name]
7577 [controller setDelegate:delegate_];
7579 [[self navigationController] pushViewController:controller animated:YES];
7583 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7584 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7585 [list_ setRowHeight:45.0f];
7586 [(UITableView *) list_ setDataSource:self];
7587 [list_ setDelegate:self];
7588 [self setView:list_];
7591 - (void) viewDidLoad {
7592 [super viewDidLoad];
7594 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7597 - (void) releaseSubviews {
7603 [super releaseSubviews];
7606 - (id) initWithDatabase:(Database *)database {
7607 if ((self = [super init]) != nil) {
7608 database_ = database;
7612 - (void) reloadData {
7615 NSArray *packages = [database_ packages];
7617 sections_ = [NSMutableArray arrayWithCapacity:16];
7618 filtered_ = [NSMutableArray arrayWithCapacity:16];
7620 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7623 for (Package *package in packages) {
7624 NSString *name([package section]);
7625 NSString *key(name == nil ? @"" : name);
7629 _profile(SectionsView$reloadData$Section)
7630 section = [sections objectForKey:key];
7631 if (section == nil) {
7632 _profile(SectionsView$reloadData$Section$Allocate)
7633 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7634 [sections setObject:section forKey:key];
7639 [section addToCount];
7641 _profile(SectionsView$reloadData$Filter)
7642 if (![package valid] || ![package visible])
7650 [sections_ addObjectsFromArray:[sections allValues]];
7652 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7654 for (Section *section in (id) sections_) {
7655 size_t count([section row]);
7659 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7660 [section setCount:count];
7661 [filtered_ addObject:section];
7664 [self updateNavigationItem];
7669 - (void) editButtonClicked {
7670 [self setEditing:![self isEditing] animated:YES];
7676 /* Changes Controller {{{ */
7677 @interface ChangesController : CyteViewController <
7678 CyteWebViewDelegate,
7679 UITableViewDataSource,
7682 _transient Database *database_;
7684 _H<NSMutableArray> packages_;
7685 _H<NSMutableArray> sections_;
7686 _H<UITableView, 2> list_;
7687 _H<CyteWebView, 1> dickbar_;
7689 _H<IndirectDelegate, 1> indirect_;
7690 _H<CydiaObject> cydia_;
7693 - (id) initWithDatabase:(Database *)database;
7697 @implementation ChangesController
7699 - (NSURL *) navigationURL {
7700 return [NSURL URLWithString:@"cydia://changes"];
7703 - (void) viewDidAppear:(BOOL)animated {
7704 [super viewDidAppear:animated];
7705 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7708 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7709 NSInteger count([sections_ count]);
7710 return count == 0 ? 1 : count;
7713 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7714 if ([sections_ count] == 0)
7716 return [[sections_ objectAtIndex:section] name];
7719 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7720 if ([sections_ count] == 0)
7722 return [[sections_ objectAtIndex:section] count];
7725 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7726 @synchronized (database_) {
7727 if ([database_ era] != era_)
7730 NSUInteger sectionIndex([path section]);
7731 if (sectionIndex >= [sections_ count])
7733 Section *section([sections_ objectAtIndex:sectionIndex]);
7734 NSInteger row([path row]);
7735 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7738 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7739 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7741 cell = [[[PackageCell alloc] init] autorelease];
7743 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7744 [cell setPackage:package asSummary:false];
7748 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7749 Package *package([self packageAtIndexPath:path]);
7750 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[NSString stringWithFormat:@"%@/#!/changes/", UI_]] autorelease]);
7751 [view setDelegate:delegate_];
7752 [[self navigationController] pushViewController:view animated:YES];
7756 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7757 NSString *context([alert context]);
7759 if ([context isEqualToString:@"norefresh"])
7760 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7763 - (void) refreshButtonClicked {
7764 if (IsReachable("cydia.saurik.com")) {
7765 [delegate_ beginUpdate];
7766 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7768 UIAlertView *alert = [[[UIAlertView alloc]
7769 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
7770 message:@"Host Unreachable" // XXX: Localize
7772 cancelButtonTitle:UCLocalize("OK")
7773 otherButtonTitles:nil
7776 [alert setContext:@"norefresh"];
7781 - (void) upgradeButtonClicked {
7782 [delegate_ distUpgrade];
7783 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7787 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7788 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7789 [self setView:view];
7791 list_ = [[[UITableView alloc] initWithFrame:[view bounds] style:UITableViewStylePlain] autorelease];
7792 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7793 [list_ setRowHeight:73];
7794 [(UITableView *) list_ setDataSource:self];
7795 [list_ setDelegate:self];
7796 [view addSubview:list_];
7798 if (AprilFools_ && kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
7799 CGRect dickframe([view bounds]);
7800 dickframe.size.height = 44;
7802 dickbar_ = [[[CyteWebView alloc] initWithFrame:dickframe] autorelease];
7803 [dickbar_ setDelegate:self];
7804 [view addSubview:dickbar_];
7806 [dickbar_ setBackgroundColor:[UIColor clearColor]];
7807 [dickbar_ setScalesPageToFit:YES];
7809 UIWebDocumentView *document([dickbar_ _documentView]);
7810 [document setBackgroundColor:[UIColor clearColor]];
7811 [document setDrawsBackground:NO];
7813 WebView *webview([document webView]);
7814 [webview setShouldUpdateWhileOffscreen:NO];
7816 UIScrollView *scroller([dickbar_ scrollView]);
7817 [scroller setScrollingEnabled:NO];
7818 [scroller setFixedBackgroundPattern:YES];
7819 [scroller setBackgroundColor:[UIColor clearColor]];
7821 WebPreferences *preferences([webview preferences]);
7822 [preferences setCacheModel:WebCacheModelDocumentBrowser];
7823 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
7824 [preferences setOfflineWebApplicationCacheEnabled:YES];
7826 [dickbar_ loadRequest:[NSURLRequest
7827 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/dickbar/", UI_]]]
7828 cachePolicy:NSURLRequestUseProtocolCachePolicy
7832 UIEdgeInsets inset = {44, 0, 0, 0};
7833 [list_ setContentInset:inset];
7835 [dickbar_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7839 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7840 NSURL *url([request URL]);
7844 if ([frame isEqualToString:@"_open"])
7845 [delegate_ openURL:url];
7847 WebFrame *frame(nil);
7848 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7849 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7851 frame = [view mainFrame];
7853 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7855 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7856 [controller setDelegate:delegate_];
7857 [[self navigationController] pushViewController:controller animated:YES];
7863 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7864 return [CydiaWebViewController requestWithHeaders:request];
7867 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7868 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7871 - (void) setDelegate:(id)delegate {
7872 [super setDelegate:delegate];
7873 [cydia_ setDelegate:delegate];
7876 - (void) viewDidLoad {
7877 [super viewDidLoad];
7879 [[self navigationItem] setTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES"))];
7882 - (void) releaseSubviews {
7889 [super releaseSubviews];
7892 - (id) initWithDatabase:(Database *)database {
7893 if ((self = [super init]) != nil) {
7894 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7895 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7896 database_ = database;
7900 - (NSMutableArray *) _reloadPackages {
7901 @synchronized (database_) {
7902 era_ = [database_ era];
7903 NSArray *packages([database_ packages]);
7905 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7908 _profile(ChangesController$_reloadPackages$Filter)
7909 for (Package *package in packages)
7910 if ([package upgradableAndEssential:YES] || [package visible])
7911 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7914 _profile(ChangesController$_reloadPackages$radixSort)
7915 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7922 - (void) _reloadData {
7923 NSMutableArray *packages;
7927 UIProgressHUD *hud([delegate_ addProgressHUD]);
7928 [hud setText:UCLocalize("LOADING")];
7929 //NSLog(@"HUD:%@::%@", delegate_, hud);
7930 packages = [self yieldToSelector:@selector(_reloadPackages)];
7931 [delegate_ removeProgressHUD:hud];
7933 packages = [self _reloadPackages];
7936 @synchronized (database_) {
7937 if (era_ != [database_ era])
7940 packages_ = packages;
7941 sections_ = [NSMutableArray arrayWithCapacity:16];
7943 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7944 Section *ignored = nil;
7945 Section *section = nil;
7949 bool unseens = false;
7951 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7953 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7954 Package *package = [packages_ objectAtIndex:offset];
7956 BOOL uae = [package upgradableAndEssential:YES];
7960 time_t seen([package seen]);
7962 if (section == nil || last != seen) {
7966 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7969 _profile(ChangesController$reloadData$Allocate)
7970 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7971 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7972 [sections_ addObject:section];
7976 [section addToCount];
7977 } else if ([package ignored]) {
7978 if (ignored == nil) {
7979 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7981 [ignored addToCount];
7984 [upgradable addToCount];
7989 CFRelease(formatter);
7992 Section *last = [sections_ lastObject];
7993 size_t count = [last count];
7994 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7995 [sections_ removeLastObject];
7998 if ([ignored count] != 0)
7999 [sections_ insertObject:ignored atIndex:0];
8001 [sections_ insertObject:upgradable atIndex:0];
8005 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
8006 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
8007 style:UIBarButtonItemStylePlain
8009 action:@selector(upgradeButtonClicked)
8010 ] autorelease]) animated:YES];
8012 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
8013 initWithTitle:UCLocalize("REFRESH")
8014 style:UIBarButtonItemStylePlain
8016 action:@selector(refreshButtonClicked)
8017 ] autorelease]) animated:YES];
8022 - (void) reloadData {
8024 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
8029 /* Search Controller {{{ */
8030 @interface SearchController : FilteredPackageListController <
8033 _H<UISearchBar, 1> search_;
8037 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
8038 - (void) reloadData;
8042 @implementation SearchController
8044 - (NSURL *) referrerURL {
8045 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
8048 - (NSURL *) navigationURL {
8049 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
8050 return [NSURL URLWithString:@"cydia://search"];
8052 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
8055 - (NSArray *) termsForQuery:(NSString *)query {
8056 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
8057 for (NSString *component in [query componentsSeparatedByString:@" "])
8058 if ([component length] != 0)
8059 [terms addObject:component];
8064 - (void) useSearch {
8065 [self setObject:[self termsForQuery:[search_ text]] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
8070 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
8071 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8076 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
8077 [search_ resignFirstResponder];
8081 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
8082 [search_ setText:@""];
8083 [self searchBarButtonClicked:searchBar];
8086 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
8087 [self searchBarButtonClicked:searchBar];
8090 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
8091 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8095 - (bool) shouldYield {
8099 - (bool) shouldBlock {
8100 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
8103 - (bool) isSummarized {
8104 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
8107 - (bool) showsSections {
8111 - (NSMutableArray *) _reloadPackages {
8112 NSMutableArray *packages([super _reloadPackages]);
8113 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8114 [packages radixSortUsingSelector:@selector(rank)];
8118 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
8119 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[self termsForQuery:query]])) {
8120 search_ = [[[UISearchBar alloc] init] autorelease];
8121 [search_ setDelegate:self];
8124 [search_ setText:query];
8128 - (void) viewDidAppear:(BOOL)animated {
8129 [super viewDidAppear:animated];
8131 if (!searchloaded_) {
8132 searchloaded_ = YES;
8133 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
8134 [search_ layoutSubviews];
8135 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
8137 UITextField *textField;
8138 if ([search_ respondsToSelector:@selector(searchField)])
8139 textField = [search_ searchField];
8141 textField = MSHookIvar<UITextField *>(search_, "_searchField");
8143 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8144 [textField setEnablesReturnKeyAutomatically:NO];
8145 [[self navigationItem] setTitleView:textField];
8148 if ([self isSummarized])
8149 [search_ becomeFirstResponder];
8152 - (void) reloadData {
8153 id object([search_ text]);
8154 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8155 object = [self termsForQuery:object];
8157 [self setObject:object];
8163 - (void) didSelectPackage:(Package *)package {
8164 [search_ resignFirstResponder];
8165 [super didSelectPackage:package];
8170 /* Package Settings Controller {{{ */
8171 @interface PackageSettingsController : CyteViewController <
8172 UITableViewDataSource,
8175 _transient Database *database_;
8177 _H<Package> package_;
8178 _H<UITableView, 2> table_;
8179 _H<UISwitch> subscribedSwitch_;
8180 _H<UISwitch> ignoredSwitch_;
8181 _H<UITableViewCell> subscribedCell_;
8182 _H<UITableViewCell> ignoredCell_;
8185 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
8189 @implementation PackageSettingsController
8191 - (NSURL *) navigationURL {
8192 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
8195 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8196 if (package_ == nil)
8199 if ([package_ installed] == nil)
8205 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8206 if (package_ == nil)
8209 // both sections contain just one item right now.
8213 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8217 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8219 return UCLocalize("SHOW_ALL_CHANGES_EX");
8221 return UCLocalize("IGNORE_UPGRADES_EX");
8224 - (void) onSubscribed:(id)control {
8225 bool value([control isOn]);
8226 if (package_ == nil)
8228 if ([package_ setSubscribed:value])
8229 [delegate_ updateData];
8232 - (void) _updateIgnored {
8233 const char *package([name_ UTF8String]);
8234 bool on([ignoredSwitch_ isOn]);
8236 pid_t pid(ExecFork());
8238 FILE *dpkg(popen("dpkg --set-selections", "w"));
8239 fwrite(package, strlen(package), 1, dpkg);
8242 fwrite(" hold\n", 6, 1, dpkg);
8244 fwrite(" install\n", 9, 1, dpkg);
8255 - (void) onIgnored:(id)control {
8256 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8257 [invocation setTarget:self];
8258 [invocation setSelector:@selector(_updateIgnored)];
8260 [delegate_ reloadDataWithInvocation:invocation];
8263 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8264 if (package_ == nil)
8267 switch ([indexPath section]) {
8268 case 0: return subscribedCell_;
8269 case 1: return ignoredCell_;
8278 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8279 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8280 [self setView:view];
8282 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8283 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8284 [(UITableView *) table_ setDataSource:self];
8285 [table_ setDelegate:self];
8286 [view addSubview:table_];
8288 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8289 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8290 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8292 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8293 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8294 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8296 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8297 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8298 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8299 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8301 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8302 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8303 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8304 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8307 - (void) viewDidLoad {
8308 [super viewDidLoad];
8310 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8313 - (void) releaseSubviews {
8315 subscribedCell_ = nil;
8317 ignoredSwitch_ = nil;
8318 subscribedSwitch_ = nil;
8320 [super releaseSubviews];
8323 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8324 if ((self = [super init]) != nil) {
8325 database_ = database;
8330 - (void) reloadData {
8333 package_ = [database_ packageWithName:name_];
8335 if (package_ != nil) {
8336 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8337 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8338 } // XXX: what now, G?
8340 [table_ reloadData];
8346 /* Installed Controller {{{ */
8347 @interface InstalledController : FilteredPackageListController {
8351 - (id) initWithDatabase:(Database *)database;
8353 - (void) updateRoleButton;
8354 - (void) queueStatusDidChange;
8358 @implementation InstalledController
8360 - (NSURL *) referrerURL {
8361 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8364 - (NSURL *) navigationURL {
8365 return [NSURL URLWithString:@"cydia://installed"];
8368 - (id) initWithDatabase:(Database *)database {
8369 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8370 [self updateRoleButton];
8371 [self queueStatusDidChange];
8376 - (void) queueButtonClicked {
8381 - (void) queueStatusDidChange {
8385 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8386 initWithTitle:UCLocalize("QUEUE")
8387 style:UIBarButtonItemStyleDone
8389 action:@selector(queueButtonClicked)
8392 [[self navigationItem] setLeftBarButtonItem:nil];
8398 - (void) updateRoleButton {
8399 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8400 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8401 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8402 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8404 action:@selector(roleButtonClicked)
8408 - (void) roleButtonClicked {
8409 [self setObject:[NSNumber numberWithBool:expert_]];
8413 [self updateRoleButton];
8419 /* Source Cell {{{ */
8420 @interface SourceCell : CyteTableViewCell <
8421 CyteTableViewCellDelegate
8425 _H<NSString> origin_;
8426 _H<NSString> label_;
8429 - (void) setSource:(Source *)source;
8433 @implementation SourceCell
8435 - (void) _setImage:(NSArray *)data {
8436 if ([url_ isEqual:[data objectAtIndex:0]]) {
8437 icon_ = [data objectAtIndex:1];
8438 [content_ setNeedsDisplay];
8442 - (void) _setSource:(NSURL *) url {
8443 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8445 if (NSData *data = [NSURLConnection
8446 sendSynchronousRequest:[NSURLRequest
8448 cachePolicy:NSURLRequestUseProtocolCachePolicy
8452 returningResponse:NULL
8455 if (UIImage *image = [UIImage imageWithData:data])
8456 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8461 - (void) setSource:(Source *)source {
8462 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8464 origin_ = [source name];
8465 label_ = [source rooturi];
8467 [content_ setNeedsDisplay];
8469 url_ = [source iconURL];
8470 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8473 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8474 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8475 UIView *content([self contentView]);
8476 CGRect bounds([content bounds]);
8478 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8479 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8480 [content_ setBackgroundColor:[UIColor whiteColor]];
8481 [content addSubview:content_];
8483 [content_ setDelegate:self];
8484 [content_ setOpaque:YES];
8486 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8490 - (NSString *) accessibilityLabel {
8494 - (void) drawContentRect:(CGRect)rect {
8495 bool highlighted(highlighted_);
8496 float width(rect.size.width);
8500 rect.size = [(UIImage *) icon_ size];
8502 while (rect.size.width > 32 || rect.size.height > 32) {
8503 rect.size.width /= 2;
8504 rect.size.height /= 2;
8507 rect.origin.x = 25 - rect.size.width / 2;
8508 rect.origin.y = 25 - rect.size.height / 2;
8510 [icon_ drawInRect:rect];
8518 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 65) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8522 [label_ drawAtPoint:CGPointMake(48, 29) forWidth:(width - 65) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8527 /* Source Controller {{{ */
8528 @interface SourceController : FilteredPackageListController {
8529 _transient Source *source_;
8533 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8537 @implementation SourceController
8539 - (NSURL *) referrerURL {
8540 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sources/%@", UI_, [key_ stringByAddingPercentEscapesIncludingReserved]]];
8543 - (NSURL *) navigationURL {
8544 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8547 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8548 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8550 key_ = [source key];
8554 - (void) reloadData {
8555 source_ = [database_ sourceWithKey:key_];
8556 key_ = [source_ key];
8557 [self setObject:source_];
8559 [[self navigationItem] setTitle:[source_ label]];
8566 /* Sources Controller {{{ */
8567 @interface SourcesController : CyteViewController <
8568 UITableViewDataSource,
8571 _transient Database *database_;
8574 _H<UITableView, 2> list_;
8575 _H<NSMutableArray> sources_;
8579 _H<UIProgressHUD> hud_;
8582 //NSURLConnection *installer_;
8583 NSURLConnection *trivial_bz2_;
8584 NSURLConnection *trivial_gz_;
8585 //NSURLConnection *automatic_;
8590 - (id) initWithDatabase:(Database *)database;
8591 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8595 @implementation SourcesController
8597 - (void) _releaseConnection:(NSURLConnection *)connection {
8598 if (connection != nil) {
8599 [connection cancel];
8600 //[connection setDelegate:nil];
8601 [connection release];
8606 //[self _releaseConnection:installer_];
8607 [self _releaseConnection:trivial_gz_];
8608 [self _releaseConnection:trivial_bz2_];
8609 //[self _releaseConnection:automatic_];
8614 - (NSURL *) navigationURL {
8615 return [NSURL URLWithString:@"cydia://sources"];
8618 - (void) viewDidAppear:(BOOL)animated {
8619 [super viewDidAppear:animated];
8620 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8623 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8627 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8631 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8632 return [sources_ count];
8635 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8636 @synchronized (database_) {
8637 if ([database_ era] != era_)
8640 NSUInteger index([indexPath row]);
8641 return index < [sources_ count] ? [sources_ objectAtIndex:index] : nil;
8644 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8645 static NSString *cellIdentifier = @"SourceCell";
8647 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8648 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8649 [cell setSource:[self sourceAtIndexPath:indexPath]];
8650 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8655 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8656 Source *source = [self sourceAtIndexPath:indexPath];
8657 if (source == nil) return;
8659 SourceController *controller = [[[SourceController alloc]
8660 initWithDatabase:database_
8664 [controller setDelegate:delegate_];
8666 [[self navigationController] pushViewController:controller animated:YES];
8669 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8670 Source *source = [self sourceAtIndexPath:indexPath];
8671 return [source record] != nil;
8674 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8675 if (editingStyle == UITableViewCellEditingStyleDelete) {
8676 Source *source = [self sourceAtIndexPath:indexPath];
8677 if (source == nil) return;
8679 [Sources_ removeObjectForKey:[source key]];
8680 [delegate_ _saveConfig];
8681 [delegate_ reloadDataWithInvocation:nil];
8686 [delegate_ addTrivialSource:href_];
8689 [delegate_ syncData];
8692 - (NSString *) getWarning {
8693 NSString *href(href_);
8694 NSRange colon([href rangeOfString:@"://"]);
8695 if (colon.location != NSNotFound)
8696 href = [href substringFromIndex:(colon.location + 3)];
8697 href = [href stringByAddingPercentEscapes];
8698 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8700 NSURL *url([NSURL URLWithString:href]);
8702 NSStringEncoding encoding;
8703 NSError *error(nil);
8705 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8706 return [warning length] == 0 ? nil : warning;
8710 - (void) _endConnection:(NSURLConnection *)connection {
8711 // XXX: the memory management in this method is horribly awkward
8713 NSURLConnection **field = NULL;
8714 if (connection == trivial_bz2_)
8715 field = &trivial_bz2_;
8716 else if (connection == trivial_gz_)
8717 field = &trivial_gz_;
8718 _assert(field != NULL);
8719 [connection release];
8723 trivial_bz2_ == nil &&
8726 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8728 [delegate_ releaseNetworkActivityIndicator];
8730 [delegate_ removeProgressHUD:hud_];
8734 if (warning != nil) {
8735 UIAlertView *alert = [[[UIAlertView alloc]
8736 initWithTitle:UCLocalize("SOURCE_WARNING")
8739 cancelButtonTitle:UCLocalize("CANCEL")
8741 UCLocalize("ADD_ANYWAY"),
8745 [alert setContext:@"warning"];
8746 [alert setNumberOfRows:1];
8749 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8755 } else if (error_ != nil) {
8756 UIAlertView *alert = [[[UIAlertView alloc]
8757 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8758 message:[error_ localizedDescription]
8760 cancelButtonTitle:UCLocalize("OK")
8761 otherButtonTitles:nil
8764 [alert setContext:@"urlerror"];
8769 UIAlertView *alert = [[[UIAlertView alloc]
8770 initWithTitle:UCLocalize("NOT_REPOSITORY")
8771 message:UCLocalize("NOT_REPOSITORY_EX")
8773 cancelButtonTitle:UCLocalize("OK")
8774 otherButtonTitles:nil
8777 [alert setContext:@"trivial"];
8787 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8788 switch ([response statusCode]) {
8794 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8795 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8797 [self _endConnection:connection];
8800 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8801 [self _endConnection:connection];
8804 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8805 NSURL *url([NSURL URLWithString:href]);
8807 NSMutableURLRequest *request = [NSMutableURLRequest
8809 cachePolicy:NSURLRequestUseProtocolCachePolicy
8813 [request setHTTPMethod:method];
8815 if (Machine_ != NULL)
8816 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8818 if (UniqueID_ != nil)
8819 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8821 if ([url isCydiaSecure]) {
8822 if (UniqueID_ != nil)
8823 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8826 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8829 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8830 NSString *context([alert context]);
8832 if ([context isEqualToString:@"source"]) {
8835 NSString *href = [[alert textField] text];
8837 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8839 if (![href hasSuffix:@"/"])
8840 href_ = [href stringByAppendingString:@"/"];
8844 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8845 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8846 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8850 // XXX: this is stupid
8851 hud_ = [delegate_ addProgressHUD];
8852 [hud_ setText:UCLocalize("VERIFYING_URL")];
8853 [delegate_ retainNetworkActivityIndicator];
8862 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8863 } else if ([context isEqualToString:@"trivial"])
8864 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8865 else if ([context isEqualToString:@"urlerror"])
8866 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8867 else if ([context isEqualToString:@"warning"]) {
8870 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8879 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8884 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8885 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8886 [list_ setRowHeight:53];
8887 [(UITableView *) list_ setDataSource:self];
8888 [list_ setDelegate:self];
8889 [self setView:list_];
8892 - (void) viewDidLoad {
8893 [super viewDidLoad];
8895 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8896 [self updateButtonsForEditingStatusAnimated:NO];
8899 - (void) viewWillAppear:(BOOL)animated {
8900 [super viewWillAppear:animated];
8902 [list_ setEditing:NO];
8903 [self updateButtonsForEditingStatusAnimated:NO];
8906 - (void) releaseSubviews {
8911 [super releaseSubviews];
8914 - (id) initWithDatabase:(Database *)database {
8915 if ((self = [super init]) != nil) {
8916 database_ = database;
8920 - (void) reloadData {
8923 @synchronized (database_) {
8924 era_ = [database_ era];
8926 sources_ = [NSMutableArray arrayWithCapacity:16];
8927 [sources_ addObjectsFromArray:[database_ sources]];
8929 [sources_ sortUsingSelector:@selector(compareByName:)];
8932 int count([sources_ count]);
8934 for (int i = 0; i != count; i++) {
8935 if ([[sources_ objectAtIndex:i] record] == nil)
8943 - (void) showAddSourcePrompt {
8944 UIAlertView *alert = [[[UIAlertView alloc]
8945 initWithTitle:UCLocalize("ENTER_APT_URL")
8948 cancelButtonTitle:UCLocalize("CANCEL")
8950 UCLocalize("ADD_SOURCE"),
8954 [alert setContext:@"source"];
8956 [alert setNumberOfRows:1];
8957 [alert addTextFieldWithValue:@"http://" label:@""];
8959 UITextInputTraits *traits = [[alert textField] textInputTraits];
8960 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8961 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8962 [traits setKeyboardType:UIKeyboardTypeURL];
8963 // XXX: UIReturnKeyDone
8964 [traits setReturnKeyType:UIReturnKeyNext];
8969 - (void) addButtonClicked {
8970 [self showAddSourcePrompt];
8973 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8974 BOOL editing([list_ isEditing]);
8976 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8977 initWithTitle:UCLocalize("ADD")
8978 style:UIBarButtonItemStylePlain
8980 action:@selector(addButtonClicked)
8981 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8983 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8984 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8985 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8987 action:@selector(editButtonClicked)
8988 ] autorelease] animated:animated];
8990 if (IsWildcat_ && !editing)
8991 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8992 initWithTitle:UCLocalize("SETTINGS")
8993 style:UIBarButtonItemStylePlain
8995 action:@selector(settingsButtonClicked)
8999 - (void) settingsButtonClicked {
9000 [delegate_ showSettings];
9003 - (void) editButtonClicked {
9004 [list_ setEditing:![list_ isEditing] animated:YES];
9005 [self updateButtonsForEditingStatusAnimated:YES];
9011 /* Settings Controller {{{ */
9012 @interface SettingsController : CyteViewController <
9013 UITableViewDataSource,
9016 _transient Database *database_;
9017 // XXX: ok, "roledelegate_"?...
9018 _transient id roledelegate_;
9019 _H<UITableView, 2> table_;
9020 _H<UISegmentedControl> segment_;
9021 _H<UIView> container_;
9024 - (void) showDoneButton;
9025 - (void) resizeSegmentedControl;
9029 @implementation SettingsController
9032 table_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
9033 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9034 [table_ setDelegate:self];
9035 [(UITableView *) table_ setDataSource:self];
9036 [self setView:table_];
9038 NSArray *items = [NSArray arrayWithObjects:
9040 UCLocalize("HACKER"),
9041 UCLocalize("DEVELOPER"),
9043 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
9044 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
9045 [container_ addSubview:segment_];
9048 - (void) viewDidLoad {
9049 [super viewDidLoad];
9051 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
9054 if ([Role_ isEqualToString:@"User"]) index = 0;
9055 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
9056 if ([Role_ isEqualToString:@"Developer"]) index = 2;
9058 [segment_ setSelectedSegmentIndex:index];
9059 [self showDoneButton];
9062 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
9063 [self resizeSegmentedControl];
9066 - (void) releaseSubviews {
9071 [super releaseSubviews];
9074 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
9075 if ((self = [super init]) != nil) {
9076 database_ = database;
9077 roledelegate_ = delegate;
9081 - (void) resizeSegmentedControl {
9082 CGFloat width = [[self view] frame].size.width;
9083 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
9086 - (void) viewWillAppear:(BOOL)animated {
9087 [super viewWillAppear:animated];
9088 [self resizeSegmentedControl];
9091 - (void) viewDidAppear:(BOOL)animated {
9092 [super viewDidAppear:animated];
9093 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
9094 [self resizeSegmentedControl];
9097 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
9098 [self resizeSegmentedControl];
9101 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
9102 [self resizeSegmentedControl];
9106 NSString *role(nil);
9108 switch ([segment_ selectedSegmentIndex]) {
9109 case 0: role = @"User"; break;
9110 case 1: role = @"Hacker"; break;
9111 case 2: role = @"Developer"; break;
9116 if (![role isEqualToString:Role_]) {
9117 bool rolling(Role_ == nil);
9120 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
9124 [Metadata_ setObject:Settings_ forKey:@"Settings"];
9128 [roledelegate_ loadData];
9130 [roledelegate_ updateData];
9134 - (void) segmentChanged:(UISegmentedControl *)control {
9135 [self showDoneButton];
9138 - (void) saveAndClose {
9141 [[self navigationItem] setRightBarButtonItem:nil];
9142 [[self navigationController] dismissModalViewControllerAnimated:YES];
9145 - (void) doneButtonClicked {
9146 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
9147 [spinner startAnimating];
9148 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
9149 [[self navigationItem] setRightBarButtonItem:spinItem];
9151 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
9154 - (void) showDoneButton {
9155 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
9156 initWithTitle:UCLocalize("DONE")
9157 style:UIBarButtonItemStyleDone
9159 action:@selector(doneButtonClicked)
9160 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
9163 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
9164 // XXX: For not having a single cell in the table, this sure is a lot of sections.
9168 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
9172 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
9173 return nil; // This method is required by the protocol.
9176 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
9178 return UCLocalize("ROLE_EX");
9180 return [NSString stringWithFormat:
9181 @"%@: %@\n%@: %@\n%@: %@",
9182 UCLocalize("USER"), UCLocalize("USER_EX"),
9183 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
9184 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
9189 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
9190 return section == 3 ? 44.0f : 0;
9193 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
9194 return section == 3 ? container_ : nil;
9197 - (void) reloadData {
9200 [table_ reloadData];
9205 /* Stash Controller {{{ */
9206 @interface StashController : CyteViewController {
9207 _H<UIActivityIndicatorView> spinner_;
9208 _H<UILabel> status_;
9209 _H<UILabel> caption_;
9214 @implementation StashController
9217 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
9218 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
9219 [self setView:view];
9221 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
9223 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
9224 CGRect spinrect = [spinner_ frame];
9225 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
9226 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
9227 [spinner_ setFrame:spinrect];
9228 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
9229 [view addSubview:spinner_];
9230 [spinner_ startAnimating];
9233 captrect.size.width = [[self view] frame].size.width;
9234 captrect.size.height = 40.0f;
9235 captrect.origin.x = 0;
9236 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
9237 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
9238 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
9239 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9240 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
9241 [caption_ setTextColor:[UIColor whiteColor]];
9242 [caption_ setBackgroundColor:[UIColor clearColor]];
9243 [caption_ setShadowColor:[UIColor blackColor]];
9244 [caption_ setTextAlignment:UITextAlignmentCenter];
9245 [view addSubview:caption_];
9248 statusrect.size.width = [[self view] frame].size.width;
9249 statusrect.size.height = 30.0f;
9250 statusrect.origin.x = 0;
9251 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
9252 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
9253 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9254 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
9255 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
9256 [status_ setTextColor:[UIColor whiteColor]];
9257 [status_ setBackgroundColor:[UIColor clearColor]];
9258 [status_ setShadowColor:[UIColor blackColor]];
9259 [status_ setTextAlignment:UITextAlignmentCenter];
9260 [view addSubview:status_];
9263 - (void) releaseSubviews {
9268 [super releaseSubviews];
9274 @interface CYURLCache : SDURLCache {
9279 @implementation CYURLCache
9281 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
9284 else if ([event isEqualToString:@"no-cache"])
9286 else if ([event isEqualToString:@"store"])
9288 else if ([event isEqualToString:@"invalid"])
9290 else if ([event isEqualToString:@"memory"])
9292 else if ([event isEqualToString:@"disk"])
9294 else if ([event isEqualToString:@"miss"])
9297 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
9301 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
9302 if (NSURLResponse *response = [cached response])
9303 if (NSString *mime = [response MIMEType])
9304 if ([mime isEqualToString:@"text/cache-manifest"]) {
9305 NSURL *url([response URL]);
9308 NSLog(@"###: %@", [url absoluteString]);
9311 @synchronized (HostConfig_) {
9312 [CachedURLs_ addObject:url];
9316 [super storeCachedResponse:cached forRequest:request];
9321 @interface Cydia : UIApplication <
9322 ConfirmationControllerDelegate,
9325 UINavigationControllerDelegate,
9326 UITabBarControllerDelegate
9328 _H<UIWindow> window_;
9329 _H<CYTabBarController> tabbar_;
9330 _H<CydiaLoadingViewController> emulated_;
9332 _H<NSMutableArray> essential_;
9333 _H<NSMutableArray> broken_;
9335 Database *database_;
9337 _H<NSURL> starturl_;
9342 _H<StashController> stash_;
9351 @implementation Cydia
9353 - (void) lockSuspend {
9354 if (locked_++ == 0) {
9355 if ($SBSSetInterceptsMenuButtonForever != NULL)
9356 (*$SBSSetInterceptsMenuButtonForever)(true);
9358 [self setIdleTimerDisabled:YES];
9362 - (void) unlockSuspend {
9363 if (--locked_ == 0) {
9364 [self setIdleTimerDisabled:NO];
9366 if ($SBSSetInterceptsMenuButtonForever != NULL)
9367 (*$SBSSetInterceptsMenuButtonForever)(false);
9371 - (void) beginUpdate {
9372 [tabbar_ beginUpdate];
9376 return [tabbar_ updating];
9380 if ([broken_ count] != 0) {
9381 int count = [broken_ count];
9383 UIAlertView *alert = [[[UIAlertView alloc]
9384 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9385 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9387 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9389 UCLocalize("TEMPORARY_IGNORE"),
9393 [alert setContext:@"fixhalf"];
9394 [alert setNumberOfRows:2];
9396 } else if (!Ignored_ && [essential_ count] != 0) {
9397 int count = [essential_ count];
9399 UIAlertView *alert = [[[UIAlertView alloc]
9400 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9401 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9403 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9405 UCLocalize("UPGRADE_ESSENTIAL"),
9406 UCLocalize("COMPLETE_UPGRADE"),
9410 [alert setContext:@"upgrade"];
9415 - (void) returnToCydia {
9419 - (void) _saveConfig {
9420 @synchronized (database_) {
9427 NSString *error(nil);
9429 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9431 NSError *error(nil);
9432 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9433 NSLog(@"failure to save metadata data: %@", error);
9438 NSLog(@"failure to serialize metadata: %@", error);
9442 CydiaWriteSources();
9445 // Navigation controller for the queuing badge.
9446 - (UINavigationController *) queueNavigationController {
9447 NSArray *controllers = [tabbar_ viewControllers];
9448 return [controllers objectAtIndex:3];
9451 - (void) unloadData {
9452 [tabbar_ unloadData];
9455 - (void) _updateData {
9459 UINavigationController *navigation = [self queueNavigationController];
9461 id queuedelegate = nil;
9462 if ([[navigation viewControllers] count] > 0)
9463 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9465 [queuedelegate queueStatusDidChange];
9466 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9469 - (void) _refreshIfPossible:(NSDate *)update {
9470 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9472 bool recently = false;
9473 if (update != nil) {
9474 NSTimeInterval interval([update timeIntervalSinceNow]);
9475 if (interval <= 0 && interval > -(15*60))
9479 // Don't automatic refresh if:
9480 // - We already refreshed recently.
9481 // - We already auto-refreshed this launch.
9482 // - Auto-refresh is disabled.
9483 // - Cydia's server is not reachable
9484 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9485 // If we are cancelling, we need to make sure it knows it's already loaded.
9488 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9490 // We are going to load, so remember that.
9493 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9499 - (void) refreshIfPossible {
9500 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9503 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9504 @synchronized (self) {
9505 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9507 [hud setText:UCLocalize("RELOADING_DATA")];
9509 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9513 [essential_ removeAllObjects];
9514 [broken_ removeAllObjects];
9516 NSArray *packages([database_ packages]);
9517 for (Package *package in packages) {
9519 [broken_ addObject:package];
9520 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9521 if ([package essential] && [package installed] != nil)
9522 [essential_ addObject:package];
9527 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9530 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9531 [changesItem setBadgeValue:badge];
9532 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9533 [self setApplicationIconBadgeNumber:changes];
9536 [changesItem setBadgeValue:nil];
9537 [changesItem setAnimatedBadge:NO];
9538 [self setApplicationIconBadgeNumber:0];
9544 [self removeProgressHUD:hud];
9547 - (void) updateData {
9551 - (void) updateDataAndLoad {
9553 if ([database_ progressDelegate] == nil)
9559 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9562 - (void) disemulate {
9563 if (emulated_ == nil)
9566 [window_ addSubview:[tabbar_ view]];
9567 [[emulated_ view] removeFromSuperview];
9569 [window_ setUserInteractionEnabled:YES];
9572 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9573 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9575 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9577 UIViewController *parent;
9578 if (emulated_ == nil)
9587 [parent presentModalViewController:navigation animated:YES];
9590 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9591 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9593 if (navigation != nil)
9594 [navigation pushViewController:progress animated:YES];
9596 [self presentModalViewController:progress force:YES];
9598 [progress invoke:invocation withTitle:title];
9602 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9603 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9606 - (void) repairWithInvocation:(NSInvocation *)invocation {
9608 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9612 - (void) repairWithSelector:(SEL)selector {
9613 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9616 - (void) reloadData {
9617 [self reloadDataWithInvocation:nil];
9618 if ([database_ progressDelegate] == nil)
9624 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9627 - (void) addSource:(NSDictionary *) source {
9628 CydiaAddSource(source);
9631 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9632 CydiaAddSource(href, distribution, sections);
9635 - (void) addTrivialSource:(NSString *)href {
9636 CydiaAddSource(href, @"./");
9639 - (void) updateValues {
9644 pkgProblemResolver *resolver = [database_ resolver];
9646 resolver->InstallProtect();
9647 if (!resolver->Resolve(true))
9652 // XXX: this is a really crappy way of doing this.
9653 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9654 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9655 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9656 if ([tabbar_ updating])
9657 [tabbar_ cancelUpdate];
9659 if (![database_ prepare])
9662 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9663 [page setDelegate:self];
9664 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9667 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9668 [tabbar_ presentModalViewController:confirm_ animated:YES];
9674 @synchronized (self) {
9679 - (void) clearPackage:(Package *)package {
9680 @synchronized (self) {
9687 - (void) installPackages:(NSArray *)packages {
9688 @synchronized (self) {
9689 for (Package *package in packages)
9696 - (void) installPackage:(Package *)package {
9697 @synchronized (self) {
9704 - (void) removePackage:(Package *)package {
9705 @synchronized (self) {
9712 - (void) distUpgrade {
9713 @synchronized (self) {
9714 if (![database_ upgrade])
9722 system("su -c /usr/bin/uicache mobile");
9727 UIProgressHUD *hud([self addProgressHUD]);
9728 [hud setText:UCLocalize("LOADING")];
9729 [self yieldToSelector:@selector(_uicache)];
9730 [self removeProgressHUD:hud];
9734 [database_ perform];
9735 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9736 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9739 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9742 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9743 [self unlockSuspend];
9746 - (void) showSettings {
9747 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9750 - (void) retainNetworkActivityIndicator {
9751 if (activity_++ == 0)
9752 [self setNetworkActivityIndicatorVisible:YES];
9755 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9759 - (void) releaseNetworkActivityIndicator {
9760 if (--activity_ == 0)
9761 [self setNetworkActivityIndicatorVisible:NO];
9764 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9769 - (void) cancelAndClear:(bool)clear {
9770 @synchronized (self) {
9782 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9783 NSString *context([alert context]);
9785 if ([context isEqualToString:@"conffile"]) {
9786 FILE *input = [database_ input];
9787 if (button == [alert cancelButtonIndex])
9788 fprintf(input, "N\n");
9789 else if (button == [alert firstOtherButtonIndex])
9790 fprintf(input, "Y\n");
9793 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9794 } else if ([context isEqualToString:@"fixhalf"]) {
9795 if (button == [alert cancelButtonIndex]) {
9796 @synchronized (self) {
9797 for (Package *broken in (id) broken_) {
9800 NSString *id = [broken id];
9801 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9802 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9803 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9804 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9810 } else if (button == [alert firstOtherButtonIndex]) {
9811 [broken_ removeAllObjects];
9815 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9816 } else if ([context isEqualToString:@"upgrade"]) {
9817 if (button == [alert firstOtherButtonIndex]) {
9818 @synchronized (self) {
9819 for (Package *essential in (id) essential_)
9820 [essential install];
9825 } else if (button == [alert firstOtherButtonIndex] + 1) {
9827 } else if (button == [alert cancelButtonIndex]) {
9831 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9835 - (void) system:(NSString *)command {
9836 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9839 system([command UTF8String]);
9845 - (void) applicationWillSuspend {
9847 [super applicationWillSuspend];
9850 - (BOOL) isSafeToSuspend {
9853 NSLog(@"isSafeToSuspend: locked_ != 0");
9858 // Use external process status API internally.
9859 // This is probably a really bad idea.
9860 // XXX: what is the point of this? does this solve anything at all?
9861 uint64_t status = 0;
9863 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9864 notify_get_state(notify_token, &status);
9865 notify_cancel(notify_token);
9870 NSLog(@"isSafeToSuspend: status != 0");
9876 NSLog(@"isSafeToSuspend: -> true");
9881 - (void) applicationSuspend:(__GSEvent *)event {
9882 if ([self isSafeToSuspend])
9883 [super applicationSuspend:event];
9886 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9887 if ([self isSafeToSuspend])
9888 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9891 - (void) _setSuspended:(BOOL)value {
9892 if ([self isSafeToSuspend])
9893 [super _setSuspended:value];
9896 - (UIProgressHUD *) addProgressHUD {
9897 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9898 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9900 [window_ setUserInteractionEnabled:NO];
9902 UIViewController *target(tabbar_);
9903 if (UIViewController *modal = [target modalViewController])
9906 [hud showInView:[target view]];
9912 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9913 [self unlockSuspend];
9915 [hud removeFromSuperview];
9916 [window_ setUserInteractionEnabled:YES];
9919 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9920 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9923 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9924 NSString *scheme([[url scheme] lowercaseString]);
9925 if ([[url absoluteString] length] <= [scheme length] + 3)
9927 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9928 NSArray *components([path componentsSeparatedByString:@"/"]);
9930 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9931 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9932 if (controller != nil)
9933 [controller setDelegate:self];
9937 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9940 NSString *base([components objectAtIndex:0]);
9942 CyteViewController *controller = nil;
9944 if ([base isEqualToString:@"url"]) {
9945 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9946 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9947 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9948 } else if (!external && [components count] == 1) {
9949 if ([base isEqualToString:@"manage"]) {
9950 controller = [[[ManageController alloc] init] autorelease];
9953 if ([base isEqualToString:@"storage"]) {
9954 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9957 if ([base isEqualToString:@"sources"]) {
9958 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9961 if ([base isEqualToString:@"home"]) {
9962 controller = [[[HomeController alloc] init] autorelease];
9965 if ([base isEqualToString:@"sections"]) {
9966 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9969 if ([base isEqualToString:@"search"]) {
9970 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9973 if ([base isEqualToString:@"changes"]) {
9974 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9977 if ([base isEqualToString:@"installed"]) {
9978 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9980 } else if ([components count] == 2) {
9981 NSString *argument = [components objectAtIndex:1];
9983 if ([base isEqualToString:@"package"]) {
9984 controller = [self pageForPackage:argument withReferrer:referrer];
9987 if (!external && [base isEqualToString:@"search"]) {
9988 controller = [[[SearchController alloc] initWithDatabase:database_ query:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9991 if (!external && [base isEqualToString:@"sections"]) {
9992 if ([argument isEqualToString:@"all"])
9994 controller = [[[SectionController alloc] initWithDatabase:database_ section:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9997 if (!external && [base isEqualToString:@"sources"]) {
9998 if ([argument isEqualToString:@"add"]) {
9999 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
10000 [(SourcesController *)controller showAddSourcePrompt];
10002 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
10003 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
10007 if (!external && [base isEqualToString:@"launch"]) {
10008 [self launchApplicationWithIdentifier:argument suspended:NO];
10011 } else if (!external && [components count] == 3) {
10012 NSString *arg1 = [components objectAtIndex:1];
10013 NSString *arg2 = [components objectAtIndex:2];
10015 if ([base isEqualToString:@"package"]) {
10016 if ([arg2 isEqualToString:@"settings"]) {
10017 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
10018 } else if ([arg2 isEqualToString:@"files"]) {
10019 if (Package *package = [database_ packageWithName:arg1]) {
10020 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
10021 [(FileTable *)controller setPackage:package];
10027 [controller setDelegate:self];
10031 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
10032 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
10035 [tabbar_ setUnselectedViewController:page];
10037 return page != nil;
10040 - (void) applicationOpenURL:(NSURL *)url {
10041 [super applicationOpenURL:url];
10046 [self openCydiaURL:url forExternal:YES];
10049 - (void) applicationWillResignActive:(UIApplication *)application {
10050 // Stop refreshing if you get a phone call or lock the device.
10051 if ([tabbar_ updating])
10052 [tabbar_ cancelUpdate];
10054 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
10055 [super applicationWillResignActive:application];
10058 - (void) saveState {
10059 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
10060 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
10061 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
10064 [self _saveConfig];
10067 - (void) applicationWillTerminate:(UIApplication *)application {
10071 - (void) setConfigurationData:(NSString *)data {
10072 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
10074 if (!conffile_r(data)) {
10075 lprintf("E:invalid conffile\n");
10079 NSString *ofile = conffile_r[1];
10080 //NSString *nfile = conffile_r[2];
10082 UIAlertView *alert = [[[UIAlertView alloc]
10083 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
10084 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
10086 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
10088 UCLocalize("ACCEPT_NEW_COPY"),
10089 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
10093 [alert setContext:@"conffile"];
10094 [alert setNumberOfRows:2];
10098 - (void) addStashController {
10099 [self lockSuspend];
10100 stash_ = [[[StashController alloc] init] autorelease];
10101 [window_ addSubview:[stash_ view]];
10104 - (void) removeStashController {
10105 [[stash_ view] removeFromSuperview];
10107 [self unlockSuspend];
10111 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
10112 UpdateExternalStatus(1);
10113 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
10114 UpdateExternalStatus(0);
10116 [self removeStashController];
10118 pid_t pid(ExecFork());
10120 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
10121 perror("launchctl stop");
10128 - (void) setupViewControllers {
10129 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
10131 NSMutableArray *items([NSMutableArray arrayWithObjects:
10132 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
10133 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
10134 [[[UITabBarItem alloc] initWithTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES")) image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
10135 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
10139 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
10140 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10142 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10145 NSMutableArray *controllers([NSMutableArray array]);
10146 for (UITabBarItem *item in items) {
10147 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
10148 [controller setTabBarItem:item];
10149 [controllers addObject:controller];
10151 [tabbar_ setViewControllers:controllers];
10153 [tabbar_ setUpdateDelegate:self];
10156 - (void) _sendMemoryWarningNotification {
10157 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
10158 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
10160 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
10163 - (void) _sendMemoryWarningNotifications {
10165 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
10171 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
10173 [[NSURLCache sharedURLCache] removeAllCachedResponses];
10176 - (void) applicationDidFinishLaunching:(id)unused {
10177 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
10180 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
10181 [self setApplicationSupportsShakeToEdit:NO];
10183 @synchronized (HostConfig_) {
10184 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
10187 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
10188 initWithMemoryCapacity:524288
10189 diskCapacity:10485760
10190 diskPath:[NSString stringWithFormat:@"%@/SDURLCache", Cache_]
10193 [CydiaWebViewController _initialize];
10195 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
10197 // this would disallow http{,s} URLs from accessing this data
10198 //[WebView registerURLSchemeAsLocal:@"cydia"];
10200 Font12_ = [UIFont systemFontOfSize:12];
10201 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
10202 Font14_ = [UIFont systemFontOfSize:14];
10203 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
10204 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
10206 essential_ = [NSMutableArray arrayWithCapacity:4];
10207 broken_ = [NSMutableArray arrayWithCapacity:4];
10209 // XXX: I really need this thing... like, seriously... I'm sorry
10210 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
10212 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
10213 [window_ orderFront:self];
10214 [window_ makeKey:self];
10215 [window_ setHidden:NO];
10217 if (false) stash: {
10218 [self addStashController];
10219 // XXX: this would be much cleaner as a yieldToSelector:
10220 // that way the removeStashController could happen right here inline
10221 // we also could no longer require the useless stash_ field anymore
10222 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
10227 int error(stat("/", &root));
10228 _assert(error != -1);
10230 #define Stash_(path) do { \
10231 struct stat folder; \
10232 int error(lstat((path), &folder)); \
10233 if (error != -1 && ( \
10234 folder.st_dev == root.st_dev && \
10235 S_ISDIR(folder.st_mode) \
10236 ) || error == -1 && ( \
10237 errno == ENOENT || \
10242 Stash_("/Applications");
10243 Stash_("/Library/Ringtones");
10244 Stash_("/Library/Wallpaper");
10245 //Stash_("/usr/bin");
10246 Stash_("/usr/include");
10247 Stash_("/usr/lib/pam");
10248 Stash_("/usr/libexec");
10249 Stash_("/usr/share");
10250 //Stash_("/var/lib");
10252 database_ = [Database sharedInstance];
10253 [database_ setDelegate:self];
10255 [window_ setUserInteractionEnabled:NO];
10256 [self setupViewControllers];
10258 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
10259 [window_ addSubview:[emulated_ view]];
10261 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
10265 - (NSArray *) defaultStartPages {
10266 NSMutableArray *standard = [NSMutableArray array];
10267 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
10268 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
10269 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
10271 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
10273 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
10274 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
10276 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10280 - (void) loadData {
10282 if (Role_ == nil) {
10283 [window_ setUserInteractionEnabled:YES];
10284 [self showSettings];
10287 if ([emulated_ modalViewController] != nil)
10288 [emulated_ dismissModalViewControllerAnimated:YES];
10289 [window_ setUserInteractionEnabled:NO];
10292 [self reloadDataWithInvocation:nil];
10293 [self refreshIfPossible];
10298 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
10299 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
10300 int standardIndex = 0;
10301 NSArray *standard = [self defaultStartPages];
10308 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
10309 if (valid && closed != nil) {
10310 NSTimeInterval interval([closed timeIntervalSinceNow]);
10311 // XXX: Is 30 minutes the optimal time here?
10312 if (interval <= -(30*60))
10316 if (valid && [saved count] != [standard count])
10320 for (unsigned int i = 0; i < [standard count]; i++) {
10321 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10322 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10323 // but it's good enough for now.
10324 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10331 NSArray *items = nil;
10333 [tabbar_ setSelectedIndex:savedIndex];
10336 [tabbar_ setSelectedIndex:standardIndex];
10340 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10341 NSArray *stack = [items objectAtIndex:tab];
10342 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10343 NSMutableArray *current = [NSMutableArray array];
10345 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10346 NSString *addr = [stack objectAtIndex:nav];
10347 NSURL *url = [NSURL URLWithString:addr];
10348 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10350 [current addObject:page];
10353 [navigation setViewControllers:current];
10356 // (Try to) show the startup URL.
10357 if (starturl_ != nil) {
10358 [self openCydiaURL:starturl_ forExternal:NO];
10363 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10364 if (item != nil && IsWildcat_) {
10365 [sheet showFromBarButtonItem:item animated:YES];
10367 [sheet showInView:window_];
10371 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10372 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10373 [progress setTitle:task];
10374 [progress addProgressEvent:event];
10377 - (void) addProgressEventForTask:(NSArray *)data {
10378 CydiaProgressEvent *event([data objectAtIndex:0]);
10379 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10380 [self addProgressEvent:event forTask:task];
10383 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10384 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10390 id Alloc_(id self, SEL selector) {
10391 id object = alloc_(self, selector);
10392 lprintf("[%s]A-%p\n", self->isa->name, object);
10397 id Dealloc_(id self, SEL selector) {
10398 id object = dealloc_(self, selector);
10399 lprintf("[%s]D-%p\n", self->isa->name, object);
10403 static NSSet *MobilizedFiles_;
10405 static NSURL *MobilizeURL(NSURL *url) {
10406 NSString *path([url path]);
10407 if ([path hasPrefix:@"/var/root/"]) {
10408 NSString *file([path substringFromIndex:10]);
10409 if ([MobilizedFiles_ containsObject:file])
10410 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10416 Class $CFXPreferencesPropertyListSource;
10417 @class CFXPreferencesPropertyListSource;
10419 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10420 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10421 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10422 url = MobilizeURL(url);
10423 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10424 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10430 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10431 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10432 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10433 url = MobilizeURL(url);
10434 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10435 //NSLog(@"%@ %@", [url absoluteString], value);
10441 Class $NSURLConnection;
10443 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10444 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10446 NSURL *url([copy URL]);
10448 NSString *host([url host]);
10449 NSString *scheme([[url scheme] lowercaseString]);
10451 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10453 @synchronized (HostConfig_) {
10454 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10455 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10456 [copy setHTTPShouldUsePipelining:YES];
10458 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10459 if ([control isEqualToString:@"max-age=0"])
10460 if ([CachedURLs_ containsObject:url]) {
10462 NSLog(@"~~~: %@", url);
10465 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10467 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10468 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10469 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10473 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10479 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10480 CGSize size([[UIScreen mainScreen] bounds].size);
10481 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10482 if ([$WAKWindow hasLandscapeOrientation])
10483 std::swap(size.width, size.height);*/
10487 Class $NSUserDefaults;
10489 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10490 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10491 return [NSString stringWithFormat:@"%@/LocalStorage", Cache_];
10492 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10495 int main(int argc, char *argv[]) {
10496 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10500 UpdateExternalStatus(0);
10502 if (Class $UIDevice = objc_getClass("UIDevice")) {
10503 UIDevice *device([$UIDevice currentDevice]);
10504 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10506 IsWildcat_ = false;
10508 UIScreen *screen([UIScreen mainScreen]);
10509 if ([screen respondsToSelector:@selector(scale)])
10510 ScreenScale_ = [screen scale];
10514 UIDevice *device([UIDevice currentDevice]);
10515 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10516 Idiom_ = @"iphone";
10518 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10519 if (idiom == UIUserInterfaceIdiomPhone)
10520 Idiom_ = @"iphone";
10521 else if (idiom == UIUserInterfaceIdiomPad)
10524 NSLog(@"unknown UIUserInterfaceIdiom!");
10527 Pcre pattern("^([0-9]+\\.[0-9]+)");
10529 if (pattern([device systemVersion]))
10530 Firmware_ = pattern[1];
10531 if (pattern(Cydia_))
10532 Major_ = pattern[1];
10534 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10536 HostConfig_ = [[[NSObject alloc] init] autorelease];
10537 @synchronized (HostConfig_) {
10538 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10539 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10540 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10541 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10542 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10545 NSString *ui(@"ui/ios");
10547 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10548 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10549 UI_ = CydiaURL(ui);
10551 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10553 MobilizedFiles_ = [NSMutableSet setWithObjects:
10554 @"Library/Preferences/com.apple.Accessibility.plist",
10555 @"Library/Preferences/com.apple.preferences.sounds.plist",
10558 /* Library Hacks {{{ */
10559 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10561 $WAKWindow = objc_getClass("WAKWindow");
10562 if ($WAKWindow != NULL)
10563 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10564 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10566 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10568 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10569 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10570 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10571 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10574 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10575 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10576 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10577 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10580 $NSURLConnection = objc_getClass("NSURLConnection");
10581 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10582 if (NSURLConnection$init$ != NULL) {
10583 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10584 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10587 $NSUserDefaults = objc_getClass("NSUserDefaults");
10588 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10589 if (NSUserDefaults$objectForKey$ != NULL) {
10590 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10591 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10594 /* Set Locale {{{ */
10595 Locale_ = CFLocaleCopyCurrent();
10596 Languages_ = [NSLocale preferredLanguages];
10598 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10599 //NSLog(@"%@", [Languages_ description]);
10602 if (Locale_ != NULL)
10603 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10604 else if (Languages_ != nil && [Languages_ count] != 0)
10605 lang = [[Languages_ objectAtIndex:0] UTF8String];
10607 // XXX: consider just setting to C and then falling through?
10610 if (lang != NULL) {
10611 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10612 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10615 NSLog(@"Setting Language: %s", lang);
10617 if (lang != NULL) {
10618 setenv("LANG", lang, true);
10619 std::setlocale(LC_ALL, lang);
10623 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10625 /* Parse Arguments {{{ */
10626 bool substrate(false);
10632 for (int argi(1); argi != argc; ++argi)
10633 if (strcmp(argv[argi], "--") == 0) {
10635 argv[argi] = argv[0];
10641 for (int argi(1); argi != arge; ++argi)
10642 if (strcmp(args[argi], "--substrate") == 0)
10645 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10649 App_ = [[NSBundle mainBundle] bundlePath];
10655 if (access("/var/mobile/Library/Keyboard/UserDictionary.sqlite", F_OK) == 0)
10656 system("mkdir -p /var/root/Library/Keyboard; cp -af /var/mobile/Library/Keyboard/UserDictionary.sqlite /var/root/Library/Keyboard/");
10658 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/root"] retain];
10660 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10661 alloc_ = alloc->method_imp;
10662 alloc->method_imp = (IMP) &Alloc_;*/
10664 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10665 dealloc_ = dealloc->method_imp;
10666 dealloc->method_imp = (IMP) &Dealloc_;*/
10668 /* System Information {{{ */
10672 size = sizeof(maxproc);
10673 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10674 perror("sysctlbyname(\"kern.maxproc\", ?)");
10675 else if (maxproc < 64) {
10677 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10678 perror("sysctlbyname(\"kern.maxproc\", #)");
10681 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10682 char *osversion = new char[size];
10683 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10684 perror("sysctlbyname(\"kern.osversion\", ?)");
10686 System_ = [NSString stringWithUTF8String:osversion];
10688 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10689 char *machine = new char[size];
10690 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10691 perror("sysctlbyname(\"hw.machine\", ?)");
10693 Machine_ = machine;
10695 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10696 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10697 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10699 UniqueID_ = [device uniqueIdentifier];
10701 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10702 Product_ = [info objectForKey:@"SafariProductVersion"];
10703 Safari_ = [info objectForKey:@"CFBundleVersion"];
10706 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10708 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10709 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10710 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10711 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10712 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10713 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10715 UserAgent_ = agent;
10717 /* Load Database {{{ */
10719 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10721 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10723 if (Metadata_ == NULL)
10724 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10726 Settings_ = [Metadata_ objectForKey:@"Settings"];
10728 Packages_ = [Metadata_ objectForKey:@"Packages"];
10730 Values_ = [Metadata_ objectForKey:@"Values"];
10731 Sections_ = [Metadata_ objectForKey:@"Sections"];
10732 Sources_ = [Metadata_ objectForKey:@"Sources"];
10734 Token_ = [Metadata_ objectForKey:@"Token"];
10736 Version_ = [Metadata_ objectForKey:@"Version"];
10739 if (Settings_ != nil)
10740 Role_ = [Settings_ objectForKey:@"Role"];
10742 if (Values_ == nil) {
10743 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10744 [Metadata_ setObject:Values_ forKey:@"Values"];
10747 if (Sections_ == nil) {
10748 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10749 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10752 if (Sources_ == nil) {
10753 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10754 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10757 if (Version_ == nil) {
10758 Version_ = [NSNumber numberWithUnsignedInt:0];
10759 [Metadata_ setObject:Version_ forKey:@"Version"];
10762 if ([Version_ unsignedIntValue] == 0) {
10763 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10764 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10765 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10766 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10768 Version_ = [NSNumber numberWithUnsignedInt:1];
10769 [Metadata_ setObject:Version_ forKey:@"Version"];
10771 [Metadata_ removeObjectForKey:@"LastUpdate"];
10777 CydiaWriteSources();
10780 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10783 if (Packages_ != nil) {
10785 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10789 [Metadata_ removeObjectForKey:@"Packages"];
10795 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10797 #define MobileSubstrate_(name) \
10798 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10799 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10800 if (handle == NULL) \
10801 NSLog(@"%s", dlerror()); \
10804 MobileSubstrate_(Activator)
10805 MobileSubstrate_(libstatusbar)
10806 MobileSubstrate_(SimulatedKeyEvents)
10807 MobileSubstrate_(WinterBoard)
10809 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10810 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10812 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10814 if (access("/User", F_OK) != 0 || version != 6) {
10816 system("/usr/libexec/cydia/firmware.sh");
10820 _assert([[NSFileManager defaultManager]
10821 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10822 withIntermediateDirectories:YES
10827 if (access("/tmp/cydia.chk", F_OK) == 0) {
10828 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10829 _assert(errno == ENOENT);
10830 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10831 _assert(errno == ENOENT);
10834 /* APT Initialization {{{ */
10835 _assert(pkgInitConfig(*_config));
10836 _assert(pkgInitSystem(*_config, _system));
10839 _config->Set("APT::Acquire::Translation", lang);
10841 // XXX: this timeout might be important :(
10842 //_config->Set("Acquire::http::Timeout", 15);
10844 _config->Set("Acquire::http::MaxParallel", 3);
10846 /* Color Choices {{{ */
10847 space_ = CGColorSpaceCreateDeviceRGB();
10849 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10850 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10851 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10852 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10853 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10854 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10855 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10856 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10857 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10859 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10860 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10862 /* UIKit Configuration {{{ */
10863 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10864 if ($GSFontSetUseLegacyFontMetrics != NULL)
10865 $GSFontSetUseLegacyFontMetrics(YES);
10867 // XXX: I have a feeling this was important
10868 //UIKeyboardDisableAutomaticAppearance();
10871 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10873 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemHasCapability"));
10874 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10876 ShowPromoted_ = fast;
10877 PulseInterval_ = fast ? 50000 : 500000;
10879 Colon_ = UCLocalize("COLON_DELIMITED");
10880 Elision_ = UCLocalize("ELISION");
10881 Error_ = UCLocalize("ERROR");
10882 Warning_ = UCLocalize("WARNING");
10884 AprilFools_ = false;
10887 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10889 CGColorSpaceRelease(space_);
10890 CFRelease(Locale_);