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 if (icon == nil || [icon length] == 0)
2890 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2892 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2893 [applications addObject:application];
2895 [application addObject:id];
2896 [application addObject:display];
2897 [application addObject:url];
2900 return [applications count] == 0 ? nil : applications;
2903 - (Source *) source {
2904 if (source_ == nil) {
2905 @synchronized (database_) {
2906 if ([database_ era] != era_ || file_.end())
2907 source_ = (Source *) [NSNull null];
2909 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2913 return source_ == (Source *) [NSNull null] ? nil : source_;
2920 - (BOOL) matches:(NSArray *)query {
2921 if (query == nil || [query count] == 0)
2930 string = [self name];
2931 length = [string length];
2933 for (NSString *term in query) {
2934 range = [string rangeOfString:term options:MatchCompareOptions_];
2935 if (range.location != NSNotFound)
2936 rank_ -= 6 * 1000000 / length;
2941 length = [string length];
2943 for (NSString *term in query) {
2944 range = [string rangeOfString:term options:MatchCompareOptions_];
2945 if (range.location != NSNotFound)
2946 rank_ -= 6 * 1000000 / length;
2950 string = [self shortDescription];
2951 length = [string length];
2952 NSUInteger stop(std::min<NSUInteger>(length, 200));
2954 for (NSString *term in query) {
2955 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2956 if (range.location != NSNotFound)
2957 rank_ -= 2 * 100000;
2963 - (bool) hasSupportingRole {
2968 if ([Role_ isEqualToString:@"User"])
2972 if ([Role_ isEqualToString:@"Hacker"])
2976 if ([Role_ isEqualToString:@"Developer"])
2981 - (NSArray *) tags {
2985 - (BOOL) hasTag:(NSString *)tag {
2986 return tags_ == nil ? NO : [tags_ containsObject:tag];
2989 - (NSString *) primaryPurpose {
2990 for (NSString *tag in (NSArray *) tags_)
2991 if ([tag hasPrefix:@"purpose::"])
2992 return [tag substringFromIndex:9];
2996 - (NSArray *) purposes {
2997 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2998 for (NSString *tag in (NSArray *) tags_)
2999 if ([tag hasPrefix:@"purpose::"])
3000 [purposes addObject:[tag substringFromIndex:9]];
3001 return [purposes count] == 0 ? nil : purposes;
3004 - (bool) isCommercial {
3005 return [self hasTag:@"cydia::commercial"];
3008 - (void) setIndex:(size_t)index {
3009 if (metadata_->index_ != index)
3010 metadata_->index_ = index;
3013 - (CYString &) cyname {
3014 return name_.empty() ? id_ : name_;
3017 - (uint32_t) compareBySection:(NSArray *)sections {
3018 NSString *section([self section]);
3019 for (size_t i(0), e([sections count]); i != e; ++i) {
3020 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3024 return _not(uint32_t);
3028 @synchronized (database_) {
3029 pkgProblemResolver *resolver = [database_ resolver];
3030 resolver->Clear(iterator_);
3032 pkgCacheFile &cache([database_ cache]);
3033 cache->SetReInstall(iterator_, false);
3034 cache->MarkKeep(iterator_, false);
3038 @synchronized (database_) {
3039 pkgProblemResolver *resolver = [database_ resolver];
3040 resolver->Clear(iterator_);
3041 resolver->Protect(iterator_);
3043 pkgCacheFile &cache([database_ cache]);
3044 cache->SetReInstall(iterator_, false);
3045 cache->MarkInstall(iterator_, false);
3047 pkgDepCache::StateCache &state((*cache)[iterator_]);
3048 if (!state.Install())
3049 cache->SetReInstall(iterator_, true);
3053 @synchronized (database_) {
3054 pkgProblemResolver *resolver = [database_ resolver];
3055 resolver->Clear(iterator_);
3056 resolver->Remove(iterator_);
3057 resolver->Protect(iterator_);
3059 pkgCacheFile &cache([database_ cache]);
3060 cache->SetReInstall(iterator_, false);
3061 cache->MarkDelete(iterator_, true);
3064 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3065 _profile(Package$isUnfilteredAndSearchedForBy)
3068 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3069 value &= [self unfiltered];
3072 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3073 value &= [self matches:query];
3080 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3081 if ([search length] == 0)
3084 _profile(Package$isUnfilteredAndSelectedForBy)
3087 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3088 value &= [self unfiltered];
3091 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3092 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3099 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3100 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3103 - (bool) isVisibleInSection:(NSString *)name {
3104 NSString *section([self section]);
3108 section == nil && [name length] == 0 ||
3109 [name isEqualToString:section]
3110 ) && [self visible];
3113 - (bool) isVisibleInSource:(Source *)source {
3114 return [self source] == source && [self visible];
3119 /* Section Class {{{ */
3120 @interface Section : NSObject {
3125 _H<NSString> localized_;
3128 - (NSComparisonResult) compareByLocalized:(Section *)section;
3129 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3130 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3131 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3132 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3133 - (NSString *) name;
3140 - (void) addToCount;
3142 - (void) setCount:(size_t)count;
3143 - (NSString *) localized;
3147 @implementation Section
3149 - (NSComparisonResult) compareByLocalized:(Section *)section {
3150 NSString *lhs(localized_);
3151 NSString *rhs([section localized]);
3153 /*if ([lhs length] != 0 && [rhs length] != 0) {
3154 unichar lhc = [lhs characterAtIndex:0];
3155 unichar rhc = [rhs characterAtIndex:0];
3157 if (isalpha(lhc) && !isalpha(rhc))
3158 return NSOrderedAscending;
3159 else if (!isalpha(lhc) && isalpha(rhc))
3160 return NSOrderedDescending;
3163 return [lhs compare:rhs options:LaxCompareOptions_];
3166 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3167 if ((self = [self initWithName:name localize:NO]) != nil) {
3168 if (localized != nil)
3169 localized_ = localized;
3173 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3174 return [self initWithName:name row:0 localize:localize];
3177 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3178 if ((self = [super init]) != nil) {
3183 localized_ = LocalizeSection(name_);
3187 /* XXX: localize the index thingees */
3188 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3189 if ((self = [super init]) != nil) {
3190 name_ = [NSString stringWithCharacters:&index length:1];
3196 - (NSString *) name {
3216 - (void) addToCount {
3220 - (void) setCount:(size_t)count {
3224 - (NSString *) localized {
3231 class CydiaLogCleaner :
3232 public pkgArchiveCleaner
3235 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3240 /* Database Implementation {{{ */
3241 @implementation Database
3243 + (Database *) sharedInstance {
3244 static _H<Database> instance;
3245 if (instance == nil)
3246 instance = [[[Database alloc] init] autorelease];
3254 - (void) releasePackages {
3255 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3256 CFArrayRemoveAllValues(packages_);
3260 // XXX: actually implement this thing
3262 [self releasePackages];
3263 apr_pool_destroy(pool_);
3264 NSRecycleZone(zone_);
3268 - (void) _readCydia:(NSNumber *)fd {
3269 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3270 std::istream is(&ib);
3273 static Pcre finish_r("^finish:([^:]*)$");
3275 while (std::getline(is, line)) {
3276 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3278 const char *data(line.c_str());
3279 size_t size = line.size();
3280 lprintf("C:%s\n", data);
3282 if (finish_r(data, size)) {
3283 NSString *finish = finish_r[1];
3284 int index = [Finishes_ indexOfObject:finish];
3285 if (index != INT_MAX && index > Finish_)
3295 - (void) _readStatus:(NSNumber *)fd {
3296 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3297 std::istream is(&ib);
3300 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3301 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3303 while (std::getline(is, line)) {
3304 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3306 const char *data(line.c_str());
3307 size_t size(line.size());
3308 lprintf("S:%s\n", data);
3310 if (conffile_r(data, size)) {
3311 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3312 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3313 } else if (strncmp(data, "status: ", 8) == 0) {
3314 // status: <package>: {unpacked,half-configured,installed}
3315 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3316 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3317 } else if (strncmp(data, "processing: ", 12) == 0) {
3318 // processing: configure: config-test
3319 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3320 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3321 } else if (pmstatus_r(data, size)) {
3322 std::string type([pmstatus_r[1] UTF8String]);
3324 NSString *package = pmstatus_r[2];
3325 if ([package isEqualToString:@"dpkg-exec"])
3328 float percent([pmstatus_r[3] floatValue]);
3329 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3331 NSString *string = pmstatus_r[4];
3333 if (type == "pmerror") {
3334 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3335 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3336 } else if (type == "pmstatus") {
3337 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3338 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3339 } else if (type == "pmconffile")
3340 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3342 lprintf("E:unknown pmstatus\n");
3344 lprintf("E:unknown status\n");
3352 - (void) _readOutput:(NSNumber *)fd {
3353 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3354 std::istream is(&ib);
3357 while (std::getline(is, line)) {
3358 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3360 lprintf("O:%s\n", line.c_str());
3362 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3363 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3375 - (Package *) packageWithName:(NSString *)name {
3378 @synchronized (self) {
3379 if (static_cast<pkgDepCache *>(cache_) == NULL)
3381 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3382 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3386 if ((self = [super init]) != nil) {
3393 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3394 apr_pool_create(&pool_, NULL);
3396 size_t capacity(MetaFile_->active_);
3402 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3403 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3407 _assert(pipe(fds) != -1);
3410 _config->Set("APT::Keep-Fds::", cydiafd_);
3411 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3414 detachNewThreadSelector:@selector(_readCydia:)
3416 withObject:[NSNumber numberWithInt:fds[0]]
3419 _assert(pipe(fds) != -1);
3423 detachNewThreadSelector:@selector(_readStatus:)
3425 withObject:[NSNumber numberWithInt:fds[0]]
3428 _assert(pipe(fds) != -1);
3429 _assert(dup2(fds[0], 0) != -1);
3430 _assert(close(fds[0]) != -1);
3432 input_ = fdopen(fds[1], "a");
3434 _assert(pipe(fds) != -1);
3435 _assert(dup2(fds[1], 1) != -1);
3436 _assert(close(fds[1]) != -1);
3439 detachNewThreadSelector:@selector(_readOutput:)
3441 withObject:[NSNumber numberWithInt:fds[0]]
3446 - (pkgCacheFile &) cache {
3450 - (pkgDepCache::Policy *) policy {
3454 - (pkgRecords *) records {
3458 - (pkgProblemResolver *) resolver {
3462 - (pkgAcquire &) fetcher {
3466 - (pkgSourceList &) list {
3470 - (NSArray *) packages {
3471 return (NSArray *) packages_;
3474 - (NSArray *) sources {
3478 - (Source *) sourceWithKey:(NSString *)key {
3479 for (Source *source in [self sources]) {
3480 if ([[source key] isEqualToString:key])
3485 - (bool) popErrorWithTitle:(NSString *)title {
3488 while (!_error->empty()) {
3490 bool warning(!_error->PopMessage(error));
3495 size_t size(error.size());
3496 if (size == 0 || error[size - 1] != '\n')
3498 error.resize(size - 1);
3501 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3503 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3504 if (warning && no_pubkey(error.c_str()))
3507 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3513 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3514 return [self popErrorWithTitle:title] || !success;
3517 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3518 @synchronized (self) {
3521 [self releasePackages];
3524 [sourceList_ removeAllObjects];
3544 apr_pool_clear(pool_);
3546 NSRecycleZone(zone_);
3547 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3549 int chk(creat("/tmp/cydia.chk", 0644));
3553 if (invocation != nil)
3554 [invocation invoke];
3556 NSString *title(UCLocalize("DATABASE"));
3558 list_ = new pkgSourceList();
3559 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3562 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3563 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3564 [sourceList_ addObject:object];
3568 OpProgress progress;
3570 if (!cache_.Open(progress, true)) {
3571 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3572 while (!_error->empty()) {
3574 bool warning(!_error->PopMessage(error));
3576 lprintf("cache_.Open():[%s]\n", error.c_str());
3578 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3582 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3583 repair = @selector(configure);
3584 //else if (error == "The package lists or status file could not be parsed or opened.")
3585 // repair = @selector(update);
3586 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3587 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3588 // else if (error == "Malformed Status line")
3589 // else if (error == "The list of sources could not be read.")
3591 if (repair != NULL) {
3593 [delegate_ repairWithSelector:repair];
3602 unlink("/tmp/cydia.chk");
3604 now_ = [[NSDate date] timeIntervalSince1970];
3606 policy_ = new pkgDepCache::Policy();
3607 records_ = new pkgRecords(cache_);
3608 resolver_ = new pkgProblemResolver(cache_);
3609 fetcher_ = new pkgAcquire(&status_);
3612 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3613 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3617 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3620 if (cache_->BrokenCount() != 0) {
3621 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3624 if (cache_->BrokenCount() != 0) {
3625 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3629 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3633 for (Source *object in (id) sourceList_) {
3634 metaIndex *source([object metaIndex]);
3635 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3636 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3637 // XXX: this could be more intelligent
3638 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3639 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3641 sourceMap_[cached->ID] = object;
3646 /*std::vector<Package *> packages;
3647 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3652 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3653 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3654 //packages.push_back(package);
3655 CFArrayAppendValue(packages_, CFRetain(package));
3659 /*if (packages.empty())
3660 packages_ = [[NSArray alloc] init];
3662 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3665 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3666 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3667 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3675 /*if (!packages.empty())
3676 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3677 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3679 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3681 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3683 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3687 size_t count(CFArrayGetCount(packages_));
3688 MetaFile_->active_ = count;
3690 for (size_t index(0); index != count; ++index)
3691 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3698 @synchronized (self) {
3700 resolver_ = new pkgProblemResolver(cache_);
3702 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3703 if (!cache_[iterator].Keep())
3704 cache_->MarkKeep(iterator, false);
3705 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3706 cache_->SetReInstall(iterator, false);
3709 - (void) configure {
3710 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3712 system([dpkg UTF8String]);
3717 @synchronized (self) {
3718 // XXX: I don't remember this condition
3723 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3725 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3727 if ([self popErrorWithTitle:title])
3731 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3733 CydiaLogCleaner cleaner;
3734 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3741 fetcher_->Shutdown();
3743 pkgRecords records(cache_);
3745 lock_ = new FileFd();
3746 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3748 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3750 if ([self popErrorWithTitle:title])
3754 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3757 manager_ = (_system->CreatePM(cache_));
3758 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3765 bool substrate(RestartSubstrate_);
3766 RestartSubstrate_ = false;
3768 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3770 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3772 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3774 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3775 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3778 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3780 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3782 [self popErrorWithTitle:title];
3786 bool failed = false;
3787 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3788 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3790 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3793 std::string uri = (*item)->DescURI();
3794 std::string error = (*item)->ErrorText;
3796 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3799 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3800 [delegate_ addProgressEventOnMainThread:event forTask:title];
3803 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3811 RestartSubstrate_ = true;
3814 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3815 if ([self popErrorWithTitle:title])
3818 if (result == pkgPackageManager::Failed) {
3823 if (result != pkgPackageManager::Completed) {
3828 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3830 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3832 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3833 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3836 if (![before isEqualToArray:after])
3841 NSString *title(UCLocalize("UPGRADE"));
3842 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3848 [self updateWithStatus:status_];
3851 - (void) updateWithStatus:(Status &)status {
3852 NSString *title(UCLocalize("REFRESHING_DATA"));
3855 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3859 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3860 if ([self popErrorWithTitle:title])
3863 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3865 bool success(ListUpdate(status, list, PulseInterval_));
3866 if (status.WasCancelled())
3869 [self popErrorWithTitle:title forOperation:success];
3870 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3874 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3877 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3878 delegate_ = delegate;
3881 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3882 progress_ = delegate;
3883 status_.setDelegate(delegate);
3886 - (NSObject<ProgressDelegate> *) progressDelegate {
3890 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3891 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3892 return i == sourceMap_.end() ? nil : i->second;
3895 - (NSString *) mappedSectionForPointer:(const char *)section {
3896 _H<NSString> *mapped;
3898 _profile(Database$mappedSectionForPointer$Cache)
3899 mapped = §ions_[section];
3902 if (*mapped == NULL) {
3903 size_t length(strlen(section));
3904 char spaced[length + 1];
3906 _profile(Database$mappedSectionForPointer$Replace)
3907 for (size_t index(0); index != length; ++index)
3908 spaced[index] = section[index] == '_' ? ' ' : section[index];
3909 spaced[length] = '\0';
3914 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3915 string = [NSString stringWithUTF8String:spaced];
3918 _profile(Database$mappedSectionForPointer$Map)
3919 string = [SectionMap_ objectForKey:string] ?: string;
3929 static _H<NSMutableSet> Diversions_;
3931 @interface Diversion : NSObject {
3934 _H<NSString> format_;
3939 @implementation Diversion
3941 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3942 if ((self = [super init]) != nil) {
3943 pattern_ = [from UTF8String];
3949 - (NSString *) divert:(NSString *)url {
3950 return !pattern_(url) ? nil : pattern_->*format_;
3953 + (NSURL *) divertURL:(NSURL *)url {
3955 NSString *href([url absoluteString]);
3957 for (Diversion *diversion in (id) Diversions_)
3958 if (NSString *diverted = [diversion divert:href]) {
3960 NSLog(@"div: %@", diverted);
3962 url = [NSURL URLWithString:diverted];
3969 - (NSString *) key {
3973 - (NSUInteger) hash {
3977 - (BOOL) isEqual:(Diversion *)object {
3978 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3983 @interface CydiaObject : NSObject {
3984 _H<CyteWebViewController> indirect_;
3985 _transient id delegate_;
3988 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3994 @interface CydiaWebViewController : CyteWebViewController {
3995 _H<CydiaObject> cydia_;
3998 + (void) addDiversion:(Diversion *)diversion;
3999 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4000 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4001 - (void) setDelegate:(id)delegate;
4005 /* Web Scripting {{{ */
4006 @implementation CydiaObject
4008 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4009 if ((self = [super init]) != nil) {
4010 indirect_ = (CyteWebViewController *) indirect;
4014 - (void) setDelegate:(id)delegate {
4015 delegate_ = delegate;
4018 + (NSArray *) _attributeKeys {
4019 return [NSArray arrayWithObjects:
4022 @"coreFoundationVersionNumber",
4039 - (NSArray *) attributeKeys {
4040 return [[self class] _attributeKeys];
4043 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4044 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4047 - (NSString *) version {
4051 - (NSString *) build {
4055 - (NSString *) coreFoundationVersionNumber {
4056 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4059 - (NSString *) device {
4060 return [[UIDevice currentDevice] uniqueIdentifier];
4063 - (NSString *) firmware {
4064 return [[UIDevice currentDevice] systemVersion];
4067 - (NSString *) hostname {
4068 return [[UIDevice currentDevice] name];
4071 - (NSString *) idiom {
4072 return (id) Idiom_ ?: [NSNull null];
4075 - (NSString *) mcc {
4076 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4077 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4081 - (NSString *) mnc {
4082 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4083 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4087 - (NSString *) operator {
4088 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4089 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4093 - (NSString *) bbsnum {
4094 return (id) BBSNum_ ?: [NSNull null];
4097 - (NSString *) ecid {
4098 return (id) ChipID_ ?: [NSNull null];
4101 - (NSString *) serial {
4102 return SerialNumber_;
4105 - (NSString *) role {
4106 return (id) Role_ ?: [NSNull null];
4109 - (NSString *) model {
4110 return [NSString stringWithUTF8String:Machine_];
4113 - (NSString *) token {
4114 return (id) Token_ ?: [NSNull null];
4117 + (NSString *) webScriptNameForSelector:(SEL)selector {
4119 else if (selector == @selector(addBridgedHost:))
4120 return @"addBridgedHost";
4121 else if (selector == @selector(addInsecureHost:))
4122 return @"addInsecureHost";
4123 else if (selector == @selector(addInternalRedirect::))
4124 return @"addInternalRedirect";
4125 else if (selector == @selector(addPipelinedHost:scheme:))
4126 return @"addPipelinedHost";
4127 else if (selector == @selector(addSource:::))
4128 return @"addSource";
4129 else if (selector == @selector(addTokenHost:))
4130 return @"addTokenHost";
4131 else if (selector == @selector(addTrivialSource:))
4132 return @"addTrivialSource";
4133 else if (selector == @selector(close))
4135 else if (selector == @selector(du:))
4137 else if (selector == @selector(stringWithFormat:arguments:))
4139 else if (selector == @selector(getAllSources))
4140 return @"getAllSourcs";
4141 else if (selector == @selector(getKernelNumber:))
4142 return @"getKernelNumber";
4143 else if (selector == @selector(getKernelString:))
4144 return @"getKernelString";
4145 else if (selector == @selector(getInstalledPackages))
4146 return @"getInstalledPackages";
4147 else if (selector == @selector(getIORegistryEntry::))
4148 return @"getIORegistryEntry";
4149 else if (selector == @selector(getLocaleIdentifier))
4150 return @"getLocaleIdentifier";
4151 else if (selector == @selector(getPreferredLanguages))
4152 return @"getPreferredLanguages";
4153 else if (selector == @selector(getPackageById:))
4154 return @"getPackageById";
4155 else if (selector == @selector(getMetadataKeys))
4156 return @"getMetadataKeys";
4157 else if (selector == @selector(getMetadataValue:))
4158 return @"getMetadataValue";
4159 else if (selector == @selector(getSessionValue:))
4160 return @"getSessionValue";
4161 else if (selector == @selector(installPackages:))
4162 return @"installPackages";
4163 else if (selector == @selector(isReachable:))
4164 return @"isReachable";
4165 else if (selector == @selector(localizedStringForKey:value:table:))
4167 else if (selector == @selector(popViewController:))
4168 return @"popViewController";
4169 else if (selector == @selector(refreshSources))
4170 return @"refreshSources";
4171 else if (selector == @selector(removeButton))
4172 return @"removeButton";
4173 else if (selector == @selector(saveConfig))
4174 return @"saveConfig";
4175 else if (selector == @selector(setMetadataValue::))
4176 return @"setMetadataValue";
4177 else if (selector == @selector(setSessionValue::))
4178 return @"setSessionValue";
4179 else if (selector == @selector(setShowPromoted:))
4180 return @"setShowPromoted";
4181 else if (selector == @selector(substitutePackageNames:))
4182 return @"substitutePackageNames";
4183 else if (selector == @selector(scrollToBottom:))
4184 return @"scrollToBottom";
4185 else if (selector == @selector(setAllowsNavigationAction:))
4186 return @"setAllowsNavigationAction";
4187 else if (selector == @selector(setBadgeValue:))
4188 return @"setBadgeValue";
4189 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4190 return @"setButtonImage";
4191 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4192 return @"setButtonTitle";
4193 else if (selector == @selector(setHidesBackButton:))
4194 return @"setHidesBackButton";
4195 else if (selector == @selector(setHidesNavigationBar:))
4196 return @"setHidesNavigationBar";
4197 else if (selector == @selector(setNavigationBarStyle:))
4198 return @"setNavigationBarStyle";
4199 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4200 return @"setNavigationBarTintColor";
4201 else if (selector == @selector(setPasteboardString:))
4202 return @"setPasteboardString";
4203 else if (selector == @selector(setPasteboardURL:))
4204 return @"setPasteboardURL";
4205 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4206 return @"setScrollAlwaysBounceVertical";
4207 else if (selector == @selector(setScrollIndicatorStyle:))
4208 return @"setScrollIndicatorStyle";
4209 else if (selector == @selector(setToken:))
4211 else if (selector == @selector(setViewportWidth:))
4212 return @"setViewportWidth";
4213 else if (selector == @selector(statfs:))
4215 else if (selector == @selector(supports:))
4217 else if (selector == @selector(unload))
4223 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4224 return [self webScriptNameForSelector:selector] == nil;
4227 - (BOOL) supports:(NSString *)feature {
4228 return [feature isEqualToString:@"window.open"];
4232 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4235 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4236 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4239 - (void) setScrollIndicatorStyle:(NSString *)style {
4240 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4243 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4244 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4247 - (NSNumber *) getKernelNumber:(NSString *)name {
4248 const char *string([name UTF8String]);
4251 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4252 return (id) [NSNull null];
4254 if (size != sizeof(int))
4255 return (id) [NSNull null];
4258 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4259 return (id) [NSNull null];
4261 return [NSNumber numberWithInt:value];
4264 - (NSString *) getKernelString:(NSString *)name {
4265 const char *string([name UTF8String]);
4268 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4269 return (id) [NSNull null];
4271 char value[size + 1];
4272 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4273 return (id) [NSNull null];
4275 // XXX: just in case you request something ludicrous
4278 return [NSString stringWithCString:value];
4281 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4282 NSObject *value(CYIOGetValue([path UTF8String], entry));
4285 if ([value isKindOfClass:[NSData class]])
4286 value = CYHex((NSData *) value);
4291 - (NSArray *) getMetadataKeys {
4292 @synchronized (Values_) {
4293 return [Values_ allKeys];
4296 - (void) _setShowPromoted:(NSNumber *)value {
4297 [Metadata_ setObject:value forKey:@"ShowPromoted"];
4301 - (void) setShowPromoted:(NSNumber *)value {
4302 [self performSelectorOnMainThread:@selector(_setShowPromoted:) withObject:value waitUntilDone:NO];
4305 - (id) getMetadataValue:(NSString *)key {
4306 @synchronized (Values_) {
4307 return [Values_ objectForKey:key];
4310 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4311 @synchronized (Values_) {
4312 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4313 [Values_ removeObjectForKey:key];
4315 [Values_ setObject:value forKey:key];
4317 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4320 - (id) getSessionValue:(NSString *)key {
4321 @synchronized (SessionData_) {
4322 return [SessionData_ objectForKey:key];
4325 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4326 @synchronized (SessionData_) {
4327 if (value == (id) [WebUndefined undefined])
4328 [SessionData_ removeObjectForKey:key];
4330 [SessionData_ setObject:value forKey:key];
4333 - (void) addBridgedHost:(NSString *)host {
4334 @synchronized (HostConfig_) {
4335 [BridgedHosts_ addObject:host];
4338 - (void) addInsecureHost:(NSString *)host {
4339 @synchronized (HostConfig_) {
4340 [InsecureHosts_ addObject:host];
4343 - (void) addTokenHost:(NSString *)host {
4344 @synchronized (HostConfig_) {
4345 [TokenHosts_ addObject:host];
4348 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4349 @synchronized (HostConfig_) {
4350 if (scheme != (id) [WebUndefined undefined])
4351 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4353 [PipelinedHosts_ addObject:host];
4356 - (void) popViewController:(NSNumber *)value {
4357 if (value == (id) [WebUndefined undefined])
4358 value = [NSNumber numberWithBool:YES];
4359 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4362 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4363 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4365 for (NSString *section in sections)
4366 [array addObject:section];
4368 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4371 distribution, @"Distribution",
4373 nil] waitUntilDone:NO];
4376 - (void) addTrivialSource:(NSString *)href {
4377 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4380 - (void) refreshSources {
4381 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4384 - (void) saveConfig {
4385 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4388 - (NSArray *) getAllSources {
4389 return [[Database sharedInstance] sources];
4392 - (NSArray *) getInstalledPackages {
4393 Database *database([Database sharedInstance]);
4394 @synchronized (database) {
4395 NSArray *packages([database packages]);
4396 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4397 for (Package *package in packages)
4398 if (![package uninstalled])
4399 [installed addObject:package];
4403 - (Package *) getPackageById:(NSString *)id {
4404 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4408 return (Package *) [NSNull null];
4411 - (NSString *) getLocaleIdentifier {
4412 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4415 - (NSArray *) getPreferredLanguages {
4419 - (NSArray *) statfs:(NSString *)path {
4422 if (path == nil || statfs([path UTF8String], &stat) == -1)
4425 return [NSArray arrayWithObjects:
4426 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4427 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4428 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4432 - (NSNumber *) du:(NSString *)path {
4433 NSNumber *value(nil);
4436 _assert(pipe(fds) != -1);
4438 pid_t pid(ExecFork());
4440 _assert(dup2(fds[1], 1) != -1);
4441 _assert(close(fds[0]) != -1);
4442 _assert(close(fds[1]) != -1);
4443 /* XXX: this should probably not use du */
4444 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4449 _assert(close(fds[1]) != -1);
4451 if (FILE *du = fdopen(fds[0], "r")) {
4453 while (fgets(line, sizeof(line), du) != NULL) {
4454 size_t length(strlen(line));
4455 while (length != 0 && line[length - 1] == '\n')
4456 line[--length] = '\0';
4457 if (char *tab = strchr(line, '\t')) {
4459 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4464 } else _assert(close(fds[0]));
4472 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4475 - (NSNumber *) isReachable:(NSString *)name {
4476 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4479 - (void) installPackages:(NSArray *)packages {
4480 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4483 - (NSString *) substitutePackageNames:(NSString *)message {
4484 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4485 for (size_t i(0), e([words count]); i != e; ++i) {
4486 NSString *word([words objectAtIndex:i]);
4487 if (Package *package = [[Database sharedInstance] packageWithName:word])
4488 [words replaceObjectAtIndex:i withObject:[package name]];
4491 return [words componentsJoinedByString:@" "];
4494 - (void) removeButton {
4495 [indirect_ removeButton];
4498 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4499 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4502 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4503 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4506 - (void) setBadgeValue:(id)value {
4507 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4510 - (void) setAllowsNavigationAction:(NSString *)value {
4511 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4514 - (void) setHidesBackButton:(NSString *)value {
4515 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4518 - (void) setHidesNavigationBar:(NSString *)value {
4519 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4522 - (void) setNavigationBarStyle:(NSString *)value {
4523 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4526 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4527 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4528 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4529 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4532 - (void) setPasteboardString:(NSString *)value {
4533 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4536 - (void) setPasteboardURL:(NSString *)value {
4537 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4540 - (void) _setToken:(NSString *)token {
4544 [Metadata_ removeObjectForKey:@"Token"];
4546 [Metadata_ setObject:Token_ forKey:@"Token"];
4551 - (void) setToken:(NSString *)token {
4552 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4555 - (void) scrollToBottom:(NSNumber *)animated {
4556 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4559 - (void) setViewportWidth:(float)width {
4560 [indirect_ setViewportWidthOnMainThread:width];
4563 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4564 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4565 unsigned count([arguments count]);
4567 for (unsigned i(0); i != count; ++i)
4568 values[i] = [arguments objectAtIndex:i];
4569 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4572 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4573 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4575 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4577 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4583 @interface NSURL (CydiaSecure)
4586 @implementation NSURL (CydiaSecure)
4588 - (bool) isCydiaSecure {
4589 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4592 @synchronized (HostConfig_) {
4593 if ([InsecureHosts_ containsObject:[self host]])
4602 /* Cydia Browser Controller {{{ */
4603 @implementation CydiaWebViewController
4605 - (NSURL *) navigationURL {
4606 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4609 + (void) _initialize {
4610 [super _initialize];
4612 Diversions_ = [NSMutableSet setWithCapacity:0];
4615 + (void) addDiversion:(Diversion *)diversion {
4616 [Diversions_ addObject:diversion];
4619 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4620 [super webView:view didClearWindowObject:window forFrame:frame];
4621 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4624 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4625 WebDataSource *source([frame dataSource]);
4626 NSURLResponse *response([source response]);
4627 NSURL *url([response URL]);
4628 NSString *scheme([[url scheme] lowercaseString]);
4630 bool bridged(false);
4632 @synchronized (HostConfig_) {
4633 if ([scheme isEqualToString:@"file"])
4635 else if ([scheme isEqualToString:@"https"])
4636 if ([BridgedHosts_ containsObject:[url host]])
4641 [window setValue:cydia forKey:@"cydia"];
4644 - (void) _setupMail:(MFMailComposeViewController *)controller {
4645 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4647 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4648 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4651 - (NSURL *) URLWithURL:(NSURL *)url {
4652 return [Diversion divertURL:url];
4655 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4656 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4659 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4660 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4662 NSURL *url([copy URL]);
4663 NSString *href([url absoluteString]);
4664 NSString *host([url host]);
4666 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4667 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4668 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4669 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4672 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4673 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4675 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4679 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4680 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4681 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4682 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4687 @synchronized (HostConfig_) {
4688 bridged = [BridgedHosts_ containsObject:host];
4689 token = [TokenHosts_ containsObject:host];
4692 if ([url isCydiaSecure]) {
4694 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4695 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4697 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4698 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4705 - (void) setDelegate:(id)delegate {
4706 [super setDelegate:delegate];
4707 [cydia_ setDelegate:delegate];
4710 - (NSString *) applicationNameForUserAgent {
4715 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4716 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4722 @interface AppCacheController : CydiaWebViewController {
4727 @implementation AppCacheController
4729 - (void) didReceiveMemoryWarning {
4730 // XXX: this doesn't work
4733 - (bool) retainsNetworkActivityIndicator {
4741 @interface NSObject (CydiaScript)
4742 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4745 @implementation NSObject (CydiaScript)
4747 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4753 @implementation NSArray (CydiaScript)
4755 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4756 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4757 for (size_t i(0), e([self count]); i != e; ++i)
4758 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4764 @implementation NSDictionary (CydiaScript)
4766 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4767 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4769 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4776 /* Confirmation Controller {{{ */
4777 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4778 if (!iterator.end())
4779 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4780 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4782 pkgCache::PkgIterator package(dep.TargetPkg());
4785 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4792 @protocol ConfirmationControllerDelegate
4793 - (void) cancelAndClear:(bool)clear;
4794 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4798 @interface ConfirmationController : CydiaWebViewController {
4799 _transient Database *database_;
4801 _H<UIAlertView> essential_;
4803 _H<NSDictionary> changes_;
4804 _H<NSMutableArray> issues_;
4805 _H<NSDictionary> sizes_;
4810 - (id) initWithDatabase:(Database *)database;
4814 @implementation ConfirmationController
4818 RestartSubstrate_ = true;
4819 [delegate_ confirmWithNavigationController:[self navigationController]];
4822 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4823 NSString *context([alert context]);
4825 if ([context isEqualToString:@"remove"]) {
4826 if (button == [alert cancelButtonIndex])
4827 [self dismissModalViewControllerAnimated:YES];
4828 else if (button == [alert firstOtherButtonIndex]) {
4829 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
4832 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4833 } else if ([context isEqualToString:@"unable"]) {
4834 [self dismissModalViewControllerAnimated:YES];
4835 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4837 [super alertView:alert clickedButtonAtIndex:button];
4841 - (void) _doContinue {
4842 [delegate_ cancelAndClear:NO];
4843 [self dismissModalViewControllerAnimated:YES];
4846 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4847 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4851 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4852 [super webView:view didClearWindowObject:window forFrame:frame];
4854 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4855 (id) changes_, @"changes",
4856 (id) issues_, @"issues",
4857 (id) sizes_, @"sizes",
4859 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4862 - (id) initWithDatabase:(Database *)database {
4863 if ((self = [super init]) != nil) {
4864 database_ = database;
4866 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4867 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4868 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4869 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4870 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4874 pkgCacheFile &cache([database_ cache]);
4875 NSArray *packages([database_ packages]);
4876 pkgDepCache::Policy *policy([database_ policy]);
4878 issues_ = [NSMutableArray arrayWithCapacity:4];
4880 for (Package *package in packages) {
4881 pkgCache::PkgIterator iterator([package iterator]);
4882 NSString *name([package id]);
4884 if ([package broken]) {
4885 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4887 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4889 reasons, @"reasons",
4892 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4896 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4897 pkgCache::DepIterator start;
4898 pkgCache::DepIterator end;
4899 dep.GlobOr(start, end); // ++dep
4901 if (!cache->IsImportantDep(end))
4903 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4906 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4908 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4909 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4910 clauses, @"clauses",
4914 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4916 pkgCache::PkgIterator target(start.TargetPkg());
4917 if (target->ProvidesList != 0)
4918 reason = @"missing";
4920 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4922 reason = @"installed";
4923 installed = [NSString stringWithUTF8String:ver.VerStr()];
4924 } else if (!cache[target].CandidateVerIter(cache).end())
4925 reason = @"uninstalled";
4926 else if (target->ProvidesList == 0)
4927 reason = @"uninstallable";
4929 reason = @"virtual";
4932 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4933 [NSString stringWithUTF8String:start.CompType()], @"operator",
4934 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4937 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4938 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4939 version, @"version",
4941 installed, @"installed",
4944 // yes, seriously. (wtf?)
4952 pkgDepCache::StateCache &state(cache[iterator]);
4954 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4956 if (state.NewInstall())
4957 [installs addObject:name];
4958 // XXX: else if (state.Install())
4959 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4960 [reinstalls addObject:name];
4961 // XXX: move before previous if
4962 else if (state.Upgrade())
4963 [upgrades addObject:name];
4964 else if (state.Downgrade())
4965 [downgrades addObject:name];
4966 else if (!state.Delete())
4967 // XXX: _assert(state.Keep());
4969 else if (special_r(name))
4970 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4971 [NSNull null], @"package",
4972 [NSArray arrayWithObjects:
4973 [NSDictionary dictionaryWithObjectsAndKeys:
4974 @"Conflicts", @"relationship",
4975 [NSArray arrayWithObjects:
4976 [NSDictionary dictionaryWithObjectsAndKeys:
4978 [NSNull null], @"version",
4979 @"installed", @"reason",
4986 if ([package essential])
4988 [removes addObject:name];
4991 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4992 substrate_ |= DepSubstrate(iterator.CurrentVer());
4997 else if (Advanced_) {
4998 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5000 essential_ = [[[UIAlertView alloc]
5001 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5002 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5004 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5006 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5010 [essential_ setContext:@"remove"];
5011 [essential_ setNumberOfRows:2];
5013 essential_ = [[[UIAlertView alloc]
5014 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5015 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5017 cancelButtonTitle:UCLocalize("OKAY")
5018 otherButtonTitles:nil
5021 [essential_ setContext:@"unable"];
5024 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5025 installs, @"installs",
5026 reinstalls, @"reinstalls",
5027 upgrades, @"upgrades",
5028 downgrades, @"downgrades",
5029 removes, @"removes",
5032 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5033 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5034 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5037 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5041 - (UIBarButtonItem *) leftButton {
5042 return [[[UIBarButtonItem alloc]
5043 initWithTitle:UCLocalize("CANCEL")
5044 style:UIBarButtonItemStylePlain
5046 action:@selector(cancelButtonClicked)
5051 - (void) applyRightButton {
5052 if ([issues_ count] == 0 && ![self isLoading])
5053 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5054 initWithTitle:UCLocalize("CONFIRM")
5055 style:UIBarButtonItemStyleDone
5057 action:@selector(confirmButtonClicked)
5060 [[self navigationItem] setRightBarButtonItem:nil];
5064 - (void) cancelButtonClicked {
5065 [delegate_ cancelAndClear:YES];
5066 [self dismissModalViewControllerAnimated:YES];
5070 - (void) confirmButtonClicked {
5071 if (essential_ != nil)
5081 /* Progress Data {{{ */
5082 @interface CydiaProgressData : NSObject {
5083 _transient id delegate_;
5092 _H<NSMutableArray> events_;
5093 _H<NSString> title_;
5095 _H<NSString> status_;
5096 _H<NSString> finish_;
5101 @implementation CydiaProgressData
5103 + (NSArray *) _attributeKeys {
5104 return [NSArray arrayWithObjects:
5116 - (NSArray *) attributeKeys {
5117 return [[self class] _attributeKeys];
5120 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5121 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5125 if ((self = [super init]) != nil) {
5126 events_ = [NSMutableArray arrayWithCapacity:32];
5130 - (void) setDelegate:(id)delegate {
5131 delegate_ = delegate;
5134 - (void) setPercent:(float)value {
5138 - (NSNumber *) percent {
5139 return [NSNumber numberWithFloat:percent_];
5142 - (void) setCurrent:(float)value {
5146 - (NSNumber *) current {
5147 return [NSNumber numberWithFloat:current_];
5150 - (void) setTotal:(float)value {
5154 - (NSNumber *) total {
5155 return [NSNumber numberWithFloat:total_];
5158 - (void) setSpeed:(float)value {
5162 - (NSNumber *) speed {
5163 return [NSNumber numberWithFloat:speed_];
5166 - (NSArray *) events {
5170 - (void) removeAllEvents {
5171 [events_ removeAllObjects];
5174 - (void) addEvent:(CydiaProgressEvent *)event {
5175 [events_ addObject:event];
5178 - (void) setTitle:(NSString *)text {
5182 - (NSString *) title {
5186 - (void) setFinish:(NSString *)text {
5190 - (NSString *) finish {
5191 return (id) finish_ ?: [NSNull null];
5194 - (void) setRunning:(bool)running {
5198 - (NSNumber *) running {
5199 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5204 /* Progress Controller {{{ */
5205 @interface ProgressController : CydiaWebViewController <
5208 _transient Database *database_;
5209 _H<CydiaProgressData, 1> progress_;
5213 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5215 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5217 - (void) setTitle:(NSString *)title;
5218 - (void) setCancellable:(bool)cancellable;
5222 @implementation ProgressController
5225 [database_ setProgressDelegate:nil];
5229 - (UIBarButtonItem *) leftButton {
5230 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5231 initWithTitle:UCLocalize("CANCEL")
5232 style:UIBarButtonItemStylePlain
5234 action:@selector(cancel)
5235 ] autorelease] : nil;
5238 - (void) updateCancel {
5239 [super applyLeftButton];
5242 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5243 if ((self = [super init]) != nil) {
5244 database_ = database;
5245 delegate_ = delegate;
5247 [database_ setProgressDelegate:self];
5249 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5250 [progress_ setDelegate:self];
5252 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5254 [scroller_ setBackgroundColor:[UIColor blackColor]];
5256 [[self navigationItem] setHidesBackButton:YES];
5258 [self updateCancel];
5262 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5263 [super webView:view didClearWindowObject:window forFrame:frame];
5264 [window setValue:progress_ forKey:@"cydiaProgress"];
5267 - (void) updateProgress {
5268 [self dispatchEvent:@"CydiaProgressUpdate"];
5271 - (void) viewWillAppear:(BOOL)animated {
5272 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5273 [super viewWillAppear:animated];
5276 - (void) reloadSpringBoard {
5277 pid_t pid(ExecFork());
5279 pid_t pid(ExecFork());
5281 execl("/usr/bin/sbreload", "sbreload", NULL);
5292 system("/usr/bin/killall SpringBoard");
5296 UpdateExternalStatus(0);
5299 [delegate_ saveState];
5303 [delegate_ returnToCydia];
5307 [delegate_ terminateWithSuccess];
5308 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5309 [delegate_ suspendWithAnimation:YES];
5311 [delegate_ suspend];*/
5323 UIProgressHUD *hud([delegate_ addProgressHUD]);
5324 [hud setText:UCLocalize("LOADING")];
5325 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5331 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5332 SBReboot(SBSSpringBoardServerPort());
5334 reboot2(RB_AUTOBOOT);
5341 - (void) setTitle:(NSString *)title {
5342 [progress_ setTitle:title];
5343 [self updateProgress];
5346 - (UIBarButtonItem *) rightButton {
5347 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5348 initWithTitle:UCLocalize("CLOSE")
5349 style:UIBarButtonItemStylePlain
5351 action:@selector(close)
5355 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5356 UpdateExternalStatus(1);
5358 [progress_ setRunning:true];
5359 [self setTitle:title];
5360 // implicit updateProgress
5362 SHA1SumValue notifyconf; {
5364 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5367 MMap mmap(file, MMap::ReadOnly);
5369 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5370 notifyconf = sha1.Result();
5374 SHA1SumValue springlist; {
5376 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5379 MMap mmap(file, MMap::ReadOnly);
5381 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5382 springlist = sha1.Result();
5386 if (invocation != nil) {
5387 [invocation yieldToSelector:@selector(invoke)];
5388 [self setTitle:@"COMPLETE"];
5393 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5396 MMap mmap(file, MMap::ReadOnly);
5398 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5399 if (!(notifyconf == sha1.Result()))
5406 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5409 MMap mmap(file, MMap::ReadOnly);
5411 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5412 if (!(springlist == sha1.Result()))
5418 if (RestartSubstrate_)
5422 RestartSubstrate_ = false;
5425 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5426 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5427 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5428 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5429 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5432 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5434 [progress_ setRunning:false];
5435 [self updateProgress];
5437 [self applyRightButton];
5440 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5441 [progress_ addEvent:event];
5442 [self updateProgress];
5445 - (bool) isProgressCancelled {
5446 return cancel_ == 2;
5451 [self updateCancel];
5454 - (void) setCancellable:(bool)cancellable {
5455 unsigned cancel(cancel_);
5459 else if (cancel_ == 0)
5462 if (cancel != cancel_)
5463 [self updateCancel];
5466 - (void) setProgressCancellable:(NSNumber *)cancellable {
5467 [self setCancellable:[cancellable boolValue]];
5470 - (void) setProgressPercent:(NSNumber *)percent {
5471 [progress_ setPercent:[percent floatValue]];
5472 [self updateProgress];
5475 - (void) setProgressStatus:(NSDictionary *)status {
5476 if (status == nil) {
5477 [progress_ setCurrent:0];
5478 [progress_ setTotal:0];
5479 [progress_ setSpeed:0];
5481 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5483 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5484 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5485 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5488 [self updateProgress];
5494 /* Package Cell {{{ */
5495 @interface PackageCell : CyteTableViewCell <
5496 CyteTableViewCellDelegate
5500 _H<NSString> description_;
5502 _H<NSString> source_;
5504 _H<UIImage> placard_;
5508 - (PackageCell *) init;
5509 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5511 - (void) drawContentRect:(CGRect)rect;
5515 @implementation PackageCell
5517 - (PackageCell *) init {
5518 CGRect frame(CGRectMake(0, 0, 320, 74));
5519 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5520 UIView *content([self contentView]);
5521 CGRect bounds([content bounds]);
5523 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5524 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5525 [content addSubview:content_];
5527 [content_ setDelegate:self];
5528 [content_ setOpaque:YES];
5532 - (NSString *) accessibilityLabel {
5533 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5536 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5537 summarized_ = summary;
5547 [content_ setBackgroundColor:[UIColor whiteColor]];
5551 Source *source = [package source];
5553 icon_ = [package icon];
5555 if (NSString *name = [package name])
5556 name_ = [NSString stringWithString:name];
5558 NSString *description(nil);
5560 if (description == nil && IsWildcat_)
5561 description = [package longDescription];
5562 if (description == nil)
5563 description = [package shortDescription];
5565 if (description != nil)
5566 description_ = [NSString stringWithString:description];
5568 commercial_ = [package isCommercial];
5570 NSString *label = nil;
5571 bool trusted = false;
5573 if (source != nil) {
5574 label = [source label];
5575 trusted = [source trusted];
5576 } else if ([[package id] isEqualToString:@"firmware"])
5577 label = UCLocalize("APPLE");
5579 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5581 NSString *from(label);
5583 NSString *section = [package simpleSection];
5584 if (section != nil && ![section isEqualToString:label]) {
5585 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5586 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5589 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5591 if (NSString *purpose = [package primaryPurpose])
5592 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5597 if (NSString *mode = [package mode]) {
5598 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5599 color = RemovingColor_;
5600 //placard = @"removing";
5602 color = InstallingColor_;
5603 //placard = @"installing";
5606 // XXX: the removing/installing placards are not @2x
5609 color = [UIColor whiteColor];
5611 if ([package installed] != nil)
5612 placard = @"installed";
5617 [content_ setBackgroundColor:color];
5620 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5623 [self setNeedsDisplay];
5624 [content_ setNeedsDisplay];
5627 - (void) drawSummaryContentRect:(CGRect)rect {
5628 bool highlighted(highlighted_);
5629 float width([self bounds].size.width);
5633 rect.size = [(UIImage *) icon_ size];
5635 while (rect.size.width > 16 || rect.size.height > 16) {
5636 rect.size.width /= 2;
5637 rect.size.height /= 2;
5640 rect.origin.x = 18 - rect.size.width / 2;
5641 rect.origin.y = 18 - rect.size.height / 2;
5643 [icon_ drawInRect:rect];
5646 if (badge_ != nil) {
5648 rect.size = [(UIImage *) badge_ size];
5650 rect.size.width /= 4;
5651 rect.size.height /= 4;
5653 rect.origin.x = 23 - rect.size.width / 2;
5654 rect.origin.y = 23 - rect.size.height / 2;
5656 [badge_ drawInRect:rect];
5663 UISetColor(commercial_ ? Purple_ : Black_);
5664 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5666 if (placard_ != nil)
5667 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5670 - (void) drawNormalContentRect:(CGRect)rect {
5671 bool highlighted(highlighted_);
5672 float width([self bounds].size.width);
5676 rect.size = [(UIImage *) icon_ size];
5678 while (rect.size.width > 32 || rect.size.height > 32) {
5679 rect.size.width /= 2;
5680 rect.size.height /= 2;
5683 rect.origin.x = 25 - rect.size.width / 2;
5684 rect.origin.y = 25 - rect.size.height / 2;
5686 [icon_ drawInRect:rect];
5689 if (badge_ != nil) {
5691 rect.size = [(UIImage *) badge_ size];
5693 rect.size.width /= 2;
5694 rect.size.height /= 2;
5696 rect.origin.x = 36 - rect.size.width / 2;
5697 rect.origin.y = 36 - rect.size.height / 2;
5699 [badge_ drawInRect:rect];
5706 UISetColor(commercial_ ? Purple_ : Black_);
5707 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5708 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5711 UISetColor(commercial_ ? Purplish_ : Gray_);
5712 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5714 if (placard_ != nil)
5715 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5718 - (void) drawContentRect:(CGRect)rect {
5720 [self drawSummaryContentRect:rect];
5722 [self drawNormalContentRect:rect];
5727 /* Section Cell {{{ */
5728 @interface SectionCell : CyteTableViewCell <
5729 CyteTableViewCellDelegate
5731 _H<NSString> basic_;
5732 _H<NSString> section_;
5734 _H<NSString> count_;
5736 _H<UISwitch> switch_;
5740 - (void) setSection:(Section *)section editing:(BOOL)editing;
5744 @implementation SectionCell
5746 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5747 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5748 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5749 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5750 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5752 UIView *content([self contentView]);
5753 CGRect bounds([content bounds]);
5755 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5756 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5757 [content addSubview:content_];
5758 [content_ setBackgroundColor:[UIColor whiteColor]];
5760 [content_ setDelegate:self];
5764 - (void) onSwitch:(id)sender {
5765 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5766 if (metadata == nil) {
5767 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5768 [Sections_ setObject:metadata forKey:basic_];
5771 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5775 - (void) setSection:(Section *)section editing:(BOOL)editing {
5776 if (editing != editing_) {
5778 [switch_ removeFromSuperview];
5780 [self addSubview:switch_];
5789 if (section == nil) {
5790 name_ = UCLocalize("ALL_PACKAGES");
5793 basic_ = [section name];
5794 section_ = [section localized];
5796 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5797 count_ = [NSString stringWithFormat:@"%d", [section count]];
5800 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5803 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5804 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5806 [content_ setNeedsDisplay];
5809 - (void) setFrame:(CGRect)frame {
5810 [super setFrame:frame];
5812 CGRect rect([switch_ frame]);
5813 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5816 - (NSString *) accessibilityLabel {
5820 - (void) drawContentRect:(CGRect)rect {
5821 bool highlighted(highlighted_ && !editing_);
5823 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5828 float width(rect.size.width);
5834 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5836 CGSize size = [count_ sizeWithFont:Font14_];
5840 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5846 /* File Table {{{ */
5847 @interface FileTable : CyteViewController <
5848 UITableViewDataSource,
5851 _transient Database *database_;
5852 _H<Package> package_;
5854 _H<NSMutableArray> files_;
5855 _H<UITableView, 2> list_;
5858 - (id) initWithDatabase:(Database *)database;
5859 - (void) setPackage:(Package *)package;
5863 @implementation FileTable
5865 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5866 return files_ == nil ? 0 : [files_ count];
5869 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5873 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5874 static NSString *reuseIdentifier = @"Cell";
5876 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5878 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5879 [cell setFont:[UIFont systemFontOfSize:16]];
5881 [cell setText:[files_ objectAtIndex:indexPath.row]];
5882 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5887 - (NSURL *) navigationURL {
5888 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5892 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5893 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5894 [list_ setRowHeight:24.0f];
5895 [(UITableView *) list_ setDataSource:self];
5896 [list_ setDelegate:self];
5897 [self setView:list_];
5900 - (void) viewDidLoad {
5901 [super viewDidLoad];
5903 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5906 - (void) releaseSubviews {
5912 [super releaseSubviews];
5915 - (id) initWithDatabase:(Database *)database {
5916 if ((self = [super init]) != nil) {
5917 database_ = database;
5921 - (void) setPackage:(Package *)package {
5925 files_ = [NSMutableArray arrayWithCapacity:32];
5927 if (package != nil) {
5929 name_ = [package id];
5931 if (NSArray *files = [package files])
5932 [files_ addObjectsFromArray:files];
5934 if ([files_ count] != 0) {
5935 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5936 [files_ removeObjectAtIndex:0];
5937 [files_ sortUsingSelector:@selector(compareByPath:)];
5939 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5940 [stack addObject:@"/"];
5942 for (int i(0), e([files_ count]); i != e; ++i) {
5943 NSString *file = [files_ objectAtIndex:i];
5944 while (![file hasPrefix:[stack lastObject]])
5945 [stack removeLastObject];
5946 NSString *directory = [stack lastObject];
5947 [stack addObject:[file stringByAppendingString:@"/"]];
5948 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5949 ([stack count] - 2) * 3, "",
5950 [file substringFromIndex:[directory length]]
5959 - (void) reloadData {
5962 [self setPackage:[database_ packageWithName:name_]];
5967 /* Package Controller {{{ */
5968 @interface CYPackageController : CydiaWebViewController <
5969 UIActionSheetDelegate
5971 _transient Database *database_;
5972 _H<Package> package_;
5975 _H<NSMutableArray> buttons_;
5976 _H<UIBarButtonItem> button_;
5979 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
5983 @implementation CYPackageController
5985 - (NSURL *) navigationURL {
5986 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5989 /* XXX: this is not safe at all... localization of /fail/ */
5990 - (void) _clickButtonWithName:(NSString *)name {
5991 if ([name isEqualToString:UCLocalize("CLEAR")])
5992 [delegate_ clearPackage:package_];
5993 else if ([name isEqualToString:UCLocalize("INSTALL")])
5994 [delegate_ installPackage:package_];
5995 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5996 [delegate_ installPackage:package_];
5997 else if ([name isEqualToString:UCLocalize("REMOVE")])
5998 [delegate_ removePackage:package_];
5999 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6000 [delegate_ installPackage:package_];
6001 else _assert(false);
6004 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6005 NSString *context([sheet context]);
6007 if ([context isEqualToString:@"modify"]) {
6008 if (button != [sheet cancelButtonIndex]) {
6009 NSString *buttonName = [buttons_ objectAtIndex:button];
6010 [self _clickButtonWithName:buttonName];
6013 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6017 - (bool) _allowJavaScriptPanel {
6022 - (void) _customButtonClicked {
6023 int count([buttons_ count]);
6028 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6030 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6031 [buttons addObjectsFromArray:buttons_];
6033 UIActionSheet *sheet = [[[UIActionSheet alloc]
6036 cancelButtonTitle:nil
6037 destructiveButtonTitle:nil
6038 otherButtonTitles:nil
6041 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6043 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6044 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6046 [sheet setContext:@"modify"];
6048 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6052 // We don't want to allow non-commercial packages to do custom things to the install button,
6053 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6054 - (void) customButtonClicked {
6056 [super customButtonClicked];
6058 [self _customButtonClicked];
6061 - (void) reloadButtonClicked {
6062 // Don't reload a commerical package by tapping the loading button,
6063 // but if it's not an Install button, we should forward it on.
6064 if (![package_ uninstalled])
6065 [self _customButtonClicked];
6068 - (void) applyLoadingTitle {
6069 // Don't show "Loading" as the title. Ever.
6072 - (UIBarButtonItem *) rightButton {
6077 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6078 if ((self = [super init]) != nil) {
6079 database_ = database;
6080 buttons_ = [NSMutableArray arrayWithCapacity:4];
6081 name_ = name == nil ? @"" : [NSString stringWithString:name];
6082 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6086 - (void) reloadData {
6089 package_ = [database_ packageWithName:name_];
6091 [buttons_ removeAllObjects];
6093 if (package_ != nil) {
6094 [(Package *) package_ parse];
6096 commercial_ = [package_ isCommercial];
6098 if ([package_ mode] != nil)
6099 [buttons_ addObject:UCLocalize("CLEAR")];
6100 if ([package_ source] == nil);
6101 else if ([package_ upgradableAndEssential:NO])
6102 [buttons_ addObject:UCLocalize("UPGRADE")];
6103 else if ([package_ uninstalled])
6104 [buttons_ addObject:UCLocalize("INSTALL")];
6106 [buttons_ addObject:UCLocalize("REINSTALL")];
6107 if (![package_ uninstalled])
6108 [buttons_ addObject:UCLocalize("REMOVE")];
6112 switch ([buttons_ count]) {
6113 case 0: title = nil; break;
6114 case 1: title = [buttons_ objectAtIndex:0]; break;
6115 default: title = UCLocalize("MODIFY"); break;
6118 button_ = [[[UIBarButtonItem alloc]
6120 style:UIBarButtonItemStylePlain
6122 action:@selector(customButtonClicked)
6126 - (bool) isLoading {
6127 return commercial_ ? [super isLoading] : false;
6133 /* Package List Controller {{{ */
6134 @interface PackageListController : CyteViewController <
6135 UITableViewDataSource,
6138 _transient Database *database_;
6140 _H<NSArray> packages_;
6141 _H<NSMutableArray> sections_;
6142 _H<UITableView, 2> list_;
6143 _H<NSMutableArray> index_;
6144 _H<NSMutableDictionary> indices_;
6145 _H<NSString> title_;
6146 unsigned reloading_;
6149 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6150 - (void) setDelegate:(id)delegate;
6151 - (void) resetCursor;
6156 @implementation PackageListController
6158 - (NSURL *) referrerURL {
6159 return [self navigationURL];
6162 - (bool) isSummarized {
6166 - (bool) showsSections {
6170 - (void) deselectWithAnimation:(BOOL)animated {
6171 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6174 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6175 CGRect base = [[self view] bounds];
6176 base.size.height -= bounds.size.height;
6177 base.origin = [list_ frame].origin;
6179 [UIView beginAnimations:nil context:NULL];
6180 [UIView setAnimationBeginsFromCurrentState:YES];
6181 [UIView setAnimationCurve:curve];
6182 [UIView setAnimationDuration:duration];
6183 [list_ setFrame:base];
6184 [UIView commitAnimations];
6187 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6188 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6191 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6192 [self resizeForKeyboardBounds:bounds duration:0];
6195 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6196 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6197 *curve = UIViewAnimationCurveEaseInOut;
6199 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6201 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6204 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6207 - (void) keyboardWillShow:(NSNotification *)notification {
6210 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6211 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6213 NSTimeInterval duration;
6214 UIViewAnimationCurve curve;
6215 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6217 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);
6218 UIViewController *base = self;
6219 while ([base parentOrPresentingViewController] != nil)
6220 base = [base parentOrPresentingViewController];
6221 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6222 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6224 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6225 intersection.size.height += CYStatusBarHeight();
6227 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6230 - (void) keyboardWillHide:(NSNotification *)notification {
6231 NSTimeInterval duration;
6232 UIViewAnimationCurve curve;
6233 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6235 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6238 - (void) viewWillAppear:(BOOL)animated {
6239 [super viewWillAppear:animated];
6241 [self resizeForKeyboardBounds:CGRectZero];
6242 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6243 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6246 - (void) viewWillDisappear:(BOOL)animated {
6247 [super viewWillDisappear:animated];
6249 [self resizeForKeyboardBounds:CGRectZero];
6250 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6251 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6254 - (void) viewDidAppear:(BOOL)animated {
6255 [super viewDidAppear:animated];
6256 [self deselectWithAnimation:animated];
6259 - (void) didSelectPackage:(Package *)package {
6260 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6261 [view setDelegate:delegate_];
6262 [[self navigationController] pushViewController:view animated:YES];
6265 #if TryIndexedCollation
6266 + (BOOL) hasIndexedCollation {
6267 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6271 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6272 NSInteger count([sections_ count]);
6273 return count == 0 ? 1 : count;
6276 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6277 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6279 return [[sections_ objectAtIndex:section] name];
6282 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6283 if ([sections_ count] == 0)
6285 return [[sections_ objectAtIndex:section] count];
6288 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6289 @synchronized (database_) {
6290 if ([database_ era] != era_)
6293 Section *section([sections_ objectAtIndex:[path section]]);
6294 NSInteger row([path row]);
6295 Package *package([packages_ objectAtIndex:([section row] + row)]);
6296 return [[package retain] autorelease];
6299 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6300 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6302 cell = [[[PackageCell alloc] init] autorelease];
6304 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6305 [cell setPackage:package asSummary:[self isSummarized]];
6309 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6310 Package *package([self packageAtIndexPath:path]);
6311 package = [database_ packageWithName:[package id]];
6312 [self didSelectPackage:package];
6315 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6316 if (![self showsSections])
6322 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6323 #if TryIndexedCollation
6324 if ([[self class] hasIndexedCollation]) {
6325 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6332 - (void) updateHeight {
6333 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6336 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6337 if ((self = [super init]) != nil) {
6338 database_ = database;
6339 title_ = [title copy];
6340 [[self navigationItem] setTitle:title_];
6345 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6346 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6347 [self setView:view];
6349 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6350 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6351 [view addSubview:list_];
6353 // XXX: is 20 the most optimal number here?
6354 [list_ setSectionIndexMinimumDisplayRowCount:20];
6356 [(UITableView *) list_ setDataSource:self];
6357 [list_ setDelegate:self];
6359 [self updateHeight];
6362 - (void) releaseSubviews {
6370 [super releaseSubviews];
6373 - (void) setDelegate:(id)delegate {
6374 delegate_ = delegate;
6377 - (bool) shouldYield {
6381 - (bool) shouldBlock {
6385 - (NSMutableArray *) _reloadPackages {
6386 @synchronized (database_) {
6387 era_ = [database_ era];
6388 NSArray *packages([database_ packages]);
6390 return [NSMutableArray arrayWithArray:packages];
6393 - (void) _reloadData {
6394 if (reloading_ != 0) {
6402 if ([self shouldYield]) {
6406 if (![self shouldBlock])
6409 hud = [delegate_ addProgressHUD];
6410 [hud setText:UCLocalize("LOADING")];
6414 packages = [self yieldToSelector:@selector(_reloadPackages)];
6417 [delegate_ removeProgressHUD:hud];
6418 } while (reloading_ == 2);
6420 packages = [self _reloadPackages];
6423 @synchronized (database_) {
6424 if (era_ != [database_ era])
6428 packages_ = packages;
6430 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6431 sections_ = [NSMutableArray arrayWithCapacity:16];
6433 Section *section = nil;
6435 #if TryIndexedCollation
6436 if ([[self class] hasIndexedCollation]) {
6437 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6439 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6440 NSArray *titles = [collation sectionIndexTitles];
6443 _profile(PackageTable$reloadData$Section)
6444 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6448 _profile(PackageTable$reloadData$Section$Package)
6449 package = [packages_ objectAtIndex:offset];
6450 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6453 while (secidx < index) {
6456 _profile(PackageTable$reloadData$Section$Allocate)
6457 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6460 _profile(PackageTable$reloadData$Section$Add)
6461 [sections_ addObject:section];
6465 [section addToCount];
6471 index_ = [NSMutableArray arrayWithCapacity:32];
6473 bool sectioned([self showsSections]);
6475 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6476 [sections_ addObject:section];
6479 _profile(PackageTable$reloadData$Section)
6480 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6484 _profile(PackageTable$reloadData$Section$Package)
6485 package = [packages_ objectAtIndex:offset];
6486 index = [package index];
6489 if (sectioned && (section == nil || [section index] != index)) {
6490 _profile(PackageTable$reloadData$Section$Allocate)
6491 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6494 [index_ addObject:[section name]];
6495 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6497 _profile(PackageTable$reloadData$Section$Add)
6498 [sections_ addObject:section];
6502 [section addToCount];
6507 [self updateHeight];
6509 _profile(PackageTable$reloadData$List)
6510 [(UITableView *) list_ setDataSource:self];
6515 - (void) reloadData {
6518 if ([self shouldYield])
6519 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6524 - (void) resetCursor {
6525 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6528 - (void) clearData {
6529 [self updateHeight];
6531 [list_ setDataSource:nil];
6539 /* Filtered Package List Controller {{{ */
6540 @interface FilteredPackageListController : PackageListController {
6543 _H<NSObject> object_;
6546 - (void) setObject:(id)object;
6547 - (void) setObject:(id)object forFilter:(SEL)filter;
6550 - (void) setFilter:(SEL)filter;
6552 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6556 @implementation FilteredPackageListController
6562 - (void) setFilter:(SEL)filter {
6563 @synchronized (self) {
6566 /* XXX: this is an unsafe optimization of doomy hell */
6567 Method method(class_getInstanceMethod([Package class], filter));
6568 _assert(method != NULL);
6569 imp_ = method_getImplementation(method);
6570 _assert(imp_ != NULL);
6573 - (void) setObject:(id)object {
6574 @synchronized (self) {
6578 - (void) setObject:(id)object forFilter:(SEL)filter {
6579 @synchronized (self) {
6580 [self setFilter:filter];
6581 [self setObject:object];
6584 - (NSMutableArray *) _reloadPackages {
6585 @synchronized (database_) {
6586 era_ = [database_ era];
6587 NSArray *packages([database_ packages]);
6589 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6593 _H<NSObject> object;
6595 @synchronized (self) {
6601 _profile(PackageTable$reloadData$Filter)
6602 for (Package *package in packages)
6603 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6604 [filtered addObject:package];
6610 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6611 if ((self = [super initWithDatabase:database title:title]) != nil) {
6612 [self setFilter:filter];
6613 [self setObject:object];
6620 /* Home Controller {{{ */
6621 @interface HomeController : CydiaWebViewController {
6622 CFRunLoopRef runloop_;
6623 SCNetworkReachabilityRef reachability_;
6628 @implementation HomeController
6630 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6631 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6635 if ((self = [super init]) != nil) {
6636 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6639 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6640 if (reachability_ != NULL) {
6641 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6642 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6644 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6645 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6652 if (reachability_ != NULL && runloop_ != NULL)
6653 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6657 - (NSURL *) navigationURL {
6658 return [NSURL URLWithString:@"cydia://home"];
6661 - (void) aboutButtonClicked {
6662 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6664 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6665 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6666 [alert setCancelButtonIndex:0];
6669 @"Copyright \u00a9 2008-2012\n"
6672 "Jay Freeman (saurik)\n"
6673 "saurik@saurik.com\n"
6674 "http://www.saurik.com/"
6680 - (UIBarButtonItem *) leftButton {
6681 return [[[UIBarButtonItem alloc]
6682 initWithTitle:UCLocalize("ABOUT")
6683 style:UIBarButtonItemStylePlain
6685 action:@selector(aboutButtonClicked)
6691 /* Manage Controller {{{ */
6692 @interface ManageController : CydiaWebViewController {
6695 - (void) queueStatusDidChange;
6699 @implementation ManageController
6702 if ((self = [super init]) != nil) {
6703 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6707 - (NSURL *) navigationURL {
6708 return [NSURL URLWithString:@"cydia://manage"];
6711 - (UIBarButtonItem *) leftButton {
6712 return [[[UIBarButtonItem alloc]
6713 initWithTitle:UCLocalize("SETTINGS")
6714 style:UIBarButtonItemStylePlain
6716 action:@selector(settingsButtonClicked)
6720 - (void) settingsButtonClicked {
6721 [delegate_ showSettings];
6724 - (void) queueButtonClicked {
6728 - (UIBarButtonItem *) rightButton {
6729 return Queuing_ ? [[[UIBarButtonItem alloc]
6730 initWithTitle:UCLocalize("QUEUE")
6731 style:UIBarButtonItemStyleDone
6733 action:@selector(queueButtonClicked)
6734 ] autorelease] : nil;
6737 - (void) queueStatusDidChange {
6738 [self applyRightButton];
6741 - (bool) isLoading {
6742 return !Queuing_ && [super isLoading];
6748 /* Refresh Bar {{{ */
6749 @interface RefreshBar : UINavigationBar {
6750 _H<UIProgressIndicator> indicator_;
6751 _H<UITextLabel> prompt_;
6752 _H<UIProgressBar> progress_;
6753 _H<UINavigationButton> cancel_;
6758 @implementation RefreshBar
6760 - (void) positionViews {
6761 CGRect frame = [cancel_ frame];
6762 frame.size = [cancel_ sizeThatFits:frame.size];
6763 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6764 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6765 [cancel_ setFrame:frame];
6767 CGSize prgsize = {75, 100};
6769 [self frame].size.width - prgsize.width - 10,
6770 ([self frame].size.height - prgsize.height) / 2
6772 [progress_ setFrame:prgrect];
6774 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6775 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6776 CGRect indrect = {{indoffset, indoffset}, indsize};
6777 [indicator_ setFrame:indrect];
6779 CGSize prmsize = {215, indsize.height + 4};
6781 indoffset * 2 + indsize.width,
6782 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6784 [prompt_ setFrame:prmrect];
6787 - (void) setFrame:(CGRect)frame {
6788 [super setFrame:frame];
6789 [self positionViews];
6792 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6793 if ((self = [super initWithFrame:frame]) != nil) {
6794 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6796 [self setBarStyle:UIBarStyleBlack];
6798 UIBarStyle barstyle([self _barStyle:NO]);
6799 bool ugly(barstyle == UIBarStyleDefault);
6801 UIProgressIndicatorStyle style = ugly ?
6802 UIProgressIndicatorStyleMediumBrown :
6803 UIProgressIndicatorStyleMediumWhite;
6805 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6806 [(UIProgressIndicator *) indicator_ setStyle:style];
6807 [indicator_ startAnimation];
6808 [self addSubview:indicator_];
6810 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6811 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6812 [prompt_ setBackgroundColor:[UIColor clearColor]];
6813 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6814 [self addSubview:prompt_];
6816 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6817 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6818 [(UIProgressBar *) progress_ setStyle:0];
6819 [self addSubview:progress_];
6821 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6822 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6823 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6824 [cancel_ setBarStyle:barstyle];
6826 [self positionViews];
6830 - (void) setCancellable:(bool)cancellable {
6832 [self addSubview:cancel_];
6834 [cancel_ removeFromSuperview];
6838 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6839 [progress_ setProgress:0];
6843 [self setCancellable:NO];
6846 - (void) setPrompt:(NSString *)prompt {
6847 [prompt_ setText:prompt];
6850 - (void) setProgress:(float)progress {
6851 [progress_ setProgress:progress];
6857 /* Cydia Navigation Controller Interface {{{ */
6858 @interface UINavigationController (Cydia)
6860 - (NSArray *) navigationURLCollection;
6861 - (void) unloadData;
6866 /* Cydia Tab Bar Controller {{{ */
6867 @interface CYTabBarController : UITabBarController <
6868 UITabBarControllerDelegate,
6871 _transient Database *database_;
6872 _H<RefreshBar, 1> refreshbar_;
6876 // XXX: ok, "updatedelegate_"?...
6877 _transient NSObject<CydiaDelegate> *updatedelegate_;
6879 _H<UIViewController> remembered_;
6880 _transient UIViewController *transient_;
6883 - (NSArray *) navigationURLCollection;
6884 - (void) dropBar:(BOOL)animated;
6885 - (void) beginUpdate;
6886 - (void) raiseBar:(BOOL)animated;
6888 - (void) unloadData;
6892 @implementation CYTabBarController
6894 - (void) didReceiveMemoryWarning {
6895 [super didReceiveMemoryWarning];
6897 // presenting a UINavigationController on 2.x does not update its transitionView
6898 // it thereby will not allow its topViewController to be unloaded by memory pressure
6899 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6900 UIViewController *selected([self selectedViewController]);
6901 for (UINavigationController *controller in [self viewControllers])
6902 if (controller != selected)
6903 if (UIViewController *top = [controller topViewController])
6908 - (void) setUnselectedViewController:(UIViewController *)transient {
6909 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6910 if (transient != nil) {
6911 [[[self viewControllers] objectAtIndex:0] pushViewController:transient animated:YES];
6912 [self setSelectedIndex:0];
6916 NSMutableArray *controllers = [[[self viewControllers] mutableCopy] autorelease];
6917 if (transient != nil) {
6918 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
6919 [navigation setViewControllers:[NSArray arrayWithObject:transient]];
6920 transient = navigation;
6922 if (transient_ == nil)
6923 remembered_ = [controllers objectAtIndex:0];
6924 transient_ = transient;
6925 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6926 [controllers replaceObjectAtIndex:0 withObject:transient_];
6927 [self setSelectedIndex:0];
6928 [self setViewControllers:controllers];
6929 [self concealTabBarSelection];
6930 } else if (remembered_ != nil) {
6931 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6932 transient_ = transient;
6933 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6935 [self setViewControllers:controllers];
6936 [self revealTabBarSelection];
6940 - (UIViewController *) unselectedViewController {
6944 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6945 if ([self unselectedViewController])
6946 [self setUnselectedViewController:nil];
6948 // presenting a UINavigationController on 2.x does not update its transitionView
6949 // if this view was unloaded, the tranitionView may currently be presenting nothing
6950 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6951 UINavigationController *navigation((UINavigationController *) viewController);
6952 [navigation pushViewController:[[[UIViewController alloc] init] autorelease] animated:NO];
6953 [navigation popViewControllerAnimated:NO];
6957 - (NSArray *) navigationURLCollection {
6958 NSMutableArray *items([NSMutableArray array]);
6960 // XXX: Should this deal with transient view controllers?
6961 for (id navigation in [self viewControllers]) {
6962 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6964 [items addObject:stack];
6970 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6971 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6972 [self setUnselectedViewController:nil];
6974 [super dismissModalViewControllerAnimated:YES];
6977 - (void) unloadData {
6980 for (UINavigationController *controller in [self viewControllers])
6981 [controller unloadData];
6983 if (UIViewController *selected = [self selectedViewController])
6984 [selected reloadData];
6986 if (UIViewController *unselected = [self unselectedViewController]) {
6987 [unselected unloadData];
6988 [unselected reloadData];
6993 [[NSNotificationCenter defaultCenter] removeObserver:self];
6998 - (id) initWithDatabase:(Database *)database {
6999 if ((self = [super init]) != nil) {
7000 database_ = database;
7001 [self setDelegate:self];
7003 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7004 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7006 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
7010 - (void) setUpdate:(NSDate *)date {
7014 - (void) beginUpdate {
7015 [(RefreshBar *) refreshbar_ start];
7018 [updatedelegate_ retainNetworkActivityIndicator];
7022 detachNewThreadSelector:@selector(performUpdate)
7028 - (void) performUpdate {
7029 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7032 status.setDelegate(self);
7033 [database_ updateWithStatus:status];
7036 performSelectorOnMainThread:@selector(completeUpdate)
7044 - (void) stopUpdateWithSelector:(SEL)selector {
7046 [updatedelegate_ releaseNetworkActivityIndicator];
7048 [self raiseBar:YES];
7051 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7054 - (void) completeUpdate {
7057 [self stopUpdateWithSelector:@selector(reloadData)];
7060 - (void) cancelUpdate {
7061 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7064 - (void) cancelPressed {
7065 [self cancelUpdate];
7072 - (void) addProgressEvent:(CydiaProgressEvent *)event {
7073 [refreshbar_ setPrompt:[event compoundMessage]];
7076 - (bool) isProgressCancelled {
7080 - (void) setProgressCancellable:(NSNumber *)cancellable {
7081 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
7084 - (void) setProgressPercent:(NSNumber *)percent {
7085 [refreshbar_ setProgress:[percent floatValue]];
7088 - (void) setProgressStatus:(NSDictionary *)status {
7090 [self setProgressPercent:[status objectForKey:@"Percent"]];
7093 - (void) setUpdateDelegate:(id)delegate {
7094 updatedelegate_ = delegate;
7097 - (UIView *) transitionView {
7098 if ([self respondsToSelector:@selector(_transitionView)])
7099 return [self _transitionView];
7101 return MSHookIvar<id>(self, "_viewControllerTransitionView");
7104 - (void) dropBar:(BOOL)animated {
7109 UIView *transition([self transitionView]);
7110 [[self view] addSubview:refreshbar_];
7112 CGRect barframe([refreshbar_ frame]);
7114 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
7115 barframe.origin.y = CYStatusBarHeight();
7117 barframe.origin.y = 0;
7119 [refreshbar_ setFrame:barframe];
7122 [UIView beginAnimations:nil context:NULL];
7124 CGRect viewframe = [transition frame];
7125 viewframe.origin.y += barframe.size.height;
7126 viewframe.size.height -= barframe.size.height;
7127 [transition setFrame:viewframe];
7130 [UIView commitAnimations];
7132 // Ensure bar has the proper width for our view, it might have changed
7133 barframe.size.width = viewframe.size.width;
7134 [refreshbar_ setFrame:barframe];
7137 - (void) raiseBar:(BOOL)animated {
7142 UIView *transition([self transitionView]);
7143 [refreshbar_ removeFromSuperview];
7145 CGRect barframe([refreshbar_ frame]);
7148 [UIView beginAnimations:nil context:NULL];
7150 CGRect viewframe = [transition frame];
7151 viewframe.origin.y -= barframe.size.height;
7152 viewframe.size.height += barframe.size.height;
7153 [transition setFrame:viewframe];
7156 [UIView commitAnimations];
7159 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7160 bool dropped(dropped_);
7165 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7171 - (void) statusBarFrameChanged:(NSNotification *)notification {
7181 /* Cydia Navigation Controller Implementation {{{ */
7182 @implementation UINavigationController (Cydia)
7184 - (NSArray *) navigationURLCollection {
7185 NSMutableArray *stack([NSMutableArray array]);
7187 for (CyteViewController *controller in [self viewControllers]) {
7188 NSString *url = [[controller navigationURL] absoluteString];
7190 [stack addObject:url];
7196 - (void) reloadData {
7199 UIViewController *visible([self visibleViewController]);
7201 [visible reloadData];
7203 // on the iPad, this view controller is ALSO visible. :(
7205 if (UIViewController *top = [self topViewController])
7210 - (void) unloadData {
7211 for (CyteViewController *page in [self viewControllers])
7220 /* Cydia:// Protocol {{{ */
7221 @interface CydiaURLProtocol : NSURLProtocol {
7226 @implementation CydiaURLProtocol
7228 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7229 NSURL *url([request URL]);
7233 NSString *scheme([[url scheme] lowercaseString]);
7234 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7236 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7242 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7246 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7247 id<NSURLProtocolClient> client([self client]);
7249 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7251 NSData *data(UIImagePNGRepresentation(icon));
7253 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7254 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7255 [client URLProtocol:self didLoadData:data];
7256 [client URLProtocolDidFinishLoading:self];
7260 - (void) startLoading {
7261 id<NSURLProtocolClient> client([self client]);
7262 NSURLRequest *request([self request]);
7264 NSURL *url([request URL]);
7265 NSString *href([url absoluteString]);
7266 NSString *scheme([[url scheme] lowercaseString]);
7270 if ([scheme isEqualToString:@"cydia"])
7271 path = [href substringFromIndex:8];
7272 else if ([scheme isEqualToString:@"about"])
7273 path = [href substringFromIndex:12];
7274 else _assert(false);
7276 NSRange slash([path rangeOfString:@"/"]);
7279 if (slash.location == NSNotFound) {
7283 command = [path substringToIndex:slash.location];
7284 path = [path substringFromIndex:(slash.location + 1)];
7287 Database *database([Database sharedInstance]);
7289 if ([command isEqualToString:@"package-icon"]) {
7292 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7293 Package *package([database packageWithName:path]);
7297 UIImage *icon([package icon]);
7298 [self _returnPNGWithImage:icon forRequest:request];
7299 } else if ([command isEqualToString:@"uikit-image"]) {
7302 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7303 UIImage *icon(_UIImageWithName(path));
7304 [self _returnPNGWithImage:icon forRequest:request];
7305 } else if ([command isEqualToString:@"section-icon"]) {
7308 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7309 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7311 icon = [UIImage applicationImageNamed:@"unknown.png"];
7312 [self _returnPNGWithImage:icon forRequest:request];
7314 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7318 - (void) stopLoading {
7324 /* Section Controller {{{ */
7325 @interface SectionController : FilteredPackageListController {
7326 _H<IndirectDelegate, 1> indirect_;
7327 _H<CydiaObject> cydia_;
7328 _H<NSString> section_;
7329 std::vector< _H<CyteWebViewTableViewCell, 1> > promoted_;
7332 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7336 @implementation SectionController
7338 - (NSURL *) referrerURL {
7339 NSString *name = section_;
7343 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@", UI_, [name stringByAddingPercentEscapesIncludingReserved]]];
7346 - (NSURL *) navigationURL {
7347 NSString *name = section_;
7351 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", [name stringByAddingPercentEscapesIncludingReserved]]];
7354 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7357 title = UCLocalize("ALL_PACKAGES");
7358 else if (![name isEqual:@""])
7359 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7361 title = UCLocalize("NO_SECTION");
7363 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7364 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7365 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7370 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7371 return [super numberOfSectionsInTableView:list] + 1;
7374 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7375 return section == 0 ? nil : [super tableView:list titleForHeaderInSection:(section - 1)];
7378 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7379 return section == 0 ? promoted_.size() : [super tableView:list numberOfRowsInSection:(section - 1)];
7382 + (NSIndexPath *) adjustedIndexPath:(NSIndexPath *)path {
7383 return [NSIndexPath indexPathForRow:[path row] inSection:([path section] - 1)];
7386 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7387 if ([path section] != 0)
7388 return [super tableView:table cellForRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7390 return promoted_[[path row]];
7393 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
7394 if ([path section] != 0)
7395 return [super tableView:table didSelectRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7398 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
7399 NSInteger section([super tableView:tableView sectionForSectionIndexTitle:title atIndex:index]);
7400 return section == 0 ? 0 : section + 1;
7403 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7404 NSURL *url([request URL]);
7408 if ([frame isEqualToString:@"_open"])
7409 [delegate_ openURL:url];
7411 WebFrame *frame(nil);
7412 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7413 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7415 frame = [view mainFrame];
7417 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7419 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7420 [controller setDelegate:delegate_];
7421 [[self navigationController] pushViewController:controller animated:YES];
7427 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7428 return [CydiaWebViewController requestWithHeaders:request];
7431 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7432 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7438 // XXX: this code is horrible. I mean, wtf Jay?
7439 if (ShowPromoted_ && [[Metadata_ objectForKey:@"ShowPromoted"] boolValue]) {
7440 promoted_.resize(1);
7442 for (unsigned i(0); i != promoted_.size(); ++i) {
7443 CyteWebViewTableViewCell *promoted([CyteWebViewTableViewCell cellWithRequest:[NSURLRequest
7444 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sectionhead/%u/%@",
7445 UI_, i, section_ == nil ? @"" : [section_ stringByAddingPercentEscapesIncludingReserved]]
7448 cachePolicy:NSURLRequestUseProtocolCachePolicy
7452 [promoted setDelegate:self];
7453 promoted_[i] = promoted;
7458 - (void) setDelegate:(id)delegate {
7459 [super setDelegate:delegate];
7460 [cydia_ setDelegate:delegate];
7463 - (void) releaseSubviews {
7465 [super releaseSubviews];
7470 /* Sections Controller {{{ */
7471 @interface SectionsController : CyteViewController <
7472 UITableViewDataSource,
7475 _transient Database *database_;
7476 _H<NSMutableArray> sections_;
7477 _H<NSMutableArray> filtered_;
7478 _H<UITableView, 2> list_;
7481 - (id) initWithDatabase:(Database *)database;
7482 - (void) editButtonClicked;
7486 @implementation SectionsController
7488 - (NSURL *) navigationURL {
7489 return [NSURL URLWithString:@"cydia://sections"];
7492 - (void) updateNavigationItem {
7493 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7494 if ([sections_ count] == 0) {
7495 [[self navigationItem] setRightBarButtonItem:nil];
7497 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7498 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7500 action:@selector(editButtonClicked)
7501 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7505 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7506 [super setEditing:editing animated:animated];
7511 [delegate_ updateData];
7513 [self updateNavigationItem];
7516 - (void) viewDidAppear:(BOOL)animated {
7517 [super viewDidAppear:animated];
7518 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7521 - (void) viewWillDisappear:(BOOL)animated {
7522 [super viewWillDisappear:animated];
7523 [self setEditing:NO];
7526 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7527 Section *section = nil;
7528 int index = [indexPath row];
7529 if (![self isEditing]) {
7532 section = [filtered_ objectAtIndex:index];
7534 section = [sections_ objectAtIndex:index];
7539 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7540 if ([self isEditing])
7541 return [sections_ count];
7543 return [filtered_ count] + 1;
7546 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7550 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7551 static NSString *reuseIdentifier = @"SectionCell";
7553 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7555 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7557 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7562 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7563 if ([self isEditing])
7566 Section *section = [self sectionAtIndexPath:indexPath];
7568 SectionController *controller = [[[SectionController alloc]
7569 initWithDatabase:database_
7570 section:[section name]
7572 [controller setDelegate:delegate_];
7574 [[self navigationController] pushViewController:controller animated:YES];
7578 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7579 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7580 [list_ setRowHeight:45.0f];
7581 [(UITableView *) list_ setDataSource:self];
7582 [list_ setDelegate:self];
7583 [self setView:list_];
7586 - (void) viewDidLoad {
7587 [super viewDidLoad];
7589 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7592 - (void) releaseSubviews {
7598 [super releaseSubviews];
7601 - (id) initWithDatabase:(Database *)database {
7602 if ((self = [super init]) != nil) {
7603 database_ = database;
7607 - (void) reloadData {
7610 NSArray *packages = [database_ packages];
7612 sections_ = [NSMutableArray arrayWithCapacity:16];
7613 filtered_ = [NSMutableArray arrayWithCapacity:16];
7615 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7618 for (Package *package in packages) {
7619 NSString *name([package section]);
7620 NSString *key(name == nil ? @"" : name);
7624 _profile(SectionsView$reloadData$Section)
7625 section = [sections objectForKey:key];
7626 if (section == nil) {
7627 _profile(SectionsView$reloadData$Section$Allocate)
7628 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7629 [sections setObject:section forKey:key];
7634 [section addToCount];
7636 _profile(SectionsView$reloadData$Filter)
7637 if (![package valid] || ![package visible])
7645 [sections_ addObjectsFromArray:[sections allValues]];
7647 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7649 for (Section *section in (id) sections_) {
7650 size_t count([section row]);
7654 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7655 [section setCount:count];
7656 [filtered_ addObject:section];
7659 [self updateNavigationItem];
7664 - (void) editButtonClicked {
7665 [self setEditing:![self isEditing] animated:YES];
7671 /* Changes Controller {{{ */
7672 @interface ChangesController : CyteViewController <
7673 CyteWebViewDelegate,
7674 UITableViewDataSource,
7677 _transient Database *database_;
7679 _H<NSMutableArray> packages_;
7680 _H<NSMutableArray> sections_;
7681 _H<UITableView, 2> list_;
7682 _H<CyteWebView, 1> dickbar_;
7684 _H<IndirectDelegate, 1> indirect_;
7685 _H<CydiaObject> cydia_;
7688 - (id) initWithDatabase:(Database *)database;
7692 @implementation ChangesController
7694 - (NSURL *) navigationURL {
7695 return [NSURL URLWithString:@"cydia://changes"];
7698 - (void) viewDidAppear:(BOOL)animated {
7699 [super viewDidAppear:animated];
7700 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7703 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7704 NSInteger count([sections_ count]);
7705 return count == 0 ? 1 : count;
7708 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7709 if ([sections_ count] == 0)
7711 return [[sections_ objectAtIndex:section] name];
7714 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7715 if ([sections_ count] == 0)
7717 return [[sections_ objectAtIndex:section] count];
7720 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7721 @synchronized (database_) {
7722 if ([database_ era] != era_)
7725 NSUInteger sectionIndex([path section]);
7726 if (sectionIndex >= [sections_ count])
7728 Section *section([sections_ objectAtIndex:sectionIndex]);
7729 NSInteger row([path row]);
7730 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7733 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7734 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7736 cell = [[[PackageCell alloc] init] autorelease];
7738 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7739 [cell setPackage:package asSummary:false];
7743 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7744 Package *package([self packageAtIndexPath:path]);
7745 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[NSString stringWithFormat:@"%@/#!/changes/", UI_]] autorelease]);
7746 [view setDelegate:delegate_];
7747 [[self navigationController] pushViewController:view animated:YES];
7751 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7752 NSString *context([alert context]);
7754 if ([context isEqualToString:@"norefresh"])
7755 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7758 - (void) refreshButtonClicked {
7759 if (IsReachable("cydia.saurik.com")) {
7760 [delegate_ beginUpdate];
7761 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7763 UIAlertView *alert = [[[UIAlertView alloc]
7764 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
7765 message:@"Host Unreachable" // XXX: Localize
7767 cancelButtonTitle:UCLocalize("OK")
7768 otherButtonTitles:nil
7771 [alert setContext:@"norefresh"];
7776 - (void) upgradeButtonClicked {
7777 [delegate_ distUpgrade];
7778 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7782 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7783 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7784 [self setView:view];
7786 list_ = [[[UITableView alloc] initWithFrame:[view bounds] style:UITableViewStylePlain] autorelease];
7787 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7788 [list_ setRowHeight:73];
7789 [(UITableView *) list_ setDataSource:self];
7790 [list_ setDelegate:self];
7791 [view addSubview:list_];
7793 if (AprilFools_ && kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
7794 CGRect dickframe([view bounds]);
7795 dickframe.size.height = 44;
7797 dickbar_ = [[[CyteWebView alloc] initWithFrame:dickframe] autorelease];
7798 [dickbar_ setDelegate:self];
7799 [view addSubview:dickbar_];
7801 [dickbar_ setBackgroundColor:[UIColor clearColor]];
7802 [dickbar_ setScalesPageToFit:YES];
7804 UIWebDocumentView *document([dickbar_ _documentView]);
7805 [document setBackgroundColor:[UIColor clearColor]];
7806 [document setDrawsBackground:NO];
7808 WebView *webview([document webView]);
7809 [webview setShouldUpdateWhileOffscreen:NO];
7811 UIScrollView *scroller([dickbar_ scrollView]);
7812 [scroller setScrollingEnabled:NO];
7813 [scroller setFixedBackgroundPattern:YES];
7814 [scroller setBackgroundColor:[UIColor clearColor]];
7816 WebPreferences *preferences([webview preferences]);
7817 [preferences setCacheModel:WebCacheModelDocumentBrowser];
7818 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
7819 [preferences setOfflineWebApplicationCacheEnabled:YES];
7821 [dickbar_ loadRequest:[NSURLRequest
7822 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/dickbar/", UI_]]]
7823 cachePolicy:NSURLRequestUseProtocolCachePolicy
7827 UIEdgeInsets inset = {44, 0, 0, 0};
7828 [list_ setContentInset:inset];
7830 [dickbar_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7834 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7835 NSURL *url([request URL]);
7839 if ([frame isEqualToString:@"_open"])
7840 [delegate_ openURL:url];
7842 WebFrame *frame(nil);
7843 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7844 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7846 frame = [view mainFrame];
7848 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7850 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7851 [controller setDelegate:delegate_];
7852 [[self navigationController] pushViewController:controller animated:YES];
7858 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7859 return [CydiaWebViewController requestWithHeaders:request];
7862 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7863 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7866 - (void) setDelegate:(id)delegate {
7867 [super setDelegate:delegate];
7868 [cydia_ setDelegate:delegate];
7871 - (void) viewDidLoad {
7872 [super viewDidLoad];
7874 [[self navigationItem] setTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES"))];
7877 - (void) releaseSubviews {
7884 [super releaseSubviews];
7887 - (id) initWithDatabase:(Database *)database {
7888 if ((self = [super init]) != nil) {
7889 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7890 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7891 database_ = database;
7895 - (NSMutableArray *) _reloadPackages {
7896 @synchronized (database_) {
7897 era_ = [database_ era];
7898 NSArray *packages([database_ packages]);
7900 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7903 _profile(ChangesController$_reloadPackages$Filter)
7904 for (Package *package in packages)
7905 if ([package upgradableAndEssential:YES] || [package visible])
7906 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7909 _profile(ChangesController$_reloadPackages$radixSort)
7910 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7917 - (void) _reloadData {
7918 NSMutableArray *packages;
7922 UIProgressHUD *hud([delegate_ addProgressHUD]);
7923 [hud setText:UCLocalize("LOADING")];
7924 //NSLog(@"HUD:%@::%@", delegate_, hud);
7925 packages = [self yieldToSelector:@selector(_reloadPackages)];
7926 [delegate_ removeProgressHUD:hud];
7928 packages = [self _reloadPackages];
7931 @synchronized (database_) {
7932 if (era_ != [database_ era])
7935 packages_ = packages;
7936 sections_ = [NSMutableArray arrayWithCapacity:16];
7938 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7939 Section *ignored = nil;
7940 Section *section = nil;
7944 bool unseens = false;
7946 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7948 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7949 Package *package = [packages_ objectAtIndex:offset];
7951 BOOL uae = [package upgradableAndEssential:YES];
7955 time_t seen([package seen]);
7957 if (section == nil || last != seen) {
7961 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7964 _profile(ChangesController$reloadData$Allocate)
7965 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7966 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7967 [sections_ addObject:section];
7971 [section addToCount];
7972 } else if ([package ignored]) {
7973 if (ignored == nil) {
7974 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7976 [ignored addToCount];
7979 [upgradable addToCount];
7984 CFRelease(formatter);
7987 Section *last = [sections_ lastObject];
7988 size_t count = [last count];
7989 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7990 [sections_ removeLastObject];
7993 if ([ignored count] != 0)
7994 [sections_ insertObject:ignored atIndex:0];
7996 [sections_ insertObject:upgradable atIndex:0];
8000 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
8001 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
8002 style:UIBarButtonItemStylePlain
8004 action:@selector(upgradeButtonClicked)
8005 ] autorelease]) animated:YES];
8007 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
8008 initWithTitle:UCLocalize("REFRESH")
8009 style:UIBarButtonItemStylePlain
8011 action:@selector(refreshButtonClicked)
8012 ] autorelease]) animated:YES];
8017 - (void) reloadData {
8019 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
8024 /* Search Controller {{{ */
8025 @interface SearchController : FilteredPackageListController <
8028 _H<UISearchBar, 1> search_;
8032 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
8033 - (void) reloadData;
8037 @implementation SearchController
8039 - (NSURL *) referrerURL {
8040 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
8043 - (NSURL *) navigationURL {
8044 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
8045 return [NSURL URLWithString:@"cydia://search"];
8047 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
8050 - (NSArray *) termsForQuery:(NSString *)query {
8051 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
8052 for (NSString *component in [query componentsSeparatedByString:@" "])
8053 if ([component length] != 0)
8054 [terms addObject:component];
8059 - (void) useSearch {
8060 [self setObject:[self termsForQuery:[search_ text]] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
8065 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
8066 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8071 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
8072 [search_ resignFirstResponder];
8076 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
8077 [search_ setText:@""];
8078 [self searchBarButtonClicked:searchBar];
8081 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
8082 [self searchBarButtonClicked:searchBar];
8085 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
8086 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8090 - (bool) shouldYield {
8094 - (bool) shouldBlock {
8095 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
8098 - (bool) isSummarized {
8099 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
8102 - (bool) showsSections {
8106 - (NSMutableArray *) _reloadPackages {
8107 NSMutableArray *packages([super _reloadPackages]);
8108 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8109 [packages radixSortUsingSelector:@selector(rank)];
8113 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
8114 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[self termsForQuery:query]])) {
8115 search_ = [[[UISearchBar alloc] init] autorelease];
8116 [search_ setDelegate:self];
8119 [search_ setText:query];
8123 - (void) viewDidAppear:(BOOL)animated {
8124 [super viewDidAppear:animated];
8126 if (!searchloaded_) {
8127 searchloaded_ = YES;
8128 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
8129 [search_ layoutSubviews];
8130 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
8132 UITextField *textField;
8133 if ([search_ respondsToSelector:@selector(searchField)])
8134 textField = [search_ searchField];
8136 textField = MSHookIvar<UITextField *>(search_, "_searchField");
8138 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8139 [textField setEnablesReturnKeyAutomatically:NO];
8140 [[self navigationItem] setTitleView:textField];
8143 if ([self isSummarized])
8144 [search_ becomeFirstResponder];
8147 - (void) reloadData {
8148 id object([search_ text]);
8149 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8150 object = [self termsForQuery:object];
8152 [self setObject:object];
8158 - (void) didSelectPackage:(Package *)package {
8159 [search_ resignFirstResponder];
8160 [super didSelectPackage:package];
8165 /* Package Settings Controller {{{ */
8166 @interface PackageSettingsController : CyteViewController <
8167 UITableViewDataSource,
8170 _transient Database *database_;
8172 _H<Package> package_;
8173 _H<UITableView, 2> table_;
8174 _H<UISwitch> subscribedSwitch_;
8175 _H<UISwitch> ignoredSwitch_;
8176 _H<UITableViewCell> subscribedCell_;
8177 _H<UITableViewCell> ignoredCell_;
8180 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
8184 @implementation PackageSettingsController
8186 - (NSURL *) navigationURL {
8187 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
8190 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8191 if (package_ == nil)
8194 if ([package_ installed] == nil)
8200 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8201 if (package_ == nil)
8204 // both sections contain just one item right now.
8208 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8212 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8214 return UCLocalize("SHOW_ALL_CHANGES_EX");
8216 return UCLocalize("IGNORE_UPGRADES_EX");
8219 - (void) onSubscribed:(id)control {
8220 bool value([control isOn]);
8221 if (package_ == nil)
8223 if ([package_ setSubscribed:value])
8224 [delegate_ updateData];
8227 - (void) _updateIgnored {
8228 const char *package([name_ UTF8String]);
8229 bool on([ignoredSwitch_ isOn]);
8231 pid_t pid(ExecFork());
8233 FILE *dpkg(popen("dpkg --set-selections", "w"));
8234 fwrite(package, strlen(package), 1, dpkg);
8237 fwrite(" hold\n", 6, 1, dpkg);
8239 fwrite(" install\n", 9, 1, dpkg);
8250 - (void) onIgnored:(id)control {
8251 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8252 [invocation setTarget:self];
8253 [invocation setSelector:@selector(_updateIgnored)];
8255 [delegate_ reloadDataWithInvocation:invocation];
8258 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8259 if (package_ == nil)
8262 switch ([indexPath section]) {
8263 case 0: return subscribedCell_;
8264 case 1: return ignoredCell_;
8273 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8274 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8275 [self setView:view];
8277 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8278 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8279 [(UITableView *) table_ setDataSource:self];
8280 [table_ setDelegate:self];
8281 [view addSubview:table_];
8283 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8284 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8285 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8287 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8288 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8289 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8291 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8292 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8293 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8294 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8296 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8297 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8298 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8299 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8302 - (void) viewDidLoad {
8303 [super viewDidLoad];
8305 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8308 - (void) releaseSubviews {
8310 subscribedCell_ = nil;
8312 ignoredSwitch_ = nil;
8313 subscribedSwitch_ = nil;
8315 [super releaseSubviews];
8318 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8319 if ((self = [super init]) != nil) {
8320 database_ = database;
8325 - (void) reloadData {
8328 package_ = [database_ packageWithName:name_];
8330 if (package_ != nil) {
8331 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8332 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8333 } // XXX: what now, G?
8335 [table_ reloadData];
8341 /* Installed Controller {{{ */
8342 @interface InstalledController : FilteredPackageListController {
8346 - (id) initWithDatabase:(Database *)database;
8348 - (void) updateRoleButton;
8349 - (void) queueStatusDidChange;
8353 @implementation InstalledController
8355 - (NSURL *) referrerURL {
8356 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8359 - (NSURL *) navigationURL {
8360 return [NSURL URLWithString:@"cydia://installed"];
8363 - (id) initWithDatabase:(Database *)database {
8364 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8365 [self updateRoleButton];
8366 [self queueStatusDidChange];
8371 - (void) queueButtonClicked {
8376 - (void) queueStatusDidChange {
8380 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8381 initWithTitle:UCLocalize("QUEUE")
8382 style:UIBarButtonItemStyleDone
8384 action:@selector(queueButtonClicked)
8387 [[self navigationItem] setLeftBarButtonItem:nil];
8393 - (void) updateRoleButton {
8394 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8395 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8396 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8397 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8399 action:@selector(roleButtonClicked)
8403 - (void) roleButtonClicked {
8404 [self setObject:[NSNumber numberWithBool:expert_]];
8408 [self updateRoleButton];
8414 /* Source Cell {{{ */
8415 @interface SourceCell : CyteTableViewCell <
8416 CyteTableViewCellDelegate
8420 _H<NSString> origin_;
8421 _H<NSString> label_;
8424 - (void) setSource:(Source *)source;
8428 @implementation SourceCell
8430 - (void) _setImage:(NSArray *)data {
8431 if ([url_ isEqual:[data objectAtIndex:0]]) {
8432 icon_ = [data objectAtIndex:1];
8433 [content_ setNeedsDisplay];
8437 - (void) _setSource:(NSURL *) url {
8438 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8440 if (NSData *data = [NSURLConnection
8441 sendSynchronousRequest:[NSURLRequest
8443 cachePolicy:NSURLRequestUseProtocolCachePolicy
8447 returningResponse:NULL
8450 if (UIImage *image = [UIImage imageWithData:data])
8451 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8456 - (void) setSource:(Source *)source {
8457 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8459 origin_ = [source name];
8460 label_ = [source rooturi];
8462 [content_ setNeedsDisplay];
8464 url_ = [source iconURL];
8465 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8468 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8469 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8470 UIView *content([self contentView]);
8471 CGRect bounds([content bounds]);
8473 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8474 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8475 [content_ setBackgroundColor:[UIColor whiteColor]];
8476 [content addSubview:content_];
8478 [content_ setDelegate:self];
8479 [content_ setOpaque:YES];
8481 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8485 - (NSString *) accessibilityLabel {
8489 - (void) drawContentRect:(CGRect)rect {
8490 bool highlighted(highlighted_);
8491 float width(rect.size.width);
8495 rect.size = [(UIImage *) icon_ size];
8497 while (rect.size.width > 32 || rect.size.height > 32) {
8498 rect.size.width /= 2;
8499 rect.size.height /= 2;
8502 rect.origin.x = 25 - rect.size.width / 2;
8503 rect.origin.y = 25 - rect.size.height / 2;
8505 [icon_ drawInRect:rect];
8513 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 65) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8517 [label_ drawAtPoint:CGPointMake(48, 29) forWidth:(width - 65) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8522 /* Source Controller {{{ */
8523 @interface SourceController : FilteredPackageListController {
8524 _transient Source *source_;
8528 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8532 @implementation SourceController
8534 - (NSURL *) referrerURL {
8535 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sources/%@", UI_, [key_ stringByAddingPercentEscapesIncludingReserved]]];
8538 - (NSURL *) navigationURL {
8539 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8542 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8543 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8545 key_ = [source key];
8549 - (void) reloadData {
8550 source_ = [database_ sourceWithKey:key_];
8551 key_ = [source_ key];
8552 [self setObject:source_];
8554 [[self navigationItem] setTitle:[source_ label]];
8561 /* Sources Controller {{{ */
8562 @interface SourcesController : CyteViewController <
8563 UITableViewDataSource,
8566 _transient Database *database_;
8569 _H<UITableView, 2> list_;
8570 _H<NSMutableArray> sources_;
8574 _H<UIProgressHUD> hud_;
8577 //NSURLConnection *installer_;
8578 NSURLConnection *trivial_bz2_;
8579 NSURLConnection *trivial_gz_;
8580 //NSURLConnection *automatic_;
8585 - (id) initWithDatabase:(Database *)database;
8586 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8590 @implementation SourcesController
8592 - (void) _releaseConnection:(NSURLConnection *)connection {
8593 if (connection != nil) {
8594 [connection cancel];
8595 //[connection setDelegate:nil];
8596 [connection release];
8601 //[self _releaseConnection:installer_];
8602 [self _releaseConnection:trivial_gz_];
8603 [self _releaseConnection:trivial_bz2_];
8604 //[self _releaseConnection:automatic_];
8609 - (NSURL *) navigationURL {
8610 return [NSURL URLWithString:@"cydia://sources"];
8613 - (void) viewDidAppear:(BOOL)animated {
8614 [super viewDidAppear:animated];
8615 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8618 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8622 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8626 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8627 return [sources_ count];
8630 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8631 @synchronized (database_) {
8632 if ([database_ era] != era_)
8635 NSUInteger index([indexPath row]);
8636 return index < [sources_ count] ? [sources_ objectAtIndex:index] : nil;
8639 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8640 static NSString *cellIdentifier = @"SourceCell";
8642 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8643 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8644 [cell setSource:[self sourceAtIndexPath:indexPath]];
8645 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8650 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8651 Source *source = [self sourceAtIndexPath:indexPath];
8652 if (source == nil) return;
8654 SourceController *controller = [[[SourceController alloc]
8655 initWithDatabase:database_
8659 [controller setDelegate:delegate_];
8661 [[self navigationController] pushViewController:controller animated:YES];
8664 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8665 Source *source = [self sourceAtIndexPath:indexPath];
8666 return [source record] != nil;
8669 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8670 if (editingStyle == UITableViewCellEditingStyleDelete) {
8671 Source *source = [self sourceAtIndexPath:indexPath];
8672 if (source == nil) return;
8674 [Sources_ removeObjectForKey:[source key]];
8675 [delegate_ _saveConfig];
8676 [delegate_ reloadDataWithInvocation:nil];
8681 [delegate_ addTrivialSource:href_];
8684 [delegate_ syncData];
8687 - (NSString *) getWarning {
8688 NSString *href(href_);
8689 NSRange colon([href rangeOfString:@"://"]);
8690 if (colon.location != NSNotFound)
8691 href = [href substringFromIndex:(colon.location + 3)];
8692 href = [href stringByAddingPercentEscapes];
8693 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8695 NSURL *url([NSURL URLWithString:href]);
8697 NSStringEncoding encoding;
8698 NSError *error(nil);
8700 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8701 return [warning length] == 0 ? nil : warning;
8705 - (void) _endConnection:(NSURLConnection *)connection {
8706 // XXX: the memory management in this method is horribly awkward
8708 NSURLConnection **field = NULL;
8709 if (connection == trivial_bz2_)
8710 field = &trivial_bz2_;
8711 else if (connection == trivial_gz_)
8712 field = &trivial_gz_;
8713 _assert(field != NULL);
8714 [connection release];
8718 trivial_bz2_ == nil &&
8721 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8723 [delegate_ releaseNetworkActivityIndicator];
8725 [delegate_ removeProgressHUD:hud_];
8729 if (warning != nil) {
8730 UIAlertView *alert = [[[UIAlertView alloc]
8731 initWithTitle:UCLocalize("SOURCE_WARNING")
8734 cancelButtonTitle:UCLocalize("CANCEL")
8736 UCLocalize("ADD_ANYWAY"),
8740 [alert setContext:@"warning"];
8741 [alert setNumberOfRows:1];
8744 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8750 } else if (error_ != nil) {
8751 UIAlertView *alert = [[[UIAlertView alloc]
8752 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8753 message:[error_ localizedDescription]
8755 cancelButtonTitle:UCLocalize("OK")
8756 otherButtonTitles:nil
8759 [alert setContext:@"urlerror"];
8764 UIAlertView *alert = [[[UIAlertView alloc]
8765 initWithTitle:UCLocalize("NOT_REPOSITORY")
8766 message:UCLocalize("NOT_REPOSITORY_EX")
8768 cancelButtonTitle:UCLocalize("OK")
8769 otherButtonTitles:nil
8772 [alert setContext:@"trivial"];
8782 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8783 switch ([response statusCode]) {
8789 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8790 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8792 [self _endConnection:connection];
8795 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8796 [self _endConnection:connection];
8799 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8800 NSURL *url([NSURL URLWithString:href]);
8802 NSMutableURLRequest *request = [NSMutableURLRequest
8804 cachePolicy:NSURLRequestUseProtocolCachePolicy
8808 [request setHTTPMethod:method];
8810 if (Machine_ != NULL)
8811 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8813 if (UniqueID_ != nil)
8814 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8816 if ([url isCydiaSecure]) {
8817 if (UniqueID_ != nil)
8818 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8821 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8824 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8825 NSString *context([alert context]);
8827 if ([context isEqualToString:@"source"]) {
8830 NSString *href = [[alert textField] text];
8832 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8834 if (![href hasSuffix:@"/"])
8835 href_ = [href stringByAppendingString:@"/"];
8839 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8840 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8841 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8845 // XXX: this is stupid
8846 hud_ = [delegate_ addProgressHUD];
8847 [hud_ setText:UCLocalize("VERIFYING_URL")];
8848 [delegate_ retainNetworkActivityIndicator];
8857 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8858 } else if ([context isEqualToString:@"trivial"])
8859 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8860 else if ([context isEqualToString:@"urlerror"])
8861 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8862 else if ([context isEqualToString:@"warning"]) {
8865 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8874 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8879 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8880 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8881 [list_ setRowHeight:53];
8882 [(UITableView *) list_ setDataSource:self];
8883 [list_ setDelegate:self];
8884 [self setView:list_];
8887 - (void) viewDidLoad {
8888 [super viewDidLoad];
8890 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8891 [self updateButtonsForEditingStatusAnimated:NO];
8894 - (void) viewWillAppear:(BOOL)animated {
8895 [super viewWillAppear:animated];
8897 [list_ setEditing:NO];
8898 [self updateButtonsForEditingStatusAnimated:NO];
8901 - (void) releaseSubviews {
8906 [super releaseSubviews];
8909 - (id) initWithDatabase:(Database *)database {
8910 if ((self = [super init]) != nil) {
8911 database_ = database;
8915 - (void) reloadData {
8918 @synchronized (database_) {
8919 era_ = [database_ era];
8921 sources_ = [NSMutableArray arrayWithCapacity:16];
8922 [sources_ addObjectsFromArray:[database_ sources]];
8924 [sources_ sortUsingSelector:@selector(compareByName:)];
8927 int count([sources_ count]);
8929 for (int i = 0; i != count; i++) {
8930 if ([[sources_ objectAtIndex:i] record] == nil)
8938 - (void) showAddSourcePrompt {
8939 UIAlertView *alert = [[[UIAlertView alloc]
8940 initWithTitle:UCLocalize("ENTER_APT_URL")
8943 cancelButtonTitle:UCLocalize("CANCEL")
8945 UCLocalize("ADD_SOURCE"),
8949 [alert setContext:@"source"];
8951 [alert setNumberOfRows:1];
8952 [alert addTextFieldWithValue:@"http://" label:@""];
8954 UITextInputTraits *traits = [[alert textField] textInputTraits];
8955 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8956 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8957 [traits setKeyboardType:UIKeyboardTypeURL];
8958 // XXX: UIReturnKeyDone
8959 [traits setReturnKeyType:UIReturnKeyNext];
8964 - (void) addButtonClicked {
8965 [self showAddSourcePrompt];
8968 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8969 BOOL editing([list_ isEditing]);
8971 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8972 initWithTitle:UCLocalize("ADD")
8973 style:UIBarButtonItemStylePlain
8975 action:@selector(addButtonClicked)
8976 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8978 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8979 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8980 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8982 action:@selector(editButtonClicked)
8983 ] autorelease] animated:animated];
8985 if (IsWildcat_ && !editing)
8986 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8987 initWithTitle:UCLocalize("SETTINGS")
8988 style:UIBarButtonItemStylePlain
8990 action:@selector(settingsButtonClicked)
8994 - (void) settingsButtonClicked {
8995 [delegate_ showSettings];
8998 - (void) editButtonClicked {
8999 [list_ setEditing:![list_ isEditing] animated:YES];
9000 [self updateButtonsForEditingStatusAnimated:YES];
9006 /* Settings Controller {{{ */
9007 @interface SettingsController : CyteViewController <
9008 UITableViewDataSource,
9011 _transient Database *database_;
9012 // XXX: ok, "roledelegate_"?...
9013 _transient id roledelegate_;
9014 _H<UITableView, 2> table_;
9015 _H<UISegmentedControl> segment_;
9016 _H<UIView> container_;
9019 - (void) showDoneButton;
9020 - (void) resizeSegmentedControl;
9024 @implementation SettingsController
9027 table_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
9028 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9029 [table_ setDelegate:self];
9030 [(UITableView *) table_ setDataSource:self];
9031 [self setView:table_];
9033 NSArray *items = [NSArray arrayWithObjects:
9035 UCLocalize("HACKER"),
9036 UCLocalize("DEVELOPER"),
9038 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
9039 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
9040 [container_ addSubview:segment_];
9043 - (void) viewDidLoad {
9044 [super viewDidLoad];
9046 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
9049 if ([Role_ isEqualToString:@"User"]) index = 0;
9050 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
9051 if ([Role_ isEqualToString:@"Developer"]) index = 2;
9053 [segment_ setSelectedSegmentIndex:index];
9054 [self showDoneButton];
9057 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
9058 [self resizeSegmentedControl];
9061 - (void) releaseSubviews {
9066 [super releaseSubviews];
9069 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
9070 if ((self = [super init]) != nil) {
9071 database_ = database;
9072 roledelegate_ = delegate;
9076 - (void) resizeSegmentedControl {
9077 CGFloat width = [[self view] frame].size.width;
9078 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
9081 - (void) viewWillAppear:(BOOL)animated {
9082 [super viewWillAppear:animated];
9083 [self resizeSegmentedControl];
9086 - (void) viewDidAppear:(BOOL)animated {
9087 [super viewDidAppear:animated];
9088 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
9089 [self resizeSegmentedControl];
9092 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
9093 [self resizeSegmentedControl];
9096 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
9097 [self resizeSegmentedControl];
9101 NSString *role(nil);
9103 switch ([segment_ selectedSegmentIndex]) {
9104 case 0: role = @"User"; break;
9105 case 1: role = @"Hacker"; break;
9106 case 2: role = @"Developer"; break;
9111 if (![role isEqualToString:Role_]) {
9112 bool rolling(Role_ == nil);
9115 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
9119 [Metadata_ setObject:Settings_ forKey:@"Settings"];
9123 [roledelegate_ loadData];
9125 [roledelegate_ updateData];
9129 - (void) segmentChanged:(UISegmentedControl *)control {
9130 [self showDoneButton];
9133 - (void) saveAndClose {
9136 [[self navigationItem] setRightBarButtonItem:nil];
9137 [[self navigationController] dismissModalViewControllerAnimated:YES];
9140 - (void) doneButtonClicked {
9141 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
9142 [spinner startAnimating];
9143 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
9144 [[self navigationItem] setRightBarButtonItem:spinItem];
9146 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
9149 - (void) showDoneButton {
9150 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
9151 initWithTitle:UCLocalize("DONE")
9152 style:UIBarButtonItemStyleDone
9154 action:@selector(doneButtonClicked)
9155 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
9158 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
9159 // XXX: For not having a single cell in the table, this sure is a lot of sections.
9163 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
9167 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
9168 return nil; // This method is required by the protocol.
9171 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
9173 return UCLocalize("ROLE_EX");
9175 return [NSString stringWithFormat:
9176 @"%@: %@\n%@: %@\n%@: %@",
9177 UCLocalize("USER"), UCLocalize("USER_EX"),
9178 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
9179 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
9184 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
9185 return section == 3 ? 44.0f : 0;
9188 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
9189 return section == 3 ? container_ : nil;
9192 - (void) reloadData {
9195 [table_ reloadData];
9200 /* Stash Controller {{{ */
9201 @interface StashController : CyteViewController {
9202 _H<UIActivityIndicatorView> spinner_;
9203 _H<UILabel> status_;
9204 _H<UILabel> caption_;
9209 @implementation StashController
9212 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
9213 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
9214 [self setView:view];
9216 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
9218 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
9219 CGRect spinrect = [spinner_ frame];
9220 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
9221 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
9222 [spinner_ setFrame:spinrect];
9223 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
9224 [view addSubview:spinner_];
9225 [spinner_ startAnimating];
9228 captrect.size.width = [[self view] frame].size.width;
9229 captrect.size.height = 40.0f;
9230 captrect.origin.x = 0;
9231 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
9232 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
9233 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
9234 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9235 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
9236 [caption_ setTextColor:[UIColor whiteColor]];
9237 [caption_ setBackgroundColor:[UIColor clearColor]];
9238 [caption_ setShadowColor:[UIColor blackColor]];
9239 [caption_ setTextAlignment:UITextAlignmentCenter];
9240 [view addSubview:caption_];
9243 statusrect.size.width = [[self view] frame].size.width;
9244 statusrect.size.height = 30.0f;
9245 statusrect.origin.x = 0;
9246 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
9247 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
9248 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9249 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
9250 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
9251 [status_ setTextColor:[UIColor whiteColor]];
9252 [status_ setBackgroundColor:[UIColor clearColor]];
9253 [status_ setShadowColor:[UIColor blackColor]];
9254 [status_ setTextAlignment:UITextAlignmentCenter];
9255 [view addSubview:status_];
9258 - (void) releaseSubviews {
9263 [super releaseSubviews];
9269 @interface CYURLCache : SDURLCache {
9274 @implementation CYURLCache
9276 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
9279 else if ([event isEqualToString:@"no-cache"])
9281 else if ([event isEqualToString:@"store"])
9283 else if ([event isEqualToString:@"invalid"])
9285 else if ([event isEqualToString:@"memory"])
9287 else if ([event isEqualToString:@"disk"])
9289 else if ([event isEqualToString:@"miss"])
9292 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
9296 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
9297 if (NSURLResponse *response = [cached response])
9298 if (NSString *mime = [response MIMEType])
9299 if ([mime isEqualToString:@"text/cache-manifest"]) {
9300 NSURL *url([response URL]);
9303 NSLog(@"###: %@", [url absoluteString]);
9306 @synchronized (HostConfig_) {
9307 [CachedURLs_ addObject:url];
9311 [super storeCachedResponse:cached forRequest:request];
9316 @interface Cydia : UIApplication <
9317 ConfirmationControllerDelegate,
9320 UINavigationControllerDelegate,
9321 UITabBarControllerDelegate
9323 _H<UIWindow> window_;
9324 _H<CYTabBarController> tabbar_;
9325 _H<CydiaLoadingViewController> emulated_;
9327 _H<NSMutableArray> essential_;
9328 _H<NSMutableArray> broken_;
9330 Database *database_;
9332 _H<NSURL> starturl_;
9337 _H<StashController> stash_;
9346 @implementation Cydia
9348 - (void) lockSuspend {
9349 if (locked_++ == 0) {
9350 if ($SBSSetInterceptsMenuButtonForever != NULL)
9351 (*$SBSSetInterceptsMenuButtonForever)(true);
9355 - (void) unlockSuspend {
9356 if (--locked_ == 0) {
9357 if ($SBSSetInterceptsMenuButtonForever != NULL)
9358 (*$SBSSetInterceptsMenuButtonForever)(false);
9362 - (void) beginUpdate {
9363 [tabbar_ beginUpdate];
9367 return [tabbar_ updating];
9371 if ([broken_ count] != 0) {
9372 int count = [broken_ count];
9374 UIAlertView *alert = [[[UIAlertView alloc]
9375 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9376 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9378 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9380 UCLocalize("TEMPORARY_IGNORE"),
9384 [alert setContext:@"fixhalf"];
9385 [alert setNumberOfRows:2];
9387 } else if (!Ignored_ && [essential_ count] != 0) {
9388 int count = [essential_ count];
9390 UIAlertView *alert = [[[UIAlertView alloc]
9391 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9392 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9394 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9396 UCLocalize("UPGRADE_ESSENTIAL"),
9397 UCLocalize("COMPLETE_UPGRADE"),
9401 [alert setContext:@"upgrade"];
9406 - (void) returnToCydia {
9410 - (void) _saveConfig {
9411 @synchronized (database_) {
9418 NSString *error(nil);
9420 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9422 NSError *error(nil);
9423 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9424 NSLog(@"failure to save metadata data: %@", error);
9429 NSLog(@"failure to serialize metadata: %@", error);
9433 CydiaWriteSources();
9436 // Navigation controller for the queuing badge.
9437 - (UINavigationController *) queueNavigationController {
9438 NSArray *controllers = [tabbar_ viewControllers];
9439 return [controllers objectAtIndex:3];
9442 - (void) unloadData {
9443 [tabbar_ unloadData];
9446 - (void) _updateData {
9450 UINavigationController *navigation = [self queueNavigationController];
9452 id queuedelegate = nil;
9453 if ([[navigation viewControllers] count] > 0)
9454 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9456 [queuedelegate queueStatusDidChange];
9457 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9460 - (void) _refreshIfPossible:(NSDate *)update {
9461 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9463 bool recently = false;
9464 if (update != nil) {
9465 NSTimeInterval interval([update timeIntervalSinceNow]);
9466 if (interval <= 0 && interval > -(15*60))
9470 // Don't automatic refresh if:
9471 // - We already refreshed recently.
9472 // - We already auto-refreshed this launch.
9473 // - Auto-refresh is disabled.
9474 // - Cydia's server is not reachable
9475 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9476 // If we are cancelling, we need to make sure it knows it's already loaded.
9479 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9481 // We are going to load, so remember that.
9484 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9490 - (void) refreshIfPossible {
9491 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9494 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9495 @synchronized (self) {
9496 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9497 [hud setText:UCLocalize("RELOADING_DATA")];
9499 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9503 [essential_ removeAllObjects];
9504 [broken_ removeAllObjects];
9506 NSArray *packages([database_ packages]);
9507 for (Package *package in packages) {
9509 [broken_ addObject:package];
9510 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9511 if ([package essential] && [package installed] != nil)
9512 [essential_ addObject:package];
9517 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9520 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9521 [changesItem setBadgeValue:badge];
9522 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9523 [self setApplicationIconBadgeNumber:changes];
9526 [changesItem setBadgeValue:nil];
9527 [changesItem setAnimatedBadge:NO];
9528 [self setApplicationIconBadgeNumber:0];
9534 [self removeProgressHUD:hud];
9537 - (void) updateData {
9541 - (void) updateDataAndLoad {
9543 if ([database_ progressDelegate] == nil)
9549 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9552 - (void) disemulate {
9553 if (emulated_ == nil)
9556 [window_ addSubview:[tabbar_ view]];
9557 [[emulated_ view] removeFromSuperview];
9559 [window_ setUserInteractionEnabled:YES];
9562 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9563 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9565 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9567 UIViewController *parent;
9568 if (emulated_ == nil)
9577 [parent presentModalViewController:navigation animated:YES];
9580 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9581 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9583 if (navigation != nil)
9584 [navigation pushViewController:progress animated:YES];
9586 [self presentModalViewController:progress force:YES];
9588 [progress invoke:invocation withTitle:title];
9592 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9593 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9596 - (void) repairWithInvocation:(NSInvocation *)invocation {
9598 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9602 - (void) repairWithSelector:(SEL)selector {
9603 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9606 - (void) reloadData {
9607 [self reloadDataWithInvocation:nil];
9608 if ([database_ progressDelegate] == nil)
9614 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9617 - (void) addSource:(NSDictionary *) source {
9618 CydiaAddSource(source);
9621 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9622 CydiaAddSource(href, distribution, sections);
9625 - (void) addTrivialSource:(NSString *)href {
9626 CydiaAddSource(href, @"./");
9629 - (void) updateValues {
9634 pkgProblemResolver *resolver = [database_ resolver];
9636 resolver->InstallProtect();
9637 if (!resolver->Resolve(true))
9642 // XXX: this is a really crappy way of doing this.
9643 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9644 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9645 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9646 if ([tabbar_ updating])
9647 [tabbar_ cancelUpdate];
9649 if (![database_ prepare])
9652 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9653 [page setDelegate:self];
9654 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9657 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9658 [tabbar_ presentModalViewController:confirm_ animated:YES];
9664 @synchronized (self) {
9669 - (void) clearPackage:(Package *)package {
9670 @synchronized (self) {
9677 - (void) installPackages:(NSArray *)packages {
9678 @synchronized (self) {
9679 for (Package *package in packages)
9686 - (void) installPackage:(Package *)package {
9687 @synchronized (self) {
9694 - (void) removePackage:(Package *)package {
9695 @synchronized (self) {
9702 - (void) distUpgrade {
9703 @synchronized (self) {
9704 if (![database_ upgrade])
9712 system("su -c /usr/bin/uicache mobile");
9717 UIProgressHUD *hud([self addProgressHUD]);
9718 [hud setText:UCLocalize("LOADING")];
9719 [self yieldToSelector:@selector(_uicache)];
9720 [self removeProgressHUD:hud];
9724 [database_ perform];
9725 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9726 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9729 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9732 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9733 [self unlockSuspend];
9736 - (void) showSettings {
9737 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9740 - (void) retainNetworkActivityIndicator {
9741 if (activity_++ == 0)
9742 [self setNetworkActivityIndicatorVisible:YES];
9745 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9749 - (void) releaseNetworkActivityIndicator {
9750 if (--activity_ == 0)
9751 [self setNetworkActivityIndicatorVisible:NO];
9754 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9759 - (void) cancelAndClear:(bool)clear {
9760 @synchronized (self) {
9772 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9773 NSString *context([alert context]);
9775 if ([context isEqualToString:@"conffile"]) {
9776 FILE *input = [database_ input];
9777 if (button == [alert cancelButtonIndex])
9778 fprintf(input, "N\n");
9779 else if (button == [alert firstOtherButtonIndex])
9780 fprintf(input, "Y\n");
9783 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9784 } else if ([context isEqualToString:@"fixhalf"]) {
9785 if (button == [alert cancelButtonIndex]) {
9786 @synchronized (self) {
9787 for (Package *broken in (id) broken_) {
9790 NSString *id = [broken id];
9791 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9792 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9793 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9794 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9800 } else if (button == [alert firstOtherButtonIndex]) {
9801 [broken_ removeAllObjects];
9805 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9806 } else if ([context isEqualToString:@"upgrade"]) {
9807 if (button == [alert firstOtherButtonIndex]) {
9808 @synchronized (self) {
9809 for (Package *essential in (id) essential_)
9810 [essential install];
9815 } else if (button == [alert firstOtherButtonIndex] + 1) {
9817 } else if (button == [alert cancelButtonIndex]) {
9821 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9825 - (void) system:(NSString *)command {
9826 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9829 system([command UTF8String]);
9835 - (void) applicationWillSuspend {
9837 [super applicationWillSuspend];
9840 - (BOOL) isSafeToSuspend {
9843 NSLog(@"isSafeToSuspend: locked_ != 0");
9848 // Use external process status API internally.
9849 // This is probably a really bad idea.
9850 // XXX: what is the point of this? does this solve anything at all?
9851 uint64_t status = 0;
9853 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9854 notify_get_state(notify_token, &status);
9855 notify_cancel(notify_token);
9860 NSLog(@"isSafeToSuspend: status != 0");
9866 NSLog(@"isSafeToSuspend: -> true");
9871 - (void) applicationSuspend:(__GSEvent *)event {
9872 if ([self isSafeToSuspend])
9873 [super applicationSuspend:event];
9876 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9877 if ([self isSafeToSuspend])
9878 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9881 - (void) _setSuspended:(BOOL)value {
9882 if ([self isSafeToSuspend])
9883 [super _setSuspended:value];
9886 - (UIProgressHUD *) addProgressHUD {
9887 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9888 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9890 [window_ setUserInteractionEnabled:NO];
9892 UIViewController *target(tabbar_);
9893 if (UIViewController *modal = [target modalViewController])
9896 [hud showInView:[target view]];
9902 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9903 [self unlockSuspend];
9905 [hud removeFromSuperview];
9906 [window_ setUserInteractionEnabled:YES];
9909 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9910 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9913 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9914 NSString *scheme([[url scheme] lowercaseString]);
9915 if ([[url absoluteString] length] <= [scheme length] + 3)
9917 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9918 NSArray *components([path componentsSeparatedByString:@"/"]);
9920 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9921 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9922 if (controller != nil)
9923 [controller setDelegate:self];
9927 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9930 NSString *base([components objectAtIndex:0]);
9932 CyteViewController *controller = nil;
9934 if ([base isEqualToString:@"url"]) {
9935 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9936 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9937 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9938 } else if (!external && [components count] == 1) {
9939 if ([base isEqualToString:@"manage"]) {
9940 controller = [[[ManageController alloc] init] autorelease];
9943 if ([base isEqualToString:@"storage"]) {
9944 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9947 if ([base isEqualToString:@"sources"]) {
9948 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9951 if ([base isEqualToString:@"home"]) {
9952 controller = [[[HomeController alloc] init] autorelease];
9955 if ([base isEqualToString:@"sections"]) {
9956 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9959 if ([base isEqualToString:@"search"]) {
9960 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9963 if ([base isEqualToString:@"changes"]) {
9964 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9967 if ([base isEqualToString:@"installed"]) {
9968 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9970 } else if ([components count] == 2) {
9971 NSString *argument = [components objectAtIndex:1];
9973 if ([base isEqualToString:@"package"]) {
9974 controller = [self pageForPackage:argument withReferrer:referrer];
9977 if (!external && [base isEqualToString:@"search"]) {
9978 controller = [[[SearchController alloc] initWithDatabase:database_ query:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9981 if (!external && [base isEqualToString:@"sections"]) {
9982 if ([argument isEqualToString:@"all"])
9984 controller = [[[SectionController alloc] initWithDatabase:database_ section:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9987 if (!external && [base isEqualToString:@"sources"]) {
9988 if ([argument isEqualToString:@"add"]) {
9989 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9990 [(SourcesController *)controller showAddSourcePrompt];
9992 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9993 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9997 if (!external && [base isEqualToString:@"launch"]) {
9998 [self launchApplicationWithIdentifier:argument suspended:NO];
10001 } else if (!external && [components count] == 3) {
10002 NSString *arg1 = [components objectAtIndex:1];
10003 NSString *arg2 = [components objectAtIndex:2];
10005 if ([base isEqualToString:@"package"]) {
10006 if ([arg2 isEqualToString:@"settings"]) {
10007 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
10008 } else if ([arg2 isEqualToString:@"files"]) {
10009 if (Package *package = [database_ packageWithName:arg1]) {
10010 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
10011 [(FileTable *)controller setPackage:package];
10017 [controller setDelegate:self];
10021 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
10022 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
10025 [tabbar_ setUnselectedViewController:page];
10027 return page != nil;
10030 - (void) applicationOpenURL:(NSURL *)url {
10031 [super applicationOpenURL:url];
10036 [self openCydiaURL:url forExternal:YES];
10039 - (void) applicationWillResignActive:(UIApplication *)application {
10040 // Stop refreshing if you get a phone call or lock the device.
10041 if ([tabbar_ updating])
10042 [tabbar_ cancelUpdate];
10044 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
10045 [super applicationWillResignActive:application];
10048 - (void) saveState {
10049 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
10050 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
10051 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
10054 [self _saveConfig];
10057 - (void) applicationWillTerminate:(UIApplication *)application {
10061 - (void) setConfigurationData:(NSString *)data {
10062 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
10064 if (!conffile_r(data)) {
10065 lprintf("E:invalid conffile\n");
10069 NSString *ofile = conffile_r[1];
10070 //NSString *nfile = conffile_r[2];
10072 UIAlertView *alert = [[[UIAlertView alloc]
10073 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
10074 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
10076 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
10078 UCLocalize("ACCEPT_NEW_COPY"),
10079 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
10083 [alert setContext:@"conffile"];
10084 [alert setNumberOfRows:2];
10088 - (void) addStashController {
10089 [self lockSuspend];
10090 stash_ = [[[StashController alloc] init] autorelease];
10091 [window_ addSubview:[stash_ view]];
10094 - (void) removeStashController {
10095 [[stash_ view] removeFromSuperview];
10097 [self unlockSuspend];
10101 [self setIdleTimerDisabled:YES];
10103 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
10104 UpdateExternalStatus(1);
10105 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
10106 UpdateExternalStatus(0);
10108 [self removeStashController];
10110 pid_t pid(ExecFork());
10112 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
10113 perror("launchctl stop");
10120 - (void) setupViewControllers {
10121 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
10123 NSMutableArray *items([NSMutableArray arrayWithObjects:
10124 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
10125 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
10126 [[[UITabBarItem alloc] initWithTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES")) image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
10127 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
10131 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
10132 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10134 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10137 NSMutableArray *controllers([NSMutableArray array]);
10138 for (UITabBarItem *item in items) {
10139 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
10140 [controller setTabBarItem:item];
10141 [controllers addObject:controller];
10143 [tabbar_ setViewControllers:controllers];
10145 [tabbar_ setUpdateDelegate:self];
10148 - (void) _sendMemoryWarningNotification {
10149 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
10150 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
10152 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
10155 - (void) _sendMemoryWarningNotifications {
10157 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
10163 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
10165 [[NSURLCache sharedURLCache] removeAllCachedResponses];
10168 - (void) applicationDidFinishLaunching:(id)unused {
10169 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
10172 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
10173 [self setApplicationSupportsShakeToEdit:NO];
10175 @synchronized (HostConfig_) {
10176 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
10179 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
10180 initWithMemoryCapacity:524288
10181 diskCapacity:10485760
10182 diskPath:[NSString stringWithFormat:@"%@/SDURLCache", Cache_]
10185 [CydiaWebViewController _initialize];
10187 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
10189 // this would disallow http{,s} URLs from accessing this data
10190 //[WebView registerURLSchemeAsLocal:@"cydia"];
10192 Font12_ = [UIFont systemFontOfSize:12];
10193 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
10194 Font14_ = [UIFont systemFontOfSize:14];
10195 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
10196 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
10198 essential_ = [NSMutableArray arrayWithCapacity:4];
10199 broken_ = [NSMutableArray arrayWithCapacity:4];
10201 // XXX: I really need this thing... like, seriously... I'm sorry
10202 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
10204 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
10205 [window_ orderFront:self];
10206 [window_ makeKey:self];
10207 [window_ setHidden:NO];
10209 if (false) stash: {
10210 [self addStashController];
10211 // XXX: this would be much cleaner as a yieldToSelector:
10212 // that way the removeStashController could happen right here inline
10213 // we also could no longer require the useless stash_ field anymore
10214 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
10219 int error(stat("/", &root));
10220 _assert(error != -1);
10222 #define Stash_(path) do { \
10223 struct stat folder; \
10224 int error(lstat((path), &folder)); \
10225 if (error != -1 && ( \
10226 folder.st_dev == root.st_dev && \
10227 S_ISDIR(folder.st_mode) \
10228 ) || error == -1 && ( \
10229 errno == ENOENT || \
10234 Stash_("/Applications");
10235 Stash_("/Library/Ringtones");
10236 Stash_("/Library/Wallpaper");
10237 //Stash_("/usr/bin");
10238 Stash_("/usr/include");
10239 Stash_("/usr/lib/pam");
10240 Stash_("/usr/libexec");
10241 Stash_("/usr/share");
10242 //Stash_("/var/lib");
10244 database_ = [Database sharedInstance];
10245 [database_ setDelegate:self];
10247 [window_ setUserInteractionEnabled:NO];
10248 [self setupViewControllers];
10250 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
10251 [window_ addSubview:[emulated_ view]];
10253 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
10257 - (NSArray *) defaultStartPages {
10258 NSMutableArray *standard = [NSMutableArray array];
10259 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
10260 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
10261 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
10263 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
10265 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
10266 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
10268 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10272 - (void) loadData {
10274 if (Role_ == nil) {
10275 [window_ setUserInteractionEnabled:YES];
10276 [self showSettings];
10279 if ([emulated_ modalViewController] != nil)
10280 [emulated_ dismissModalViewControllerAnimated:YES];
10281 [window_ setUserInteractionEnabled:NO];
10284 [self reloadDataWithInvocation:nil];
10285 [self refreshIfPossible];
10290 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
10291 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
10292 int standardIndex = 0;
10293 NSArray *standard = [self defaultStartPages];
10300 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
10301 if (valid && closed != nil) {
10302 NSTimeInterval interval([closed timeIntervalSinceNow]);
10303 // XXX: Is 30 minutes the optimal time here?
10304 if (interval <= -(30*60))
10308 if (valid && [saved count] != [standard count])
10312 for (unsigned int i = 0; i < [standard count]; i++) {
10313 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10314 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10315 // but it's good enough for now.
10316 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10323 NSArray *items = nil;
10325 [tabbar_ setSelectedIndex:savedIndex];
10328 [tabbar_ setSelectedIndex:standardIndex];
10332 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10333 NSArray *stack = [items objectAtIndex:tab];
10334 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10335 NSMutableArray *current = [NSMutableArray array];
10337 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10338 NSString *addr = [stack objectAtIndex:nav];
10339 NSURL *url = [NSURL URLWithString:addr];
10340 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10342 [current addObject:page];
10345 [navigation setViewControllers:current];
10348 // (Try to) show the startup URL.
10349 if (starturl_ != nil) {
10350 [self openCydiaURL:starturl_ forExternal:NO];
10355 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10356 if (item != nil && IsWildcat_) {
10357 [sheet showFromBarButtonItem:item animated:YES];
10359 [sheet showInView:window_];
10363 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10364 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10365 [progress setTitle:task];
10366 [progress addProgressEvent:event];
10369 - (void) addProgressEventForTask:(NSArray *)data {
10370 CydiaProgressEvent *event([data objectAtIndex:0]);
10371 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10372 [self addProgressEvent:event forTask:task];
10375 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10376 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10382 id Alloc_(id self, SEL selector) {
10383 id object = alloc_(self, selector);
10384 lprintf("[%s]A-%p\n", self->isa->name, object);
10389 id Dealloc_(id self, SEL selector) {
10390 id object = dealloc_(self, selector);
10391 lprintf("[%s]D-%p\n", self->isa->name, object);
10395 static NSSet *MobilizedFiles_;
10397 static NSURL *MobilizeURL(NSURL *url) {
10398 NSString *path([url path]);
10399 if ([path hasPrefix:@"/var/root/"]) {
10400 NSString *file([path substringFromIndex:10]);
10401 if ([MobilizedFiles_ containsObject:file])
10402 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10408 Class $CFXPreferencesPropertyListSource;
10409 @class CFXPreferencesPropertyListSource;
10411 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10412 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10413 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10414 url = MobilizeURL(url);
10415 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10416 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10422 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10423 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10424 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10425 url = MobilizeURL(url);
10426 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10427 //NSLog(@"%@ %@", [url absoluteString], value);
10433 Class $NSURLConnection;
10435 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10436 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10438 NSURL *url([copy URL]);
10440 NSString *host([url host]);
10441 NSString *scheme([[url scheme] lowercaseString]);
10443 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10445 @synchronized (HostConfig_) {
10446 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10447 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10448 [copy setHTTPShouldUsePipelining:YES];
10450 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10451 if ([control isEqualToString:@"max-age=0"])
10452 if ([CachedURLs_ containsObject:url]) {
10454 NSLog(@"~~~: %@", url);
10457 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10459 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10460 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10461 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10465 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10471 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10472 CGSize size([[UIScreen mainScreen] bounds].size);
10473 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10474 if ([$WAKWindow hasLandscapeOrientation])
10475 std::swap(size.width, size.height);*/
10479 Class $NSUserDefaults;
10481 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10482 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10483 return [NSString stringWithFormat:@"%@/LocalStorage", Cache_];
10484 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10487 int main(int argc, char *argv[]) {
10488 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10492 UpdateExternalStatus(0);
10494 if (Class $UIDevice = objc_getClass("UIDevice")) {
10495 UIDevice *device([$UIDevice currentDevice]);
10496 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10498 IsWildcat_ = false;
10500 UIScreen *screen([UIScreen mainScreen]);
10501 if ([screen respondsToSelector:@selector(scale)])
10502 ScreenScale_ = [screen scale];
10506 UIDevice *device([UIDevice currentDevice]);
10507 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10508 Idiom_ = @"iphone";
10510 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10511 if (idiom == UIUserInterfaceIdiomPhone)
10512 Idiom_ = @"iphone";
10513 else if (idiom == UIUserInterfaceIdiomPad)
10516 NSLog(@"unknown UIUserInterfaceIdiom!");
10519 Pcre pattern("^([0-9]+\\.[0-9]+)");
10521 if (pattern([device systemVersion]))
10522 Firmware_ = pattern[1];
10523 if (pattern(Cydia_))
10524 Major_ = pattern[1];
10526 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10528 HostConfig_ = [[[NSObject alloc] init] autorelease];
10529 @synchronized (HostConfig_) {
10530 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10531 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10532 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10533 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10534 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10537 NSString *ui(@"ui/ios");
10539 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10540 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10541 UI_ = CydiaURL(ui);
10543 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10545 MobilizedFiles_ = [NSMutableSet setWithObjects:
10546 @"Library/Preferences/com.apple.Accessibility.plist",
10547 @"Library/Preferences/com.apple.preferences.sounds.plist",
10550 /* Library Hacks {{{ */
10551 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10553 $WAKWindow = objc_getClass("WAKWindow");
10554 if ($WAKWindow != NULL)
10555 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10556 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10558 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10560 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10561 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10562 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10563 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10566 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10567 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10568 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10569 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10572 $NSURLConnection = objc_getClass("NSURLConnection");
10573 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10574 if (NSURLConnection$init$ != NULL) {
10575 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10576 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10579 $NSUserDefaults = objc_getClass("NSUserDefaults");
10580 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10581 if (NSUserDefaults$objectForKey$ != NULL) {
10582 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10583 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10586 /* Set Locale {{{ */
10587 Locale_ = CFLocaleCopyCurrent();
10588 Languages_ = [NSLocale preferredLanguages];
10590 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10591 //NSLog(@"%@", [Languages_ description]);
10594 if (Locale_ != NULL)
10595 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10596 else if (Languages_ != nil && [Languages_ count] != 0)
10597 lang = [[Languages_ objectAtIndex:0] UTF8String];
10599 // XXX: consider just setting to C and then falling through?
10602 if (lang != NULL) {
10603 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10604 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10607 NSLog(@"Setting Language: %s", lang);
10609 if (lang != NULL) {
10610 setenv("LANG", lang, true);
10611 std::setlocale(LC_ALL, lang);
10615 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10617 /* Parse Arguments {{{ */
10618 bool substrate(false);
10624 for (int argi(1); argi != argc; ++argi)
10625 if (strcmp(argv[argi], "--") == 0) {
10627 argv[argi] = argv[0];
10633 for (int argi(1); argi != arge; ++argi)
10634 if (strcmp(args[argi], "--substrate") == 0)
10637 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10641 App_ = [[NSBundle mainBundle] bundlePath];
10647 if (access("/var/mobile/Library/Keyboard/UserDictionary.sqlite", F_OK) == 0)
10648 system("mkdir -p /var/root/Library/Keyboard; cp -af /var/mobile/Library/Keyboard/UserDictionary.sqlite /var/root/Library/Keyboard/");
10650 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/root"] retain];
10652 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10653 alloc_ = alloc->method_imp;
10654 alloc->method_imp = (IMP) &Alloc_;*/
10656 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10657 dealloc_ = dealloc->method_imp;
10658 dealloc->method_imp = (IMP) &Dealloc_;*/
10660 /* System Information {{{ */
10664 size = sizeof(maxproc);
10665 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10666 perror("sysctlbyname(\"kern.maxproc\", ?)");
10667 else if (maxproc < 64) {
10669 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10670 perror("sysctlbyname(\"kern.maxproc\", #)");
10673 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10674 char *osversion = new char[size];
10675 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10676 perror("sysctlbyname(\"kern.osversion\", ?)");
10678 System_ = [NSString stringWithUTF8String:osversion];
10680 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10681 char *machine = new char[size];
10682 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10683 perror("sysctlbyname(\"hw.machine\", ?)");
10685 Machine_ = machine;
10687 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10688 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10689 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10691 UniqueID_ = [device uniqueIdentifier];
10693 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10694 Product_ = [info objectForKey:@"SafariProductVersion"];
10695 Safari_ = [info objectForKey:@"CFBundleVersion"];
10698 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10700 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10701 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10702 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10703 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10704 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10705 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10707 UserAgent_ = agent;
10709 /* Load Database {{{ */
10711 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10713 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10715 if (Metadata_ == NULL)
10716 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10718 Settings_ = [Metadata_ objectForKey:@"Settings"];
10720 Packages_ = [Metadata_ objectForKey:@"Packages"];
10722 Values_ = [Metadata_ objectForKey:@"Values"];
10723 Sections_ = [Metadata_ objectForKey:@"Sections"];
10724 Sources_ = [Metadata_ objectForKey:@"Sources"];
10726 Token_ = [Metadata_ objectForKey:@"Token"];
10728 Version_ = [Metadata_ objectForKey:@"Version"];
10731 if (Settings_ != nil)
10732 Role_ = [Settings_ objectForKey:@"Role"];
10734 if (Values_ == nil) {
10735 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10736 [Metadata_ setObject:Values_ forKey:@"Values"];
10739 if (Sections_ == nil) {
10740 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10741 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10744 if (Sources_ == nil) {
10745 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10746 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10749 if (Version_ == nil) {
10750 Version_ = [NSNumber numberWithUnsignedInt:0];
10751 [Metadata_ setObject:Version_ forKey:@"Version"];
10754 if ([Version_ unsignedIntValue] == 0) {
10755 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10756 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10757 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10758 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10760 Version_ = [NSNumber numberWithUnsignedInt:1];
10761 [Metadata_ setObject:Version_ forKey:@"Version"];
10763 [Metadata_ removeObjectForKey:@"LastUpdate"];
10769 CydiaWriteSources();
10772 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10775 if (Packages_ != nil) {
10777 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10781 [Metadata_ removeObjectForKey:@"Packages"];
10787 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10789 #define MobileSubstrate_(name) \
10790 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10791 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10792 if (handle == NULL) \
10793 NSLog(@"%s", dlerror()); \
10796 MobileSubstrate_(Activator)
10797 MobileSubstrate_(libstatusbar)
10798 MobileSubstrate_(SimulatedKeyEvents)
10799 MobileSubstrate_(WinterBoard)
10801 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10802 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10804 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10806 if (access("/User", F_OK) != 0 || version != 6) {
10808 system("/usr/libexec/cydia/firmware.sh");
10812 _assert([[NSFileManager defaultManager]
10813 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10814 withIntermediateDirectories:YES
10819 if (access("/tmp/cydia.chk", F_OK) == 0) {
10820 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10821 _assert(errno == ENOENT);
10822 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10823 _assert(errno == ENOENT);
10826 /* APT Initialization {{{ */
10827 _assert(pkgInitConfig(*_config));
10828 _assert(pkgInitSystem(*_config, _system));
10831 _config->Set("APT::Acquire::Translation", lang);
10833 // XXX: this timeout might be important :(
10834 //_config->Set("Acquire::http::Timeout", 15);
10836 _config->Set("Acquire::http::MaxParallel", 3);
10838 /* Color Choices {{{ */
10839 space_ = CGColorSpaceCreateDeviceRGB();
10841 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10842 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10843 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10844 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10845 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10846 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10847 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10848 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10849 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10851 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10852 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10854 /* UIKit Configuration {{{ */
10855 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10856 if ($GSFontSetUseLegacyFontMetrics != NULL)
10857 $GSFontSetUseLegacyFontMetrics(YES);
10859 // XXX: I have a feeling this was important
10860 //UIKeyboardDisableAutomaticAppearance();
10863 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10865 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemHasCapability"));
10866 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10868 ShowPromoted_ = fast;
10869 PulseInterval_ = fast ? 50000 : 500000;
10871 Colon_ = UCLocalize("COLON_DELIMITED");
10872 Elision_ = UCLocalize("ELISION");
10873 Error_ = UCLocalize("ERROR");
10874 Warning_ = UCLocalize("WARNING");
10877 AprilFools_ = true;
10879 CFGregorianDate date(CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem()));
10880 AprilFools_ = date.month == 4 && date.day == 1;
10884 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10886 CGColorSpaceRelease(space_);
10887 CFRelease(Locale_);