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>
72 #include <WebKit/DOMHTMLIFrameElement.h>
79 #include <ext/stdio_filebuf.h>
83 #include <apt-pkg/acquire.h>
84 #include <apt-pkg/acquire-item.h>
85 #include <apt-pkg/algorithms.h>
86 #include <apt-pkg/cachefile.h>
87 #include <apt-pkg/clean.h>
88 #include <apt-pkg/configuration.h>
89 #include <apt-pkg/debindexfile.h>
90 #include <apt-pkg/debmetaindex.h>
91 #include <apt-pkg/error.h>
92 #include <apt-pkg/init.h>
93 #include <apt-pkg/mmap.h>
94 #include <apt-pkg/pkgrecords.h>
95 #include <apt-pkg/sha1.h>
96 #include <apt-pkg/sourcelist.h>
97 #include <apt-pkg/sptr.h>
98 #include <apt-pkg/strutl.h>
99 #include <apt-pkg/tagfile.h>
101 #include <apr-1/apr_pools.h>
103 #include <sys/types.h>
104 #include <sys/stat.h>
105 #include <sys/sysctl.h>
106 #include <sys/param.h>
107 #include <sys/mount.h>
108 #include <sys/reboot.h>
115 #include <mach-o/nlist.h>
124 #include <Cytore.hpp>
127 #include <CydiaSubstrate/CydiaSubstrate.h>
128 #include "Menes/Menes.h"
130 #include "CyteKit/IndirectDelegate.h"
131 #include "CyteKit/PerlCompatibleRegEx.hpp"
132 #include "CyteKit/TableViewCell.h"
133 #include "CyteKit/WebScriptObject-Cyte.h"
134 #include "CyteKit/WebViewController.h"
135 #include "CyteKit/WebViewTableViewCell.h"
136 #include "CyteKit/stringWithUTF8Bytes.h"
138 #include "Cydia/MIMEAddress.h"
139 #include "Cydia/LoadingViewController.h"
140 #include "Cydia/ProgressEvent.h"
142 #include "SDURLCache/SDURLCache.h"
149 #define _timestamp ({ \
151 gettimeofday(&tv, NULL); \
152 tv.tv_sec * 1000000 + tv.tv_usec; \
155 typedef std::vector<class ProfileTime *> TimeList;
165 ProfileTime(const char *name) :
169 times_.push_back(this);
172 void AddTime(uint64_t time) {
179 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
191 ProfileTimer(ProfileTime &time) :
198 time_.AddTime(_timestamp - start_);
203 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
205 std::cerr << "========" << std::endl;
208 #define _profile(name) { \
209 static ProfileTime name(#name); \
210 ProfileTimer _ ## name(name);
215 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
216 #define synchronized(lock) \
217 synchronized(static_cast<NSObject *>(lock))
219 extern NSString *Cydia_;
221 #define lprintf(args...) fprintf(stderr, args)
224 #define TraceLogging (1 && !ForRelease)
225 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
226 #define ProfileTimes (0 && !ForRelease)
227 #define ForSaurik (0 && !ForRelease)
228 #define LogBrowser (0 && !ForRelease)
229 #define TrackResize (0 && !ForRelease)
230 #define ManualRefresh (1 && !ForRelease)
231 #define ShowInternals (0 && !ForRelease)
232 #define AlwaysReload (0 && !ForRelease)
233 #define TryIndexedCollation (0 && !ForRelease)
237 #define _trace(args...)
242 #define _profile(name) {
245 #define PrintTimes() do {} while (false)
248 // Hash Functions/Structures {{{
249 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
257 static bool ShowPromoted_;
259 static NSString *Colon_;
261 static NSString *Error_;
262 static NSString *Warning_;
264 static NSString *Cache_;
266 static bool AprilFools_;
268 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
270 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
272 static NSString *UniqueIdentifier(UIDevice *device = nil) {
273 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
274 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
276 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
279 static bool IsReachable(const char *name) {
280 SCNetworkReachabilityFlags flags; {
281 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
282 SCNetworkReachabilityGetFlags(reachability, &flags);
283 CFRelease(reachability);
286 // XXX: this elaborate mess is what Apple is using to determine this? :(
287 // XXX: do we care if the user has to intervene? maybe that's ok?
289 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
290 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
291 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
292 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
293 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
294 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
299 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
301 static _finline NSString *CydiaURL(NSString *path) {
303 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
304 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
305 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
306 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
307 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
309 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
312 static void ReapZombie(pid_t pid) {
315 if (waitpid(pid, &status, 0) == -1)
321 static _finline void UpdateExternalStatus(uint64_t newStatus) {
323 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
324 notify_set_state(notify_token, newStatus);
325 notify_cancel(notify_token);
327 notify_post("com.saurik.Cydia.status");
330 static CGFloat CYStatusBarHeight() {
331 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
332 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
335 /* NSForcedOrderingSearch doesn't work on the iPhone */
336 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
337 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
338 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
340 /* Insertion Sort {{{ */
342 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
343 const char *ptr = (const char *)list;
345 CFIndex half = count / 2;
346 const char *probe = ptr + elementSize * half;
347 CFComparisonResult cr = comparator(element, probe, context);
348 if (0 == cr) return (probe - (const char *)list) / elementSize;
349 ptr = (cr < 0) ? ptr : probe + elementSize;
350 count = (cr < 0) ? half : (half + (count & 1) - 1);
352 return (ptr - (const char *)list) / elementSize;
355 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
356 const char *ptr = (const char *)list;
358 CFIndex half = count / 2;
359 const char *probe = ptr + elementSize * half;
360 CFComparisonResult cr = comparator(element, probe, context);
361 if (0 == cr) return (probe - (const char *)list) / elementSize;
362 ptr = (cr < 0) ? ptr : probe + elementSize;
363 count = (cr < 0) ? half : (half + (count & 1) - 1);
365 return (ptr - (const char *)list) / elementSize;
368 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
369 if (range.length == 0)
371 const void **values(new const void *[range.length]);
372 CFArrayGetValues(array, range, values);
374 #if HistogramInsertionSort > 0
375 uint32_t total(0), *offsets(new uint32_t[range.length]);
378 for (CFIndex index(1); index != range.length; ++index) {
379 const void *value(values[index]);
380 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
381 CFIndex correct(index);
382 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
383 #if HistogramInsertionSort > 1
384 NSLog(@"%@ < %@", value, values[correct - 1]);
389 if (correct != index) {
390 size_t offset(index - correct);
391 #if HistogramInsertionSort
395 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
397 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
398 values[correct] = value;
402 CFArrayReplaceValues(array, range, values, range.length);
405 #if HistogramInsertionSort > 0
406 for (CFIndex index(0); index != range.length; ++index)
407 if (offsets[index] != 0)
408 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
409 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
416 /* Apple Bug Fixes {{{ */
417 @implementation UIWebDocumentView (Cydia)
419 - (void) _setScrollerOffset:(CGPoint)offset {
420 UIScroller *scroller([self _scroller]);
422 CGSize size([scroller contentSize]);
423 CGSize bounds([scroller bounds].size);
426 max.x = size.width - bounds.width;
427 max.y = size.height - bounds.height;
435 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
436 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
438 [scroller setOffset:offset];
444 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
445 size_t length([self length] - state->state);
448 else if (length > count)
450 for (size_t i(0); i != length; ++i)
451 objects[i] = [self item:state->state++];
452 state->itemsPtr = objects;
453 state->mutationsPtr = (unsigned long *) self;
457 /* Cydia NSString Additions {{{ */
458 @interface NSString (Cydia)
459 - (NSComparisonResult) compareByPath:(NSString *)other;
460 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
463 @implementation NSString (Cydia)
465 - (NSComparisonResult) compareByPath:(NSString *)other {
466 NSString *prefix = [self commonPrefixWithString:other options:0];
467 size_t length = [prefix length];
469 NSRange lrange = NSMakeRange(length, [self length] - length);
470 NSRange rrange = NSMakeRange(length, [other length] - length);
472 lrange = [self rangeOfString:@"/" options:0 range:lrange];
473 rrange = [other rangeOfString:@"/" options:0 range:rrange];
475 NSComparisonResult value;
477 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
478 value = NSOrderedSame;
479 else if (lrange.location == NSNotFound)
480 value = NSOrderedAscending;
481 else if (rrange.location == NSNotFound)
482 value = NSOrderedDescending;
484 value = NSOrderedSame;
486 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
487 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
488 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
489 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
491 NSComparisonResult result = [lpath compare:rpath];
492 return result == NSOrderedSame ? value : result;
495 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
496 return [(id)CFURLCreateStringByAddingPercentEscapes(
501 kCFStringEncodingUTF8
508 /* C++ NSString Wrapper Cache {{{ */
509 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
510 return size == 0 ? NULL :
511 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
512 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
515 static _finline CFStringRef CYStringCreate(const char *data) {
516 return CYStringCreate(data, strlen(data));
525 _finline void clear_() {
526 if (cache_ != NULL) {
533 _finline bool empty() const {
537 _finline size_t size() const {
541 _finline char *data() const {
545 _finline void clear() {
550 _finline CYString() :
557 _finline ~CYString() {
561 void operator =(const CYString &rhs) {
565 if (rhs.cache_ == nil)
568 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
571 void copy(apr_pool_t *pool) {
572 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
573 memcpy(temp, data_, size_);
578 void set(apr_pool_t *pool, const char *data, size_t size) {
584 data_ = const_cast<char *>(data);
592 _finline void set(apr_pool_t *pool, const char *data) {
593 set(pool, data, data == NULL ? 0 : strlen(data));
596 _finline void set(apr_pool_t *pool, const std::string &rhs) {
597 set(pool, rhs.data(), rhs.size());
600 bool operator ==(const CYString &rhs) const {
601 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
604 _finline operator CFStringRef() {
606 cache_ = CYStringCreate(data_, size_);
610 _finline operator id() {
611 return (NSString *) static_cast<CFStringRef>(*this);
614 _finline operator const char *() {
615 return reinterpret_cast<const char *>(data_);
619 /* C++ NSString Algorithm Adapters {{{ */
621 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
624 struct NSStringMapHash :
625 std::unary_function<NSString *, size_t>
627 _finline size_t operator ()(NSString *value) const {
628 return CFStringHashNSString((CFStringRef) value);
632 struct NSStringMapLess :
633 std::binary_function<NSString *, NSString *, bool>
635 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
636 return [lhs compare:rhs] == NSOrderedAscending;
640 struct NSStringMapEqual :
641 std::binary_function<NSString *, NSString *, bool>
643 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
644 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
645 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
646 //[lhs isEqualToString:rhs];
651 /* CoreGraphics Primitives {{{ */
656 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
657 CGFloat color[] = {red, green, blue, alpha};
658 return CGColorCreate(space, color);
667 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
668 color_(Create_(space, red, green, blue, alpha))
670 Set(space, red, green, blue, alpha);
675 CGColorRelease(color_);
682 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
684 color_ = Create_(space, red, green, blue, alpha);
687 operator CGColorRef() {
693 /* Random Global Variables {{{ */
694 static int PulseInterval_ = 500000;
696 static const NSString *UI_;
699 static bool RestartSubstrate_;
700 static NSArray *Finishes_;
702 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
703 #define NotifyConfig_ "/etc/notify.conf"
705 static bool Queuing_;
707 static CYColor Blue_;
708 static CYColor Blueish_;
709 static CYColor Black_;
711 static CYColor White_;
712 static CYColor Gray_;
713 static CYColor Green_;
714 static CYColor Purple_;
715 static CYColor Purplish_;
717 static UIColor *InstallingColor_;
718 static UIColor *RemovingColor_;
720 static NSString *App_;
722 static BOOL Advanced_;
723 static BOOL Ignored_;
725 static _H<UIFont> Font12_;
726 static _H<UIFont> Font12Bold_;
727 static _H<UIFont> Font14_;
728 static _H<UIFont> Font18Bold_;
729 static _H<UIFont> Font22Bold_;
731 static const char *Machine_ = NULL;
732 static _H<NSString> System_;
733 static NSString *SerialNumber_ = nil;
734 static NSString *ChipID_ = nil;
735 static NSString *BBSNum_ = nil;
736 static _H<NSString> Token_;
737 static _H<NSString> UniqueID_;
738 static _H<NSString> UserAgent_;
739 static _H<NSString> Product_;
740 static _H<NSString> Safari_;
742 static CFLocaleRef Locale_;
743 static NSArray *Languages_;
744 static CGColorSpaceRef space_;
746 static NSDictionary *SectionMap_;
747 static NSMutableDictionary *Metadata_;
748 static _transient NSMutableDictionary *Settings_;
749 static _transient NSString *Role_;
750 static _transient NSMutableDictionary *Packages_;
751 static _transient NSMutableDictionary *Values_;
752 static _transient NSMutableDictionary *Sections_;
753 _H<NSMutableDictionary> Sources_;
754 static _transient NSNumber *Version_;
759 static CGFloat ScreenScale_;
760 static NSString *Idiom_;
761 static _H<NSString> Firmware_;
762 static NSString *Major_;
764 static _H<NSMutableDictionary> SessionData_;
765 static _H<NSObject> HostConfig_;
766 static _H<NSMutableSet> BridgedHosts_;
767 static _H<NSMutableSet> TokenHosts_;
768 static _H<NSMutableSet> InsecureHosts_;
769 static _H<NSMutableSet> PipelinedHosts_;
770 static _H<NSMutableSet> CachedURLs_;
772 static NSString *kCydiaProgressEventTypeError = @"Error";
773 static NSString *kCydiaProgressEventTypeInformation = @"Information";
774 static NSString *kCydiaProgressEventTypeStatus = @"Status";
775 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
778 /* Display Helpers {{{ */
779 inline float Interpolate(float begin, float end, float fraction) {
780 return (end - begin) * fraction + begin;
783 static _finline const char *StripVersion_(const char *version) {
784 const char *colon(strchr(version, ':'));
785 return colon == NULL ? version : colon + 1;
788 NSString *LocalizeSection(NSString *section) {
789 static Pcre title_r("^(.*?) \\((.*)\\)$");
790 if (title_r(section)) {
791 NSString *parent(title_r[1]);
792 NSString *child(title_r[2]);
794 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
795 LocalizeSection(parent),
796 LocalizeSection(child)
800 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
803 NSString *Simplify(NSString *title) {
804 const char *data = [title UTF8String];
805 size_t size = [title length];
807 static Pcre square_r("^\\[(.*)\\]$");
808 if (square_r(data, size))
809 return Simplify(square_r[1]);
811 static Pcre paren_r("^\\((.*)\\)$");
812 if (paren_r(data, size))
813 return Simplify(paren_r[1]);
815 static Pcre title_r("^(.*?) \\((.*)\\)$");
816 if (title_r(data, size))
817 return Simplify(title_r[1]);
823 NSString *GetLastUpdate() {
824 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
827 return UCLocalize("NEVER_OR_UNKNOWN");
829 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
830 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
832 CFRelease(formatter);
834 return [(NSString *) formatted autorelease];
837 bool isSectionVisible(NSString *section) {
838 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
839 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
840 return hidden == nil || ![hidden boolValue];
843 static NSObject *CYIOGetValue(const char *path, NSString *property) {
844 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
845 if (entry == MACH_PORT_NULL)
848 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
849 IOObjectRelease(entry);
853 return [(id) value autorelease];
856 static NSString *CYHex(NSData *data, bool reverse = false) {
860 size_t length([data length]);
861 uint8_t bytes[length];
862 [data getBytes:bytes];
864 char string[length * 2 + 1];
865 for (size_t i(0); i != length; ++i)
866 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
868 return [NSString stringWithUTF8String:string];
873 /* Delegate Prototypes {{{ */
876 @class CydiaProgressEvent;
878 @protocol DatabaseDelegate
879 - (void) repairWithSelector:(SEL)selector;
880 - (void) setConfigurationData:(NSString *)data;
881 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
884 @class CYPackageController;
886 @protocol CydiaDelegate
887 - (void) returnToCydia;
889 - (void) retainNetworkActivityIndicator;
890 - (void) releaseNetworkActivityIndicator;
891 - (void) clearPackage:(Package *)package;
892 - (void) installPackage:(Package *)package;
893 - (void) installPackages:(NSArray *)packages;
894 - (void) removePackage:(Package *)package;
895 - (void) beginUpdate;
897 - (void) distUpgrade;
900 - (void) _saveConfig;
902 - (void) addSource:(NSDictionary *)source;
903 - (void) addTrivialSource:(NSString *)href;
904 - (void) showSettings;
905 - (UIProgressHUD *) addProgressHUD;
906 - (void) removeProgressHUD:(UIProgressHUD *)hud;
907 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
908 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
912 /* Status Delegation {{{ */
914 public pkgAcquireStatus
917 _transient NSObject<ProgressDelegate> *delegate_;
927 void setDelegate(NSObject<ProgressDelegate> *delegate) {
928 delegate_ = delegate;
931 NSObject<ProgressDelegate> *getDelegate() const {
935 virtual bool MediaChange(std::string media, std::string drive) {
939 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
943 virtual void Fetch(pkgAcquire::ItemDesc &item) {
944 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
945 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
946 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
949 virtual void Done(pkgAcquire::ItemDesc &item) {
950 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
951 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
952 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
955 virtual void Fail(pkgAcquire::ItemDesc &item) {
957 item.Owner->Status == pkgAcquire::Item::StatIdle ||
958 item.Owner->Status == pkgAcquire::Item::StatDone
962 std::string &error(item.Owner->ErrorText);
966 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
967 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
970 virtual bool Pulse(pkgAcquire *Owner) {
971 bool value = pkgAcquireStatus::Pulse(Owner);
974 double(CurrentBytes + CurrentItems) /
975 double(TotalBytes + TotalItems)
978 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
979 [NSNumber numberWithDouble:percent], @"Percent",
981 [NSNumber numberWithDouble:CurrentBytes], @"Current",
982 [NSNumber numberWithDouble:TotalBytes], @"Total",
983 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
984 nil] waitUntilDone:YES];
986 if (value && ![delegate_ isProgressCancelled])
994 _finline bool WasCancelled() const {
998 virtual void Start() {
999 pkgAcquireStatus::Start();
1000 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1003 virtual void Stop() {
1004 pkgAcquireStatus::Stop();
1005 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1006 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1010 /* Database Interface {{{ */
1011 typedef std::map< unsigned long, _H<Source> > SourceMap;
1013 @interface Database : NSObject {
1019 pkgCacheFile cache_;
1020 pkgDepCache::Policy *policy_;
1021 pkgRecords *records_;
1022 pkgProblemResolver *resolver_;
1023 pkgAcquire *fetcher_;
1025 SPtr<pkgPackageManager> manager_;
1026 pkgSourceList *list_;
1028 SourceMap sourceMap_;
1029 _H<NSMutableArray> sourceList_;
1031 CFMutableArrayRef packages_;
1033 _transient NSObject<DatabaseDelegate> *delegate_;
1034 _transient NSObject<ProgressDelegate> *progress_;
1042 std::map<const char *, _H<NSString> > sections_;
1045 + (Database *) sharedInstance;
1048 - (void) _readCydia:(NSNumber *)fd;
1049 - (void) _readStatus:(NSNumber *)fd;
1050 - (void) _readOutput:(NSNumber *)fd;
1054 - (Package *) packageWithName:(NSString *)name;
1056 - (pkgCacheFile &) cache;
1057 - (pkgDepCache::Policy *) policy;
1058 - (pkgRecords *) records;
1059 - (pkgProblemResolver *) resolver;
1060 - (pkgAcquire &) fetcher;
1061 - (pkgSourceList &) list;
1062 - (NSArray *) packages;
1063 - (NSArray *) sources;
1064 - (Source *) sourceWithKey:(NSString *)key;
1065 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1073 - (void) updateWithStatus:(Status &)status;
1075 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1077 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1078 - (NSObject<ProgressDelegate> *) progressDelegate;
1080 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1082 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1086 /* ProgressEvent Implementation {{{ */
1087 @implementation CydiaProgressEvent
1089 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1090 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1093 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1094 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1095 [event setPackage:package];
1099 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1100 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1102 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1103 NSArray *fields([description componentsSeparatedByString:@" "]);
1104 [event setItem:fields];
1106 if ([fields count] > 3) {
1107 [event setPackage:[fields objectAtIndex:2]];
1108 [event setVersion:[fields objectAtIndex:3]];
1111 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1116 + (NSArray *) _attributeKeys {
1117 return [NSArray arrayWithObjects:
1127 - (NSArray *) attributeKeys {
1128 return [[self class] _attributeKeys];
1131 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1132 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1135 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1136 if ((self = [super init]) != nil) {
1142 - (NSString *) message {
1146 - (NSString *) type {
1150 - (NSArray *) item {
1151 return (id) item_ ?: [NSNull null];
1154 - (void) setItem:(NSArray *)item {
1158 - (NSString *) package {
1159 return (id) package_ ?: [NSNull null];
1162 - (void) setPackage:(NSString *)package {
1166 - (NSString *) url {
1167 return (id) url_ ?: [NSNull null];
1170 - (void) setURL:(NSString *)url {
1174 - (void) setVersion:(NSString *)version {
1178 - (NSString *) version {
1179 return (id) version_ ?: [NSNull null];
1182 - (NSString *) compound:(NSString *)value {
1184 NSString *mode(nil); {
1185 NSString *type([self type]);
1186 if ([type isEqualToString:kCydiaProgressEventTypeError])
1187 mode = UCLocalize("ERROR");
1188 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1189 mode = UCLocalize("WARNING");
1193 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1199 - (NSString *) compoundMessage {
1200 return [self compound:[self message]];
1203 - (NSString *) compoundTitle {
1206 if (package_ == nil)
1208 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1209 title = [package name];
1213 return [self compound:title];
1219 // Cytore Definitions {{{
1220 struct PackageValue :
1223 Cytore::Offset<PackageValue> next_;
1225 uint32_t index_ : 23;
1226 uint32_t subscribed_ : 1;
1243 Cytore::Offset<PackageValue> packages_[1 << 16];
1246 static Cytore::File<MetaValue> MetaFile_;
1248 // Cytore Helper Functions {{{
1249 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1250 SplitHash nhash = { hashlittle(name, length) };
1252 PackageValue *metadata;
1254 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1255 offset: if (offset->IsNull()) {
1256 *offset = MetaFile_.New<PackageValue>(length + 1);
1257 metadata = &MetaFile_.Get(*offset);
1259 if (metadata == NULL) {
1263 metadata = new PackageValue();
1264 memset(metadata, 0, sizeof(*metadata));
1267 memcpy(metadata->name_, name, length + 1);
1268 metadata->nhash_ = nhash.u16[1];
1270 metadata = &MetaFile_.Get(*offset);
1272 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1273 offset = &metadata->next_;
1281 static void PackageImport(const void *key, const void *value, void *context) {
1282 bool &fail(*reinterpret_cast<bool *>(context));
1285 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1286 NSLog(@"failed to import package %@", key);
1290 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1291 NSDictionary *package((NSDictionary *) value);
1293 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1294 if ([subscribed boolValue] && !metadata->subscribed_)
1295 metadata->subscribed_ = true;
1297 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1298 time_t time([date timeIntervalSince1970]);
1299 if (metadata->first_ > time || metadata->first_ == 0)
1300 metadata->first_ = time;
1303 NSDate *date([package objectForKey:@"LastSeen"]);
1304 NSString *version([package objectForKey:@"LastVersion"]);
1306 if (date != nil && version != nil) {
1307 time_t time([date timeIntervalSince1970]);
1308 if (metadata->last_ < time || metadata->last_ == 0)
1309 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1310 size_t length(strlen(buffer));
1311 uint16_t vhash(hashlittle(buffer, length));
1313 size_t capped(std::min<size_t>(8, length));
1314 char *latest(buffer + length - capped);
1316 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1317 metadata->vhash_ = vhash;
1319 metadata->last_ = time;
1325 /* Source Class {{{ */
1326 @interface Source : NSObject {
1328 Database *database_;
1331 CYString depiction_;
1332 CYString description_;
1338 CYString distribution_;
1344 _H<NSString> authority_;
1346 CYString defaultIcon_;
1348 _H<NSMutableDictionary> record_;
1352 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1354 - (NSComparisonResult) compareByName:(Source *)source;
1356 - (NSString *) depictionForPackage:(NSString *)package;
1357 - (NSString *) supportForPackage:(NSString *)package;
1359 - (metaIndex *) metaIndex;
1360 - (NSDictionary *) record;
1363 - (NSString *) rooturi;
1364 - (NSString *) distribution;
1365 - (NSString *) type;
1368 - (NSString *) host;
1370 - (NSString *) name;
1371 - (NSString *) shortDescription;
1372 - (NSString *) label;
1373 - (NSString *) origin;
1374 - (NSString *) version;
1376 - (NSString *) defaultIcon;
1377 - (NSURL *) iconURL;
1381 @implementation Source
1385 distribution_.clear();
1390 description_.clear();
1396 defaultIcon_.clear();
1403 + (NSString *) webScriptNameForSelector:(SEL)selector {
1405 else if (selector == @selector(addSection:))
1406 return @"addSection";
1407 else if (selector == @selector(getField:))
1409 else if (selector == @selector(removeSection:))
1410 return @"removeSection";
1411 else if (selector == @selector(remove))
1417 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1418 return [self webScriptNameForSelector:selector] == nil;
1421 + (NSArray *) _attributeKeys {
1422 return [NSArray arrayWithObjects:
1433 @"shortDescription",
1440 - (NSArray *) attributeKeys {
1441 return [[self class] _attributeKeys];
1444 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1445 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1448 - (metaIndex *) metaIndex {
1452 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1455 trusted_ = index->IsTrusted();
1457 uri_.set(pool, index->GetURI());
1458 distribution_.set(pool, index->GetDist());
1459 type_.set(pool, index->GetType());
1461 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1462 if (dindex != NULL) {
1463 base_.set(pool, dindex->MetaIndexURI(""));
1466 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1469 pkgTagFile tags(&fd);
1471 pkgTagSection section;
1478 {"default-icon", &defaultIcon_},
1479 {"depiction", &depiction_},
1480 {"description", &description_},
1482 {"origin", &origin_},
1483 {"support", &support_},
1484 {"version", &version_},
1487 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1488 const char *start, *end;
1490 if (section.Find(names[i].name_, start, end)) {
1491 CYString &value(*names[i].value_);
1492 value.set(pool, start, end - start);
1498 record_ = [Sources_ objectForKey:[self key]];
1500 NSURL *url([NSURL URLWithString:uri_]);
1504 host_ = [host_ lowercaseString];
1509 authority_ = [url path];
1512 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1513 if ((self = [super init]) != nil) {
1514 era_ = [database era];
1515 database_ = database;
1518 [self setMetaIndex:index inPool:pool];
1522 - (NSString *) getField:(NSString *)name {
1523 @synchronized (database_) {
1524 if ([database_ era] != era_ || index_ == NULL)
1527 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1532 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1537 pkgTagFile tags(&fd);
1539 pkgTagSection section;
1542 const char *start, *end;
1543 if (!section.Find([name UTF8String], start, end))
1544 return (NSString *) [NSNull null];
1546 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1549 - (NSComparisonResult) compareByName:(Source *)source {
1550 NSString *lhs = [self name];
1551 NSString *rhs = [source name];
1553 if ([lhs length] != 0 && [rhs length] != 0) {
1554 unichar lhc = [lhs characterAtIndex:0];
1555 unichar rhc = [rhs characterAtIndex:0];
1557 if (isalpha(lhc) && !isalpha(rhc))
1558 return NSOrderedAscending;
1559 else if (!isalpha(lhc) && isalpha(rhc))
1560 return NSOrderedDescending;
1563 return [lhs compare:rhs options:LaxCompareOptions_];
1566 - (NSString *) depictionForPackage:(NSString *)package {
1567 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1570 - (NSString *) supportForPackage:(NSString *)package {
1571 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1574 - (NSArray *) sections {
1575 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1578 - (void) _addSection:(NSString *)section {
1581 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1582 if (![sections containsObject:section]) {
1583 [sections addObject:section];
1587 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1592 - (bool) addSection:(NSString *)section {
1596 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1600 - (void) _removeSection:(NSString *)section {
1604 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1605 if ([sections containsObject:section]) {
1606 [sections removeObject:section];
1611 - (bool) removeSection:(NSString *)section {
1615 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1620 [Sources_ removeObjectForKey:[self key]];
1625 bool value(record_ != nil);
1626 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1630 - (NSDictionary *) record {
1638 - (NSString *) rooturi {
1642 - (NSString *) distribution {
1643 return distribution_;
1646 - (NSString *) type {
1650 - (NSString *) baseuri {
1651 return base_.empty() ? nil : (id) base_;
1654 - (NSString *) iconuri {
1655 if (NSString *base = [self baseuri])
1656 return [base stringByAppendingString:@"CydiaIcon.png"];
1661 - (NSURL *) iconURL {
1662 if (NSString *uri = [self iconuri])
1663 return [NSURL URLWithString:uri];
1667 - (NSString *) key {
1668 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1671 - (NSString *) host {
1675 - (NSString *) name {
1676 return origin_.empty() ? (id) authority_ : origin_;
1679 - (NSString *) shortDescription {
1680 return description_;
1683 - (NSString *) label {
1684 return label_.empty() ? (id) authority_ : label_;
1687 - (NSString *) origin {
1691 - (NSString *) version {
1695 - (NSString *) defaultIcon {
1696 return defaultIcon_;
1701 /* CydiaOperation Class {{{ */
1702 @interface CydiaOperation : NSObject {
1703 _H<NSString> operator_;
1704 _H<NSString> value_;
1707 - (NSString *) operator;
1708 - (NSString *) value;
1712 @implementation CydiaOperation
1714 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1715 if ((self = [super init]) != nil) {
1716 operator_ = [NSString stringWithUTF8String:_operator];
1717 value_ = [NSString stringWithUTF8String:value];
1721 + (NSArray *) _attributeKeys {
1722 return [NSArray arrayWithObjects:
1728 - (NSArray *) attributeKeys {
1729 return [[self class] _attributeKeys];
1732 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1733 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1736 - (NSString *) operator {
1740 - (NSString *) value {
1746 /* CydiaClause Class {{{ */
1747 @interface CydiaClause : NSObject {
1748 _H<NSString> package_;
1749 _H<CydiaOperation> version_;
1752 - (NSString *) package;
1753 - (CydiaOperation *) version;
1757 @implementation CydiaClause
1759 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1760 if ((self = [super init]) != nil) {
1761 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1763 if (const char *version = dep.TargetVer())
1764 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1766 version_ = (id) [NSNull null];
1770 + (NSArray *) _attributeKeys {
1771 return [NSArray arrayWithObjects:
1777 - (NSArray *) attributeKeys {
1778 return [[self class] _attributeKeys];
1781 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1782 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1785 - (NSString *) package {
1789 - (CydiaOperation *) version {
1795 /* CydiaRelation Class {{{ */
1796 @interface CydiaRelation : NSObject {
1797 _H<NSString> relationship_;
1798 _H<NSMutableArray> clauses_;
1801 - (NSString *) relationship;
1802 - (NSArray *) clauses;
1806 @implementation CydiaRelation
1808 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1809 if ((self = [super init]) != nil) {
1810 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1811 clauses_ = [NSMutableArray arrayWithCapacity:8];
1813 pkgCache::DepIterator start;
1814 pkgCache::DepIterator end;
1815 dep.GlobOr(start, end); // ++dep
1818 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1820 // yes, seriously. (wtf?)
1828 + (NSArray *) _attributeKeys {
1829 return [NSArray arrayWithObjects:
1835 - (NSArray *) attributeKeys {
1836 return [[self class] _attributeKeys];
1839 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1840 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1843 - (NSString *) relationship {
1844 return relationship_;
1847 - (NSArray *) clauses {
1851 - (void) addClause:(CydiaClause *)clause {
1852 [clauses_ addObject:clause];
1857 /* Package Class {{{ */
1858 struct ParsedPackage {
1862 CYString architecture_;
1865 CYString depiction_;
1875 @interface Package : NSObject {
1878 uint32_t essential_ : 1;
1879 uint32_t obsolete_ : 1;
1880 uint32_t ignored_ : 1;
1881 uint32_t pooled_ : 1;
1887 _transient Database *database_;
1889 pkgCache::VerIterator version_;
1890 pkgCache::PkgIterator iterator_;
1891 pkgCache::VerFileIterator file_;
1897 CYString installed_;
1899 const char *section_;
1900 _transient NSString *section$_;
1904 PackageValue *metadata_;
1905 ParsedPackage *parsed_;
1907 _H<NSMutableArray> tags_;
1910 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1911 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1913 - (pkgCache::PkgIterator) iterator;
1916 - (NSString *) section;
1917 - (NSString *) simpleSection;
1919 - (NSString *) longSection;
1920 - (NSString *) shortSection;
1924 - (MIMEAddress *) maintainer;
1926 - (NSString *) longDescription;
1927 - (NSString *) shortDescription;
1930 - (PackageValue *) metadata;
1933 - (bool) subscribed;
1934 - (bool) setSubscribed:(bool)subscribed;
1938 - (NSString *) latest;
1939 - (NSString *) installed;
1940 - (BOOL) uninstalled;
1943 - (BOOL) upgradableAndEssential:(BOOL)essential;
1946 - (BOOL) unfiltered;
1950 - (BOOL) halfConfigured;
1951 - (BOOL) halfInstalled;
1953 - (NSString *) mode;
1956 - (NSString *) name;
1958 - (NSString *) homepage;
1959 - (NSString *) depiction;
1960 - (MIMEAddress *) author;
1962 - (NSString *) support;
1964 - (NSArray *) files;
1965 - (NSArray *) warnings;
1966 - (NSArray *) applications;
1968 - (Source *) source;
1971 - (BOOL) matches:(NSArray *)query;
1973 - (bool) hasSupportingRole;
1974 - (BOOL) hasTag:(NSString *)tag;
1975 - (NSString *) primaryPurpose;
1976 - (NSArray *) purposes;
1977 - (bool) isCommercial;
1979 - (void) setIndex:(size_t)index;
1981 - (CYString &) cyname;
1983 - (uint32_t) compareBySection:(NSArray *)sections;
1988 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1989 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1990 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1991 - (bool) isVisibleInSection:(NSString *)section;
1992 - (bool) isVisibleInSource:(Source *)source;
1996 uint32_t PackageChangesRadix(Package *self, void *) {
2001 uint32_t timestamp : 30;
2002 uint32_t ignored : 1;
2003 uint32_t upgradable : 1;
2007 bool upgradable([self upgradableAndEssential:YES]);
2008 value.bits.upgradable = upgradable ? 1 : 0;
2011 value.bits.timestamp = 0;
2012 value.bits.ignored = [self ignored] ? 0 : 1;
2013 value.bits.upgradable = 1;
2015 value.bits.timestamp = [self seen] >> 2;
2016 value.bits.ignored = 0;
2017 value.bits.upgradable = 0;
2020 return _not(uint32_t) - value.key;
2023 uint32_t PackagePrefixRadix(Package *self, void *context) {
2024 size_t offset(reinterpret_cast<size_t>(context));
2025 CYString &name([self cyname]);
2027 size_t size(name.size());
2030 char *text(name.data());
2033 if (!isdigit(text[0]))
2037 while (size != digits && isdigit(text[digits]))
2045 if (offset == 0 && zeros != 0) {
2046 memset(data, '0', zeros);
2047 memcpy(data + zeros, text, 4 - zeros);
2049 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2050 if (size <= offset - zeros)
2053 text += offset - zeros;
2054 size -= offset - zeros;
2057 memcpy(data, text, 4);
2059 memcpy(data, text, size);
2060 memset(data + size, 0, 4 - size);
2063 for (size_t i(0); i != 4; ++i)
2064 if (isalpha(data[i]))
2072 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2074 /* XXX: ntohl may be more honest */
2075 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2078 CYString &(*PackageName)(Package *self, SEL sel);
2080 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2081 _profile(PackageNameCompare)
2082 CYString &lhi(PackageName(lhs, @selector(cyname)));
2083 CYString &rhi(PackageName(rhs, @selector(cyname)));
2084 CFStringRef lhn(lhi), rhn(rhi);
2087 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2088 else if (rhn == NULL)
2089 return NSOrderedDescending;
2091 _profile(PackageNameCompare$NumbersLast)
2092 if (!lhi.empty() && !rhi.empty()) {
2093 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2094 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2095 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2096 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2097 return lha ? NSOrderedAscending : NSOrderedDescending;
2101 CFIndex length = CFStringGetLength(lhn);
2103 _profile(PackageNameCompare$Compare)
2104 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2109 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2110 return PackageNameCompare(*lhs, *rhs, context);
2113 struct PackageNameOrdering :
2114 std::binary_function<Package *, Package *, bool>
2116 _finline bool operator ()(Package *lhs, Package *rhs) const {
2117 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2121 @implementation Package
2123 - (NSString *) description {
2124 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2129 apr_pool_destroy(pool_);
2130 if (parsed_ != NULL)
2135 + (NSString *) webScriptNameForSelector:(SEL)selector {
2137 else if (selector == @selector(clear))
2139 else if (selector == @selector(getField:))
2141 else if (selector == @selector(hasTag:))
2143 else if (selector == @selector(install))
2145 else if (selector == @selector(remove))
2151 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2152 return [self webScriptNameForSelector:selector] == nil;
2155 + (NSArray *) _attributeKeys {
2156 return [NSArray arrayWithObjects:
2177 @"shortDescription",
2190 - (NSArray *) attributeKeys {
2191 return [[self class] _attributeKeys];
2194 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2195 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2198 - (NSArray *) relations {
2199 @synchronized (database_) {
2200 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2201 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2202 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2206 - (NSString *) architecture {
2208 @synchronized (database_) {
2209 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2212 - (NSString *) getField:(NSString *)name {
2213 @synchronized (database_) {
2214 if ([database_ era] != era_ || file_.end())
2217 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2219 const char *start, *end;
2220 if (!parser.Find([name UTF8String], start, end))
2221 return (NSString *) [NSNull null];
2223 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2227 if (parsed_ != NULL)
2229 @synchronized (database_) {
2230 if ([database_ era] != era_ || file_.end())
2233 ParsedPackage *parsed(new ParsedPackage);
2236 _profile(Package$parse)
2237 pkgRecords::Parser *parser;
2239 _profile(Package$parse$Lookup)
2240 parser = &[database_ records]->Lookup(file_);
2245 _profile(Package$parse$Find)
2250 {"architecture", &parsed->architecture_},
2251 {"icon", &parsed->icon_},
2252 {"depiction", &parsed->depiction_},
2253 {"homepage", &parsed->homepage_},
2254 {"website", &website},
2255 {"bugs", &parsed->bugs_},
2256 {"support", &parsed->support_},
2257 {"sponsor", &parsed->sponsor_},
2258 {"author", &parsed->author_},
2259 {"md5sum", &parsed->md5sum_},
2262 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2263 const char *start, *end;
2265 if (parser->Find(names[i].name_, start, end)) {
2266 CYString &value(*names[i].value_);
2267 _profile(Package$parse$Value)
2268 value.set(pool_, start, end - start);
2274 _profile(Package$parse$Tagline)
2275 const char *start, *end;
2276 if (parser->ShortDesc(start, end)) {
2277 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2280 while (stop != start && stop[-1] == '\r')
2282 parsed->tagline_.set(pool_, start, stop - start);
2286 _profile(Package$parse$Retain)
2287 if (parsed->homepage_.empty())
2288 parsed->homepage_ = website;
2289 if (parsed->homepage_ == parsed->depiction_)
2290 parsed->homepage_.clear();
2295 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2296 if ((self = [super init]) != nil) {
2297 _profile(Package$initWithVersion)
2299 apr_pool_create(&pool_, NULL);
2305 database_ = database;
2306 era_ = [database era];
2310 pkgCache::PkgIterator iterator(version.ParentPkg());
2311 iterator_ = iterator;
2313 _profile(Package$initWithVersion$Version)
2314 if (!version_.end())
2315 file_ = version_.FileList();
2317 pkgCache &cache([database_ cache]);
2318 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2322 _profile(Package$initWithVersion$Cache)
2323 name_.set(NULL, iterator.Display());
2325 latest_.set(NULL, StripVersion_(version_.VerStr()));
2327 pkgCache::VerIterator current(iterator.CurrentVer());
2329 installed_.set(NULL, StripVersion_(current.VerStr()));
2332 _profile(Package$initWithVersion$Tags)
2333 pkgCache::TagIterator tag(iterator.TagList());
2335 tags_ = [NSMutableArray arrayWithCapacity:8];
2337 goto tag; for (; !tag.end(); ++tag) tag: {
2338 const char *name(tag.Name());
2339 NSString *string((NSString *) CYStringCreate(name));
2343 [tags_ addObject:[string autorelease]];
2345 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2346 if (strcmp(name + 6, "enduser") == 0)
2348 else if (strcmp(name + 6, "hacker") == 0)
2350 else if (strcmp(name + 6, "developer") == 0)
2352 else if (strcmp(name + 6, "cydia") == 0)
2358 if (strncmp(name, "cydia::", 7) == 0) {
2359 if (strcmp(name + 7, "essential") == 0)
2361 else if (strcmp(name + 7, "obsolete") == 0)
2368 _profile(Package$initWithVersion$Metadata)
2369 const char *mixed(iterator.Name());
2370 size_t size(strlen(mixed));
2371 char lower[size + 1];
2373 for (size_t i(0); i != size; ++i)
2374 lower[i] = mixed[i] | 0x20;
2377 PackageValue *metadata(PackageFind(lower, size));
2378 metadata_ = metadata;
2380 id_.set(NULL, metadata->name_, size);
2382 const char *latest(version_.VerStr());
2383 size_t length(strlen(latest));
2385 uint16_t vhash(hashlittle(latest, length));
2387 size_t capped(std::min<size_t>(8, length));
2388 latest = latest + length - capped;
2390 if (metadata->first_ == 0)
2391 metadata->first_ = now_;
2393 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2394 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2395 metadata->vhash_ = vhash;
2396 metadata->last_ = now_;
2397 } else if (metadata->last_ == 0)
2398 metadata->last_ = metadata->first_;
2401 _profile(Package$initWithVersion$Section)
2402 section_ = version_.Section();
2405 _profile(Package$initWithVersion$Flags)
2406 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2407 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2412 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2413 pkgCache::VerIterator version;
2415 _profile(Package$packageWithIterator$GetCandidateVer)
2416 version = [database policy]->GetCandidateVer(iterator);
2424 _profile(Package$packageWithIterator$Allocate)
2425 package = [Package allocWithZone:zone];
2428 _profile(Package$packageWithIterator$Initialize)
2430 initWithVersion:version
2437 _profile(Package$packageWithIterator$Autorelease)
2438 package = [package autorelease];
2444 - (pkgCache::PkgIterator) iterator {
2448 - (NSString *) section {
2449 if (section$_ == nil) {
2450 if (section_ == NULL)
2453 _profile(Package$section$mappedSectionForPointer)
2454 section$_ = [database_ mappedSectionForPointer:section_];
2459 - (NSString *) simpleSection {
2460 if (NSString *section = [self section])
2461 return Simplify(section);
2466 - (NSString *) longSection {
2467 return LocalizeSection([self section]);
2470 - (NSString *) shortSection {
2471 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2474 - (NSString *) uri {
2477 pkgIndexFile *index;
2478 pkgCache::PkgFileIterator file(file_.File());
2479 if (![database_ list].FindIndex(file, index))
2481 return [NSString stringWithUTF8String:iterator_->Path];
2482 //return [NSString stringWithUTF8String:file.Site()];
2483 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2487 - (MIMEAddress *) maintainer {
2488 @synchronized (database_) {
2489 if ([database_ era] != era_ || file_.end())
2492 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2493 const std::string &maintainer(parser->Maintainer());
2494 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2497 - (NSString *) md5sum {
2498 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2502 @synchronized (database_) {
2503 if ([database_ era] != era_ || version_.end())
2506 return version_->InstalledSize;
2509 - (NSString *) longDescription {
2510 @synchronized (database_) {
2511 if ([database_ era] != era_ || file_.end())
2514 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2515 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2517 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2518 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2519 if ([lines count] < 2)
2522 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2523 for (size_t i(1), e([lines count]); i != e; ++i) {
2524 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2525 [trimmed addObject:trim];
2528 return [trimmed componentsJoinedByString:@"\n"];
2531 - (NSString *) shortDescription {
2532 if (parsed_ != NULL)
2533 return static_cast<NSString *>(parsed_->tagline_);
2535 @synchronized (database_) {
2536 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2538 const char *start, *end;
2539 if (!parser.ShortDesc(start, end))
2542 if (end - start > 200)
2546 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2549 while (end != start && end[-1] == '\r')
2553 return [(id) CYStringCreate(start, end - start) autorelease];
2557 _profile(Package$index)
2558 CFStringRef name((CFStringRef) [self name]);
2559 if (CFStringGetLength(name) == 0)
2561 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2562 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2564 return toupper(character);
2568 - (PackageValue *) metadata {
2573 PackageValue *metadata([self metadata]);
2574 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2577 - (bool) subscribed {
2578 return [self metadata]->subscribed_;
2581 - (bool) setSubscribed:(bool)subscribed {
2582 PackageValue *metadata([self metadata]);
2583 if (metadata->subscribed_ == subscribed)
2585 metadata->subscribed_ = subscribed;
2593 - (NSString *) latest {
2597 - (NSString *) installed {
2601 - (BOOL) uninstalled {
2602 return installed_.empty();
2606 return !version_.end();
2609 - (BOOL) upgradableAndEssential:(BOOL)essential {
2610 _profile(Package$upgradableAndEssential)
2611 pkgCache::VerIterator current(iterator_.CurrentVer());
2613 return essential && essential_;
2615 return !version_.end() && version_ != current;
2619 - (BOOL) essential {
2624 return [database_ cache][iterator_].InstBroken();
2627 - (BOOL) unfiltered {
2628 _profile(Package$unfiltered$obsolete)
2629 if (_unlikely(obsolete_))
2633 _profile(Package$unfiltered$hasSupportingRole)
2634 if (_unlikely(![self hasSupportingRole]))
2642 if (![self unfiltered])
2647 _profile(Package$visible$section)
2648 section = [self section];
2651 _profile(Package$visible$isSectionVisible)
2652 if (!isSectionVisible(section))
2660 unsigned char current(iterator_->CurrentState);
2661 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2664 - (BOOL) halfConfigured {
2665 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2668 - (BOOL) halfInstalled {
2669 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2673 @synchronized (database_) {
2674 if ([database_ era] != era_ || iterator_.end())
2677 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2678 return state.Mode != pkgDepCache::ModeKeep;
2681 - (NSString *) mode {
2682 @synchronized (database_) {
2683 if ([database_ era] != era_ || iterator_.end())
2686 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2688 switch (state.Mode) {
2689 case pkgDepCache::ModeDelete:
2690 if ((state.iFlags & pkgDepCache::Purge) != 0)
2694 case pkgDepCache::ModeKeep:
2695 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2696 return @"REINSTALL";
2697 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2701 case pkgDepCache::ModeInstall:
2702 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2703 return @"REINSTALL";
2704 else*/ switch (state.Status) {
2706 return @"DOWNGRADE";
2712 return @"NEW_INSTALL";
2723 - (NSString *) name {
2724 return name_.empty() ? id_ : name_;
2727 - (UIImage *) icon {
2728 NSString *section = [self simpleSection];
2731 if (parsed_ != NULL)
2732 if (NSString *href = parsed_->icon_)
2733 if ([href hasPrefix:@"file:///"])
2734 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2735 if (icon == nil) if (section != nil)
2736 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2737 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2738 if ([dicon hasPrefix:@"file:///"])
2739 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2741 icon = [UIImage applicationImageNamed:@"unknown.png"];
2745 - (NSString *) homepage {
2746 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2749 - (NSString *) depiction {
2750 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2753 - (MIMEAddress *) sponsor {
2754 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2757 - (MIMEAddress *) author {
2758 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2761 - (NSString *) support {
2762 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2765 - (NSArray *) files {
2766 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2767 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2770 fin.open([path UTF8String]);
2775 while (std::getline(fin, line))
2776 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2781 - (NSString *) state {
2782 @synchronized (database_) {
2783 if ([database_ era] != era_ || file_.end())
2786 switch (iterator_->CurrentState) {
2787 case pkgCache::State::NotInstalled:
2788 return @"NotInstalled";
2789 case pkgCache::State::UnPacked:
2791 case pkgCache::State::HalfConfigured:
2792 return @"HalfConfigured";
2793 case pkgCache::State::HalfInstalled:
2794 return @"HalfInstalled";
2795 case pkgCache::State::ConfigFiles:
2796 return @"ConfigFiles";
2797 case pkgCache::State::Installed:
2798 return @"Installed";
2799 case pkgCache::State::TriggersAwaited:
2800 return @"TriggersAwaited";
2801 case pkgCache::State::TriggersPending:
2802 return @"TriggersPending";
2805 return (NSString *) [NSNull null];
2808 - (NSString *) selection {
2809 @synchronized (database_) {
2810 if ([database_ era] != era_ || file_.end())
2813 switch (iterator_->SelectedState) {
2814 case pkgCache::State::Unknown:
2816 case pkgCache::State::Install:
2818 case pkgCache::State::Hold:
2820 case pkgCache::State::DeInstall:
2821 return @"DeInstall";
2822 case pkgCache::State::Purge:
2826 return (NSString *) [NSNull null];
2829 - (NSArray *) warnings {
2830 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2831 const char *name(iterator_.Name());
2833 size_t length(strlen(name));
2834 if (length < 2) invalid:
2835 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2836 else for (size_t i(0); i != length; ++i)
2838 /* XXX: technically this is not allowed */
2839 (name[i] < 'A' || name[i] > 'Z') &&
2840 (name[i] < 'a' || name[i] > 'z') &&
2841 (name[i] < '0' || name[i] > '9') &&
2842 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2845 if (strcmp(name, "cydia") != 0) {
2848 bool _private = false;
2851 bool repository = [[self section] isEqualToString:@"Repositories"];
2853 if (NSArray *files = [self files])
2854 for (NSString *file in files)
2855 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2857 else if (!user && [file isEqualToString:@"/User"])
2859 else if (!_private && [file isEqualToString:@"/private"])
2861 else if (!stash && [file isEqualToString:@"/var/stash"])
2864 /* XXX: this is not sensitive enough. only some folders are valid. */
2865 if (cydia && !repository)
2866 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2868 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2870 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2872 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2875 return [warnings count] == 0 ? nil : warnings;
2878 - (NSArray *) applications {
2879 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2881 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2883 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2884 if (NSArray *files = [self files])
2885 for (NSString *file in files)
2886 if (application_r(file)) {
2887 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2888 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2889 if ([id isEqualToString:me])
2892 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2894 display = application_r[1];
2896 NSString *bundle([file stringByDeletingLastPathComponent]);
2897 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2898 // XXX: maybe this should check if this is really a string, not just for length
2899 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
2901 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2903 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2904 [applications addObject:application];
2906 [application addObject:id];
2907 [application addObject:display];
2908 [application addObject:url];
2911 return [applications count] == 0 ? nil : applications;
2914 - (Source *) source {
2915 if (source_ == nil) {
2916 @synchronized (database_) {
2917 if ([database_ era] != era_ || file_.end())
2918 source_ = (Source *) [NSNull null];
2920 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2924 return source_ == (Source *) [NSNull null] ? nil : source_;
2931 - (BOOL) matches:(NSArray *)query {
2932 if (query == nil || [query count] == 0)
2941 string = [self name];
2942 length = [string length];
2944 for (NSString *term in query) {
2945 range = [string rangeOfString:term options:MatchCompareOptions_];
2946 if (range.location != NSNotFound)
2947 rank_ -= 6 * 1000000 / length;
2952 length = [string length];
2954 for (NSString *term in query) {
2955 range = [string rangeOfString:term options:MatchCompareOptions_];
2956 if (range.location != NSNotFound)
2957 rank_ -= 6 * 1000000 / length;
2961 string = [self shortDescription];
2962 length = [string length];
2963 NSUInteger stop(std::min<NSUInteger>(length, 200));
2965 for (NSString *term in query) {
2966 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2967 if (range.location != NSNotFound)
2968 rank_ -= 2 * 100000;
2974 - (bool) hasSupportingRole {
2979 if ([Role_ isEqualToString:@"User"])
2983 if ([Role_ isEqualToString:@"Hacker"])
2987 if ([Role_ isEqualToString:@"Developer"])
2992 - (NSArray *) tags {
2996 - (BOOL) hasTag:(NSString *)tag {
2997 return tags_ == nil ? NO : [tags_ containsObject:tag];
3000 - (NSString *) primaryPurpose {
3001 for (NSString *tag in (NSArray *) tags_)
3002 if ([tag hasPrefix:@"purpose::"])
3003 return [tag substringFromIndex:9];
3007 - (NSArray *) purposes {
3008 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3009 for (NSString *tag in (NSArray *) tags_)
3010 if ([tag hasPrefix:@"purpose::"])
3011 [purposes addObject:[tag substringFromIndex:9]];
3012 return [purposes count] == 0 ? nil : purposes;
3015 - (bool) isCommercial {
3016 return [self hasTag:@"cydia::commercial"];
3019 - (void) setIndex:(size_t)index {
3020 if (metadata_->index_ != index)
3021 metadata_->index_ = index;
3024 - (CYString &) cyname {
3025 return name_.empty() ? id_ : name_;
3028 - (uint32_t) compareBySection:(NSArray *)sections {
3029 NSString *section([self section]);
3030 for (size_t i(0), e([sections count]); i != e; ++i) {
3031 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3035 return _not(uint32_t);
3039 @synchronized (database_) {
3040 pkgProblemResolver *resolver = [database_ resolver];
3041 resolver->Clear(iterator_);
3043 pkgCacheFile &cache([database_ cache]);
3044 cache->SetReInstall(iterator_, false);
3045 cache->MarkKeep(iterator_, false);
3049 @synchronized (database_) {
3050 pkgProblemResolver *resolver = [database_ resolver];
3051 resolver->Clear(iterator_);
3052 resolver->Protect(iterator_);
3054 pkgCacheFile &cache([database_ cache]);
3055 cache->SetReInstall(iterator_, false);
3056 cache->MarkInstall(iterator_, false);
3058 pkgDepCache::StateCache &state((*cache)[iterator_]);
3059 if (!state.Install())
3060 cache->SetReInstall(iterator_, true);
3064 @synchronized (database_) {
3065 pkgProblemResolver *resolver = [database_ resolver];
3066 resolver->Clear(iterator_);
3067 resolver->Remove(iterator_);
3068 resolver->Protect(iterator_);
3070 pkgCacheFile &cache([database_ cache]);
3071 cache->SetReInstall(iterator_, false);
3072 cache->MarkDelete(iterator_, true);
3075 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3076 _profile(Package$isUnfilteredAndSearchedForBy)
3079 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3080 value &= [self unfiltered];
3083 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3084 value &= [self matches:query];
3091 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3092 if ([search length] == 0)
3095 _profile(Package$isUnfilteredAndSelectedForBy)
3098 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3099 value &= [self unfiltered];
3102 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3103 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3110 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3111 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3114 - (bool) isVisibleInSection:(NSString *)name {
3115 NSString *section([self section]);
3119 section == nil && [name length] == 0 ||
3120 [name isEqualToString:section]
3121 ) && [self visible];
3124 - (bool) isVisibleInSource:(Source *)source {
3125 return [self source] == source && [self visible];
3130 /* Section Class {{{ */
3131 @interface Section : NSObject {
3136 _H<NSString> localized_;
3139 - (NSComparisonResult) compareByLocalized:(Section *)section;
3140 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3141 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3142 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3143 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3144 - (NSString *) name;
3151 - (void) addToCount;
3153 - (void) setCount:(size_t)count;
3154 - (NSString *) localized;
3158 @implementation Section
3160 - (NSComparisonResult) compareByLocalized:(Section *)section {
3161 NSString *lhs(localized_);
3162 NSString *rhs([section localized]);
3164 /*if ([lhs length] != 0 && [rhs length] != 0) {
3165 unichar lhc = [lhs characterAtIndex:0];
3166 unichar rhc = [rhs characterAtIndex:0];
3168 if (isalpha(lhc) && !isalpha(rhc))
3169 return NSOrderedAscending;
3170 else if (!isalpha(lhc) && isalpha(rhc))
3171 return NSOrderedDescending;
3174 return [lhs compare:rhs options:LaxCompareOptions_];
3177 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3178 if ((self = [self initWithName:name localize:NO]) != nil) {
3179 if (localized != nil)
3180 localized_ = localized;
3184 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3185 return [self initWithName:name row:0 localize:localize];
3188 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3189 if ((self = [super init]) != nil) {
3194 localized_ = LocalizeSection(name_);
3198 /* XXX: localize the index thingees */
3199 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3200 if ((self = [super init]) != nil) {
3201 name_ = [NSString stringWithCharacters:&index length:1];
3207 - (NSString *) name {
3227 - (void) addToCount {
3231 - (void) setCount:(size_t)count {
3235 - (NSString *) localized {
3242 class CydiaLogCleaner :
3243 public pkgArchiveCleaner
3246 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3251 /* Database Implementation {{{ */
3252 @implementation Database
3254 + (Database *) sharedInstance {
3255 static _H<Database> instance;
3256 if (instance == nil)
3257 instance = [[[Database alloc] init] autorelease];
3265 - (void) releasePackages {
3266 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3267 CFArrayRemoveAllValues(packages_);
3271 // XXX: actually implement this thing
3273 [self releasePackages];
3274 apr_pool_destroy(pool_);
3275 NSRecycleZone(zone_);
3279 - (void) _readCydia:(NSNumber *)fd {
3280 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3281 std::istream is(&ib);
3284 static Pcre finish_r("^finish:([^:]*)$");
3286 while (std::getline(is, line)) {
3287 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3289 const char *data(line.c_str());
3290 size_t size = line.size();
3291 lprintf("C:%s\n", data);
3293 if (finish_r(data, size)) {
3294 NSString *finish = finish_r[1];
3295 int index = [Finishes_ indexOfObject:finish];
3296 if (index != INT_MAX && index > Finish_)
3306 - (void) _readStatus:(NSNumber *)fd {
3307 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3308 std::istream is(&ib);
3311 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3312 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3314 while (std::getline(is, line)) {
3315 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3317 const char *data(line.c_str());
3318 size_t size(line.size());
3319 lprintf("S:%s\n", data);
3321 if (conffile_r(data, size)) {
3322 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3323 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3324 } else if (strncmp(data, "status: ", 8) == 0) {
3325 // status: <package>: {unpacked,half-configured,installed}
3326 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3327 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3328 } else if (strncmp(data, "processing: ", 12) == 0) {
3329 // processing: configure: config-test
3330 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3331 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3332 } else if (pmstatus_r(data, size)) {
3333 std::string type([pmstatus_r[1] UTF8String]);
3335 NSString *package = pmstatus_r[2];
3336 if ([package isEqualToString:@"dpkg-exec"])
3339 float percent([pmstatus_r[3] floatValue]);
3340 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3342 NSString *string = pmstatus_r[4];
3344 if (type == "pmerror") {
3345 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3346 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3347 } else if (type == "pmstatus") {
3348 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3349 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3350 } else if (type == "pmconffile")
3351 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3353 lprintf("E:unknown pmstatus\n");
3355 lprintf("E:unknown status\n");
3363 - (void) _readOutput:(NSNumber *)fd {
3364 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3365 std::istream is(&ib);
3368 while (std::getline(is, line)) {
3369 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3371 lprintf("O:%s\n", line.c_str());
3373 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3374 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3386 - (Package *) packageWithName:(NSString *)name {
3389 @synchronized (self) {
3390 if (static_cast<pkgDepCache *>(cache_) == NULL)
3392 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3393 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3397 if ((self = [super init]) != nil) {
3404 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3405 apr_pool_create(&pool_, NULL);
3407 size_t capacity(MetaFile_->active_);
3413 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3414 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3418 _assert(pipe(fds) != -1);
3421 _config->Set("APT::Keep-Fds::", cydiafd_);
3422 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3425 detachNewThreadSelector:@selector(_readCydia:)
3427 withObject:[NSNumber numberWithInt:fds[0]]
3430 _assert(pipe(fds) != -1);
3434 detachNewThreadSelector:@selector(_readStatus:)
3436 withObject:[NSNumber numberWithInt:fds[0]]
3439 _assert(pipe(fds) != -1);
3440 _assert(dup2(fds[0], 0) != -1);
3441 _assert(close(fds[0]) != -1);
3443 input_ = fdopen(fds[1], "a");
3445 _assert(pipe(fds) != -1);
3446 _assert(dup2(fds[1], 1) != -1);
3447 _assert(close(fds[1]) != -1);
3450 detachNewThreadSelector:@selector(_readOutput:)
3452 withObject:[NSNumber numberWithInt:fds[0]]
3457 - (pkgCacheFile &) cache {
3461 - (pkgDepCache::Policy *) policy {
3465 - (pkgRecords *) records {
3469 - (pkgProblemResolver *) resolver {
3473 - (pkgAcquire &) fetcher {
3477 - (pkgSourceList &) list {
3481 - (NSArray *) packages {
3482 return (NSArray *) packages_;
3485 - (NSArray *) sources {
3489 - (Source *) sourceWithKey:(NSString *)key {
3490 for (Source *source in [self sources]) {
3491 if ([[source key] isEqualToString:key])
3496 - (bool) popErrorWithTitle:(NSString *)title {
3499 while (!_error->empty()) {
3501 bool warning(!_error->PopMessage(error));
3506 size_t size(error.size());
3507 if (size == 0 || error[size - 1] != '\n')
3509 error.resize(size - 1);
3512 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3514 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3515 if (warning && no_pubkey(error.c_str()))
3518 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3524 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3525 return [self popErrorWithTitle:title] || !success;
3528 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3529 @synchronized (self) {
3532 [self releasePackages];
3535 [sourceList_ removeAllObjects];
3555 apr_pool_clear(pool_);
3557 NSRecycleZone(zone_);
3558 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3560 int chk(creat("/tmp/cydia.chk", 0644));
3564 if (invocation != nil)
3565 [invocation invoke];
3567 NSString *title(UCLocalize("DATABASE"));
3569 list_ = new pkgSourceList();
3570 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3573 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3574 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3575 [sourceList_ addObject:object];
3579 OpProgress progress;
3581 if (!cache_.Open(progress, true)) {
3582 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3583 while (!_error->empty()) {
3585 bool warning(!_error->PopMessage(error));
3587 lprintf("cache_.Open():[%s]\n", error.c_str());
3589 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3593 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3594 repair = @selector(configure);
3595 //else if (error == "The package lists or status file could not be parsed or opened.")
3596 // repair = @selector(update);
3597 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3598 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3599 // else if (error == "Malformed Status line")
3600 // else if (error == "The list of sources could not be read.")
3602 if (repair != NULL) {
3604 [delegate_ repairWithSelector:repair];
3613 unlink("/tmp/cydia.chk");
3615 now_ = [[NSDate date] timeIntervalSince1970];
3617 policy_ = new pkgDepCache::Policy();
3618 records_ = new pkgRecords(cache_);
3619 resolver_ = new pkgProblemResolver(cache_);
3620 fetcher_ = new pkgAcquire(&status_);
3623 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3624 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3628 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3631 if (cache_->BrokenCount() != 0) {
3632 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3635 if (cache_->BrokenCount() != 0) {
3636 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3640 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3644 for (Source *object in (id) sourceList_) {
3645 metaIndex *source([object metaIndex]);
3646 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3647 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3648 // XXX: this could be more intelligent
3649 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3650 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3652 sourceMap_[cached->ID] = object;
3657 /*std::vector<Package *> packages;
3658 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3663 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3664 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3665 //packages.push_back(package);
3666 CFArrayAppendValue(packages_, CFRetain(package));
3670 /*if (packages.empty())
3671 packages_ = [[NSArray alloc] init];
3673 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3676 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3677 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3678 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3686 /*if (!packages.empty())
3687 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3688 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3690 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3692 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3694 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3698 size_t count(CFArrayGetCount(packages_));
3699 MetaFile_->active_ = count;
3701 for (size_t index(0); index != count; ++index)
3702 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3709 @synchronized (self) {
3711 resolver_ = new pkgProblemResolver(cache_);
3713 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3714 if (!cache_[iterator].Keep())
3715 cache_->MarkKeep(iterator, false);
3716 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3717 cache_->SetReInstall(iterator, false);
3720 - (void) configure {
3721 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3723 system([dpkg UTF8String]);
3728 @synchronized (self) {
3729 // XXX: I don't remember this condition
3734 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3736 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3738 if ([self popErrorWithTitle:title])
3742 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3744 CydiaLogCleaner cleaner;
3745 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3752 fetcher_->Shutdown();
3754 pkgRecords records(cache_);
3756 lock_ = new FileFd();
3757 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3759 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3761 if ([self popErrorWithTitle:title])
3765 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3768 manager_ = (_system->CreatePM(cache_));
3769 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3776 bool substrate(RestartSubstrate_);
3777 RestartSubstrate_ = false;
3779 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3781 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3783 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3785 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3786 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3789 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3791 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3793 [self popErrorWithTitle:title];
3797 bool failed = false;
3798 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3799 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3801 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3804 std::string uri = (*item)->DescURI();
3805 std::string error = (*item)->ErrorText;
3807 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3810 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3811 [delegate_ addProgressEventOnMainThread:event forTask:title];
3814 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3822 RestartSubstrate_ = true;
3825 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3826 if ([self popErrorWithTitle:title])
3829 if (result == pkgPackageManager::Failed) {
3834 if (result != pkgPackageManager::Completed) {
3839 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3841 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3843 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3844 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3847 if (![before isEqualToArray:after])
3852 NSString *title(UCLocalize("UPGRADE"));
3853 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3859 [self updateWithStatus:status_];
3862 - (void) updateWithStatus:(Status &)status {
3863 NSString *title(UCLocalize("REFRESHING_DATA"));
3866 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3870 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3871 if ([self popErrorWithTitle:title])
3874 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3876 bool success(ListUpdate(status, list, PulseInterval_));
3877 if (status.WasCancelled())
3880 [self popErrorWithTitle:title forOperation:success];
3881 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3885 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3888 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3889 delegate_ = delegate;
3892 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3893 progress_ = delegate;
3894 status_.setDelegate(delegate);
3897 - (NSObject<ProgressDelegate> *) progressDelegate {
3901 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3902 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3903 return i == sourceMap_.end() ? nil : i->second;
3906 - (NSString *) mappedSectionForPointer:(const char *)section {
3907 _H<NSString> *mapped;
3909 _profile(Database$mappedSectionForPointer$Cache)
3910 mapped = §ions_[section];
3913 if (*mapped == NULL) {
3914 size_t length(strlen(section));
3915 char spaced[length + 1];
3917 _profile(Database$mappedSectionForPointer$Replace)
3918 for (size_t index(0); index != length; ++index)
3919 spaced[index] = section[index] == '_' ? ' ' : section[index];
3920 spaced[length] = '\0';
3925 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3926 string = [NSString stringWithUTF8String:spaced];
3929 _profile(Database$mappedSectionForPointer$Map)
3930 string = [SectionMap_ objectForKey:string] ?: string;
3940 static _H<NSMutableSet> Diversions_;
3942 @interface Diversion : NSObject {
3945 _H<NSString> format_;
3950 @implementation Diversion
3952 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3953 if ((self = [super init]) != nil) {
3954 pattern_ = [from UTF8String];
3960 - (NSString *) divert:(NSString *)url {
3961 return !pattern_(url) ? nil : pattern_->*format_;
3964 + (NSURL *) divertURL:(NSURL *)url {
3966 NSString *href([url absoluteString]);
3968 for (Diversion *diversion in (id) Diversions_)
3969 if (NSString *diverted = [diversion divert:href]) {
3971 NSLog(@"div: %@", diverted);
3973 url = [NSURL URLWithString:diverted];
3980 - (NSString *) key {
3984 - (NSUInteger) hash {
3988 - (BOOL) isEqual:(Diversion *)object {
3989 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3994 @interface CydiaObject : NSObject {
3995 _H<CyteWebViewController> indirect_;
3996 _transient id delegate_;
3999 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4005 @interface CydiaWebViewController : CyteWebViewController {
4006 _H<CydiaObject> cydia_;
4009 + (void) addDiversion:(Diversion *)diversion;
4010 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4011 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4012 - (void) setDelegate:(id)delegate;
4016 /* Web Scripting {{{ */
4017 @implementation CydiaObject
4019 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4020 if ((self = [super init]) != nil) {
4021 indirect_ = (CyteWebViewController *) indirect;
4025 - (void) setDelegate:(id)delegate {
4026 delegate_ = delegate;
4029 + (NSArray *) _attributeKeys {
4030 return [NSArray arrayWithObjects:
4033 @"coreFoundationVersionNumber",
4050 - (NSArray *) attributeKeys {
4051 return [[self class] _attributeKeys];
4054 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4055 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4058 - (NSString *) version {
4062 - (NSString *) build {
4066 - (NSString *) coreFoundationVersionNumber {
4067 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4070 - (NSString *) device {
4071 return UniqueIdentifier();
4074 - (NSString *) firmware {
4075 return [[UIDevice currentDevice] systemVersion];
4078 - (NSString *) hostname {
4079 return [[UIDevice currentDevice] name];
4082 - (NSString *) idiom {
4083 return (id) Idiom_ ?: [NSNull null];
4086 - (NSString *) mcc {
4087 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4088 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4092 - (NSString *) mnc {
4093 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4094 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4098 - (NSString *) operator {
4099 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4100 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4104 - (NSString *) bbsnum {
4105 return (id) BBSNum_ ?: [NSNull null];
4108 - (NSString *) ecid {
4109 return (id) ChipID_ ?: [NSNull null];
4112 - (NSString *) serial {
4113 return SerialNumber_;
4116 - (NSString *) role {
4117 return (id) Role_ ?: [NSNull null];
4120 - (NSString *) model {
4121 return [NSString stringWithUTF8String:Machine_];
4124 - (NSString *) token {
4125 return (id) Token_ ?: [NSNull null];
4128 + (NSString *) webScriptNameForSelector:(SEL)selector {
4130 else if (selector == @selector(addBridgedHost:))
4131 return @"addBridgedHost";
4132 else if (selector == @selector(addInsecureHost:))
4133 return @"addInsecureHost";
4134 else if (selector == @selector(addInternalRedirect::))
4135 return @"addInternalRedirect";
4136 else if (selector == @selector(addPipelinedHost:scheme:))
4137 return @"addPipelinedHost";
4138 else if (selector == @selector(addSource:::))
4139 return @"addSource";
4140 else if (selector == @selector(addTokenHost:))
4141 return @"addTokenHost";
4142 else if (selector == @selector(addTrivialSource:))
4143 return @"addTrivialSource";
4144 else if (selector == @selector(close))
4146 else if (selector == @selector(du:))
4148 else if (selector == @selector(stringWithFormat:arguments:))
4150 else if (selector == @selector(getAllSources))
4151 return @"getAllSources";
4152 else if (selector == @selector(getKernelNumber:))
4153 return @"getKernelNumber";
4154 else if (selector == @selector(getKernelString:))
4155 return @"getKernelString";
4156 else if (selector == @selector(getInstalledPackages))
4157 return @"getInstalledPackages";
4158 else if (selector == @selector(getIORegistryEntry::))
4159 return @"getIORegistryEntry";
4160 else if (selector == @selector(getLocaleIdentifier))
4161 return @"getLocaleIdentifier";
4162 else if (selector == @selector(getPreferredLanguages))
4163 return @"getPreferredLanguages";
4164 else if (selector == @selector(getPackageById:))
4165 return @"getPackageById";
4166 else if (selector == @selector(getMetadataKeys))
4167 return @"getMetadataKeys";
4168 else if (selector == @selector(getMetadataValue:))
4169 return @"getMetadataValue";
4170 else if (selector == @selector(getSessionValue:))
4171 return @"getSessionValue";
4172 else if (selector == @selector(installPackages:))
4173 return @"installPackages";
4174 else if (selector == @selector(isReachable:))
4175 return @"isReachable";
4176 else if (selector == @selector(localizedStringForKey:value:table:))
4178 else if (selector == @selector(popViewController:))
4179 return @"popViewController";
4180 else if (selector == @selector(refreshSources))
4181 return @"refreshSources";
4182 else if (selector == @selector(registerFrame:))
4183 return @"registerFrame";
4184 else if (selector == @selector(removeButton))
4185 return @"removeButton";
4186 else if (selector == @selector(saveConfig))
4187 return @"saveConfig";
4188 else if (selector == @selector(setMetadataValue::))
4189 return @"setMetadataValue";
4190 else if (selector == @selector(setSessionValue::))
4191 return @"setSessionValue";
4192 else if (selector == @selector(setShowPromoted:))
4193 return @"setShowPromoted";
4194 else if (selector == @selector(substitutePackageNames:))
4195 return @"substitutePackageNames";
4196 else if (selector == @selector(scrollToBottom:))
4197 return @"scrollToBottom";
4198 else if (selector == @selector(setAllowsNavigationAction:))
4199 return @"setAllowsNavigationAction";
4200 else if (selector == @selector(setBadgeValue:))
4201 return @"setBadgeValue";
4202 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4203 return @"setButtonImage";
4204 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4205 return @"setButtonTitle";
4206 else if (selector == @selector(setHidesBackButton:))
4207 return @"setHidesBackButton";
4208 else if (selector == @selector(setHidesNavigationBar:))
4209 return @"setHidesNavigationBar";
4210 else if (selector == @selector(setNavigationBarStyle:))
4211 return @"setNavigationBarStyle";
4212 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4213 return @"setNavigationBarTintColor";
4214 else if (selector == @selector(setPasteboardString:))
4215 return @"setPasteboardString";
4216 else if (selector == @selector(setPasteboardURL:))
4217 return @"setPasteboardURL";
4218 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4219 return @"setScrollAlwaysBounceVertical";
4220 else if (selector == @selector(setScrollIndicatorStyle:))
4221 return @"setScrollIndicatorStyle";
4222 else if (selector == @selector(setToken:))
4224 else if (selector == @selector(setViewportWidth:))
4225 return @"setViewportWidth";
4226 else if (selector == @selector(statfs:))
4228 else if (selector == @selector(supports:))
4230 else if (selector == @selector(unload))
4236 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4237 return [self webScriptNameForSelector:selector] == nil;
4240 - (BOOL) supports:(NSString *)feature {
4241 return [feature isEqualToString:@"window.open"];
4245 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4248 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4249 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4252 - (void) setScrollIndicatorStyle:(NSString *)style {
4253 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4256 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4257 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4260 - (NSNumber *) getKernelNumber:(NSString *)name {
4261 const char *string([name UTF8String]);
4264 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4265 return (id) [NSNull null];
4267 if (size != sizeof(int))
4268 return (id) [NSNull null];
4271 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4272 return (id) [NSNull null];
4274 return [NSNumber numberWithInt:value];
4277 - (NSString *) getKernelString:(NSString *)name {
4278 const char *string([name UTF8String]);
4281 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4282 return (id) [NSNull null];
4284 char value[size + 1];
4285 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4286 return (id) [NSNull null];
4288 // XXX: just in case you request something ludicrous
4291 return [NSString stringWithCString:value];
4294 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4295 NSObject *value(CYIOGetValue([path UTF8String], entry));
4298 if ([value isKindOfClass:[NSData class]])
4299 value = CYHex((NSData *) value);
4304 - (NSArray *) getMetadataKeys {
4305 @synchronized (Values_) {
4306 return [Values_ allKeys];
4309 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4310 WebFrame *frame([iframe contentFrame]);
4311 [indirect_ registerFrame:frame];
4314 - (void) _setShowPromoted:(NSNumber *)value {
4315 [Metadata_ setObject:value forKey:@"ShowPromoted"];
4319 - (void) setShowPromoted:(NSNumber *)value {
4320 [self performSelectorOnMainThread:@selector(_setShowPromoted:) withObject:value waitUntilDone:NO];
4323 - (id) getMetadataValue:(NSString *)key {
4324 @synchronized (Values_) {
4325 return [Values_ objectForKey:key];
4328 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4329 @synchronized (Values_) {
4330 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4331 [Values_ removeObjectForKey:key];
4333 [Values_ setObject:value forKey:key];
4335 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4338 - (id) getSessionValue:(NSString *)key {
4339 @synchronized (SessionData_) {
4340 return [SessionData_ objectForKey:key];
4343 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4344 @synchronized (SessionData_) {
4345 if (value == (id) [WebUndefined undefined])
4346 [SessionData_ removeObjectForKey:key];
4348 [SessionData_ setObject:value forKey:key];
4351 - (void) addBridgedHost:(NSString *)host {
4352 @synchronized (HostConfig_) {
4353 [BridgedHosts_ addObject:host];
4356 - (void) addInsecureHost:(NSString *)host {
4357 @synchronized (HostConfig_) {
4358 [InsecureHosts_ addObject:host];
4361 - (void) addTokenHost:(NSString *)host {
4362 @synchronized (HostConfig_) {
4363 [TokenHosts_ addObject:host];
4366 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4367 @synchronized (HostConfig_) {
4368 if (scheme != (id) [WebUndefined undefined])
4369 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4371 [PipelinedHosts_ addObject:host];
4374 - (void) popViewController:(NSNumber *)value {
4375 if (value == (id) [WebUndefined undefined])
4376 value = [NSNumber numberWithBool:YES];
4377 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4380 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4381 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4383 for (NSString *section in sections)
4384 [array addObject:section];
4386 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4389 distribution, @"Distribution",
4391 nil] waitUntilDone:NO];
4394 - (void) addTrivialSource:(NSString *)href {
4395 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4398 - (void) refreshSources {
4399 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4402 - (void) saveConfig {
4403 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4406 - (NSArray *) getAllSources {
4407 return [[Database sharedInstance] sources];
4410 - (NSArray *) getInstalledPackages {
4411 Database *database([Database sharedInstance]);
4412 @synchronized (database) {
4413 NSArray *packages([database packages]);
4414 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4415 for (Package *package in packages)
4416 if (![package uninstalled])
4417 [installed addObject:package];
4421 - (Package *) getPackageById:(NSString *)id {
4422 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4426 return (Package *) [NSNull null];
4429 - (NSString *) getLocaleIdentifier {
4430 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4433 - (NSArray *) getPreferredLanguages {
4437 - (NSArray *) statfs:(NSString *)path {
4440 if (path == nil || statfs([path UTF8String], &stat) == -1)
4443 return [NSArray arrayWithObjects:
4444 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4445 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4446 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4450 - (NSNumber *) du:(NSString *)path {
4451 NSNumber *value(nil);
4454 _assert(pipe(fds) != -1);
4456 pid_t pid(ExecFork());
4458 _assert(dup2(fds[1], 1) != -1);
4459 _assert(close(fds[0]) != -1);
4460 _assert(close(fds[1]) != -1);
4461 /* XXX: this should probably not use du */
4462 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4467 _assert(close(fds[1]) != -1);
4469 if (FILE *du = fdopen(fds[0], "r")) {
4471 while (fgets(line, sizeof(line), du) != NULL) {
4472 size_t length(strlen(line));
4473 while (length != 0 && line[length - 1] == '\n')
4474 line[--length] = '\0';
4475 if (char *tab = strchr(line, '\t')) {
4477 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4482 } else _assert(close(fds[0]));
4490 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4493 - (NSNumber *) isReachable:(NSString *)name {
4494 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4497 - (void) installPackages:(NSArray *)packages {
4498 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4501 - (NSString *) substitutePackageNames:(NSString *)message {
4502 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4503 for (size_t i(0), e([words count]); i != e; ++i) {
4504 NSString *word([words objectAtIndex:i]);
4505 if (Package *package = [[Database sharedInstance] packageWithName:word])
4506 [words replaceObjectAtIndex:i withObject:[package name]];
4509 return [words componentsJoinedByString:@" "];
4512 - (void) removeButton {
4513 [indirect_ removeButton];
4516 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4517 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4520 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4521 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4524 - (void) setBadgeValue:(id)value {
4525 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4528 - (void) setAllowsNavigationAction:(NSString *)value {
4529 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4532 - (void) setHidesBackButton:(NSString *)value {
4533 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4536 - (void) setHidesNavigationBar:(NSString *)value {
4537 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4540 - (void) setNavigationBarStyle:(NSString *)value {
4541 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4544 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4545 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4546 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4547 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4550 - (void) setPasteboardString:(NSString *)value {
4551 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4554 - (void) setPasteboardURL:(NSString *)value {
4555 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4558 - (void) _setToken:(NSString *)token {
4562 [Metadata_ removeObjectForKey:@"Token"];
4564 [Metadata_ setObject:Token_ forKey:@"Token"];
4569 - (void) setToken:(NSString *)token {
4570 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4573 - (void) scrollToBottom:(NSNumber *)animated {
4574 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4577 - (void) setViewportWidth:(float)width {
4578 [indirect_ setViewportWidthOnMainThread:width];
4581 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4582 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4583 unsigned count([arguments count]);
4585 for (unsigned i(0); i != count; ++i)
4586 values[i] = [arguments objectAtIndex:i];
4587 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4590 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4591 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4593 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4595 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4601 @interface NSURL (CydiaSecure)
4604 @implementation NSURL (CydiaSecure)
4606 - (bool) isCydiaSecure {
4607 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4610 @synchronized (HostConfig_) {
4611 if ([InsecureHosts_ containsObject:[self host]])
4620 /* Cydia Browser Controller {{{ */
4621 @implementation CydiaWebViewController
4623 - (NSURL *) navigationURL {
4624 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4627 + (void) _initialize {
4628 [super _initialize];
4630 Diversions_ = [NSMutableSet setWithCapacity:0];
4633 + (void) addDiversion:(Diversion *)diversion {
4634 [Diversions_ addObject:diversion];
4637 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4638 [super webView:view didClearWindowObject:window forFrame:frame];
4639 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4642 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4643 WebDataSource *source([frame dataSource]);
4644 NSURLResponse *response([source response]);
4645 NSURL *url([response URL]);
4646 NSString *scheme([[url scheme] lowercaseString]);
4648 bool bridged(false);
4650 @synchronized (HostConfig_) {
4651 if ([scheme isEqualToString:@"file"])
4653 else if ([scheme isEqualToString:@"https"])
4654 if ([BridgedHosts_ containsObject:[url host]])
4659 [window setValue:cydia forKey:@"cydia"];
4662 - (void) _setupMail:(MFMailComposeViewController *)controller {
4663 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4665 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4666 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4669 - (NSURL *) URLWithURL:(NSURL *)url {
4670 return [Diversion divertURL:url];
4673 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4674 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4677 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4678 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4680 NSURL *url([copy URL]);
4681 NSString *href([url absoluteString]);
4682 NSString *host([url host]);
4684 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4685 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4686 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4687 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4690 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4691 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4693 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4697 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4698 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4699 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4700 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4705 @synchronized (HostConfig_) {
4706 bridged = [BridgedHosts_ containsObject:host];
4707 token = [TokenHosts_ containsObject:host];
4710 if ([url isCydiaSecure]) {
4712 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4713 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4715 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4716 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4723 - (void) setDelegate:(id)delegate {
4724 [super setDelegate:delegate];
4725 [cydia_ setDelegate:delegate];
4728 - (NSString *) applicationNameForUserAgent {
4733 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4734 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4740 @interface AppCacheController : CydiaWebViewController {
4745 @implementation AppCacheController
4747 - (void) didReceiveMemoryWarning {
4748 // XXX: this doesn't work
4751 - (bool) retainsNetworkActivityIndicator {
4759 @interface NSObject (CydiaScript)
4760 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4763 @implementation NSObject (CydiaScript)
4765 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4771 @implementation NSArray (CydiaScript)
4773 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4774 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4775 for (size_t i(0), e([self count]); i != e; ++i)
4776 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4782 @implementation NSDictionary (CydiaScript)
4784 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4785 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4787 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4794 /* Confirmation Controller {{{ */
4795 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4796 if (!iterator.end())
4797 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4798 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4800 pkgCache::PkgIterator package(dep.TargetPkg());
4803 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4810 @protocol ConfirmationControllerDelegate
4811 - (void) cancelAndClear:(bool)clear;
4812 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4816 @interface ConfirmationController : CydiaWebViewController {
4817 _transient Database *database_;
4819 _H<UIAlertView> essential_;
4821 _H<NSDictionary> changes_;
4822 _H<NSMutableArray> issues_;
4823 _H<NSDictionary> sizes_;
4828 - (id) initWithDatabase:(Database *)database;
4832 @implementation ConfirmationController
4836 RestartSubstrate_ = true;
4837 [delegate_ confirmWithNavigationController:[self navigationController]];
4840 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4841 NSString *context([alert context]);
4843 if ([context isEqualToString:@"remove"]) {
4844 if (button == [alert cancelButtonIndex])
4845 [self dismissModalViewControllerAnimated:YES];
4846 else if (button == [alert firstOtherButtonIndex]) {
4847 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
4850 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4851 } else if ([context isEqualToString:@"unable"]) {
4852 [self dismissModalViewControllerAnimated:YES];
4853 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4855 [super alertView:alert clickedButtonAtIndex:button];
4859 - (void) _doContinue {
4860 [delegate_ cancelAndClear:NO];
4861 [self dismissModalViewControllerAnimated:YES];
4864 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4865 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4869 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4870 [super webView:view didClearWindowObject:window forFrame:frame];
4872 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4873 (id) changes_, @"changes",
4874 (id) issues_, @"issues",
4875 (id) sizes_, @"sizes",
4877 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4880 - (id) initWithDatabase:(Database *)database {
4881 if ((self = [super init]) != nil) {
4882 database_ = database;
4884 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4885 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4886 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4887 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4888 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4892 pkgCacheFile &cache([database_ cache]);
4893 NSArray *packages([database_ packages]);
4894 pkgDepCache::Policy *policy([database_ policy]);
4896 issues_ = [NSMutableArray arrayWithCapacity:4];
4898 for (Package *package in packages) {
4899 pkgCache::PkgIterator iterator([package iterator]);
4900 NSString *name([package id]);
4902 if ([package broken]) {
4903 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4905 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4907 reasons, @"reasons",
4910 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4914 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4915 pkgCache::DepIterator start;
4916 pkgCache::DepIterator end;
4917 dep.GlobOr(start, end); // ++dep
4919 if (!cache->IsImportantDep(end))
4921 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4924 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4926 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4927 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4928 clauses, @"clauses",
4932 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4934 pkgCache::PkgIterator target(start.TargetPkg());
4935 if (target->ProvidesList != 0)
4936 reason = @"missing";
4938 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4940 reason = @"installed";
4941 installed = [NSString stringWithUTF8String:ver.VerStr()];
4942 } else if (!cache[target].CandidateVerIter(cache).end())
4943 reason = @"uninstalled";
4944 else if (target->ProvidesList == 0)
4945 reason = @"uninstallable";
4947 reason = @"virtual";
4950 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4951 [NSString stringWithUTF8String:start.CompType()], @"operator",
4952 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4955 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4956 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4957 version, @"version",
4959 installed, @"installed",
4962 // yes, seriously. (wtf?)
4970 pkgDepCache::StateCache &state(cache[iterator]);
4972 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4974 if (state.NewInstall())
4975 [installs addObject:name];
4976 // XXX: else if (state.Install())
4977 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4978 [reinstalls addObject:name];
4979 // XXX: move before previous if
4980 else if (state.Upgrade())
4981 [upgrades addObject:name];
4982 else if (state.Downgrade())
4983 [downgrades addObject:name];
4984 else if (!state.Delete())
4985 // XXX: _assert(state.Keep());
4987 else if (special_r(name))
4988 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4989 [NSNull null], @"package",
4990 [NSArray arrayWithObjects:
4991 [NSDictionary dictionaryWithObjectsAndKeys:
4992 @"Conflicts", @"relationship",
4993 [NSArray arrayWithObjects:
4994 [NSDictionary dictionaryWithObjectsAndKeys:
4996 [NSNull null], @"version",
4997 @"installed", @"reason",
5004 if ([package essential])
5006 [removes addObject:name];
5009 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5010 substrate_ |= DepSubstrate(iterator.CurrentVer());
5015 else if (Advanced_) {
5016 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5018 essential_ = [[[UIAlertView alloc]
5019 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5020 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5022 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5024 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5028 [essential_ setContext:@"remove"];
5029 [essential_ setNumberOfRows:2];
5031 essential_ = [[[UIAlertView alloc]
5032 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5033 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5035 cancelButtonTitle:UCLocalize("OKAY")
5036 otherButtonTitles:nil
5039 [essential_ setContext:@"unable"];
5042 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5043 installs, @"installs",
5044 reinstalls, @"reinstalls",
5045 upgrades, @"upgrades",
5046 downgrades, @"downgrades",
5047 removes, @"removes",
5050 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5051 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5052 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5055 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5059 - (UIBarButtonItem *) leftButton {
5060 return [[[UIBarButtonItem alloc]
5061 initWithTitle:UCLocalize("CANCEL")
5062 style:UIBarButtonItemStylePlain
5064 action:@selector(cancelButtonClicked)
5069 - (void) applyRightButton {
5070 if ([issues_ count] == 0 && ![self isLoading])
5071 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5072 initWithTitle:UCLocalize("CONFIRM")
5073 style:UIBarButtonItemStyleDone
5075 action:@selector(confirmButtonClicked)
5078 [[self navigationItem] setRightBarButtonItem:nil];
5082 - (void) cancelButtonClicked {
5083 [delegate_ cancelAndClear:YES];
5084 [self dismissModalViewControllerAnimated:YES];
5088 - (void) confirmButtonClicked {
5089 if (essential_ != nil)
5099 /* Progress Data {{{ */
5100 @interface CydiaProgressData : NSObject {
5101 _transient id delegate_;
5110 _H<NSMutableArray> events_;
5111 _H<NSString> title_;
5113 _H<NSString> status_;
5114 _H<NSString> finish_;
5119 @implementation CydiaProgressData
5121 + (NSArray *) _attributeKeys {
5122 return [NSArray arrayWithObjects:
5134 - (NSArray *) attributeKeys {
5135 return [[self class] _attributeKeys];
5138 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5139 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5143 if ((self = [super init]) != nil) {
5144 events_ = [NSMutableArray arrayWithCapacity:32];
5152 - (void) setDelegate:(id)delegate {
5153 delegate_ = delegate;
5156 - (void) setPercent:(float)value {
5160 - (NSNumber *) percent {
5161 return [NSNumber numberWithFloat:percent_];
5164 - (void) setCurrent:(float)value {
5168 - (NSNumber *) current {
5169 return [NSNumber numberWithFloat:current_];
5172 - (void) setTotal:(float)value {
5176 - (NSNumber *) total {
5177 return [NSNumber numberWithFloat:total_];
5180 - (void) setSpeed:(float)value {
5184 - (NSNumber *) speed {
5185 return [NSNumber numberWithFloat:speed_];
5188 - (NSArray *) events {
5192 - (void) removeAllEvents {
5193 [events_ removeAllObjects];
5196 - (void) addEvent:(CydiaProgressEvent *)event {
5197 [events_ addObject:event];
5200 - (void) setTitle:(NSString *)text {
5204 - (NSString *) title {
5208 - (void) setFinish:(NSString *)text {
5212 - (NSString *) finish {
5213 return (id) finish_ ?: [NSNull null];
5216 - (void) setRunning:(bool)running {
5220 - (NSNumber *) running {
5221 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5226 /* Progress Controller {{{ */
5227 @interface ProgressController : CydiaWebViewController <
5230 _transient Database *database_;
5231 _H<CydiaProgressData, 1> progress_;
5235 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5237 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5239 - (void) setTitle:(NSString *)title;
5240 - (void) setCancellable:(bool)cancellable;
5244 @implementation ProgressController
5247 [database_ setProgressDelegate:nil];
5251 - (UIBarButtonItem *) leftButton {
5252 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5253 initWithTitle:UCLocalize("CANCEL")
5254 style:UIBarButtonItemStylePlain
5256 action:@selector(cancel)
5257 ] autorelease] : nil;
5260 - (void) updateCancel {
5261 [super applyLeftButton];
5264 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5265 if ((self = [super init]) != nil) {
5266 database_ = database;
5267 delegate_ = delegate;
5269 [database_ setProgressDelegate:self];
5271 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5272 [progress_ setDelegate:self];
5274 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5276 [scroller_ setBackgroundColor:[UIColor blackColor]];
5278 [[self navigationItem] setHidesBackButton:YES];
5280 [self updateCancel];
5284 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5285 [super webView:view didClearWindowObject:window forFrame:frame];
5286 [window setValue:progress_ forKey:@"cydiaProgress"];
5289 - (void) updateProgress {
5290 [self dispatchEvent:@"CydiaProgressUpdate"];
5293 - (void) viewWillAppear:(BOOL)animated {
5294 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5295 [super viewWillAppear:animated];
5298 - (void) reloadSpringBoard {
5299 if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
5300 system("/bin/launchctl stop com.apple.backboardd");
5302 system("/usr/bin/killall backboardd SpringBoard sbreload");
5306 pid_t pid(ExecFork());
5308 pid_t pid(ExecFork());
5310 execl("/usr/bin/sbreload", "sbreload", NULL);
5321 system("/usr/bin/killall backboardd SpringBoard sbreload");
5325 UpdateExternalStatus(0);
5328 [delegate_ saveState];
5332 [delegate_ returnToCydia];
5336 [delegate_ terminateWithSuccess];
5337 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5338 [delegate_ suspendWithAnimation:YES];
5340 [delegate_ suspend];*/
5352 UIProgressHUD *hud([delegate_ addProgressHUD]);
5353 [hud setText:UCLocalize("LOADING")];
5354 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5360 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5361 SBReboot(SBSSpringBoardServerPort());
5363 reboot2(RB_AUTOBOOT);
5370 - (void) setTitle:(NSString *)title {
5371 [progress_ setTitle:title];
5372 [self updateProgress];
5375 - (UIBarButtonItem *) rightButton {
5376 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5377 initWithTitle:UCLocalize("CLOSE")
5378 style:UIBarButtonItemStylePlain
5380 action:@selector(close)
5384 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5385 UpdateExternalStatus(1);
5387 [progress_ setRunning:true];
5388 [self setTitle:title];
5389 // implicit updateProgress
5391 SHA1SumValue notifyconf; {
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 notifyconf = sha1.Result();
5403 SHA1SumValue springlist; {
5405 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5408 MMap mmap(file, MMap::ReadOnly);
5410 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5411 springlist = sha1.Result();
5415 if (invocation != nil) {
5416 [invocation yieldToSelector:@selector(invoke)];
5417 [self setTitle:@"COMPLETE"];
5422 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5425 MMap mmap(file, MMap::ReadOnly);
5427 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5428 if (!(notifyconf == sha1.Result()))
5435 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5438 MMap mmap(file, MMap::ReadOnly);
5440 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5441 if (!(springlist == sha1.Result()))
5447 if (RestartSubstrate_)
5451 RestartSubstrate_ = false;
5454 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5455 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5456 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5457 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5458 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5461 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5463 [progress_ setRunning:false];
5464 [self updateProgress];
5466 [self applyRightButton];
5469 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5470 [progress_ addEvent:event];
5471 [self updateProgress];
5474 - (bool) isProgressCancelled {
5475 return cancel_ == 2;
5480 [self updateCancel];
5483 - (void) setCancellable:(bool)cancellable {
5484 unsigned cancel(cancel_);
5488 else if (cancel_ == 0)
5491 if (cancel != cancel_)
5492 [self updateCancel];
5495 - (void) setProgressCancellable:(NSNumber *)cancellable {
5496 [self setCancellable:[cancellable boolValue]];
5499 - (void) setProgressPercent:(NSNumber *)percent {
5500 [progress_ setPercent:[percent floatValue]];
5501 [self updateProgress];
5504 - (void) setProgressStatus:(NSDictionary *)status {
5505 if (status == nil) {
5506 [progress_ setCurrent:0];
5507 [progress_ setTotal:0];
5508 [progress_ setSpeed:0];
5510 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5512 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5513 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5514 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5517 [self updateProgress];
5523 /* Package Cell {{{ */
5524 @interface PackageCell : CyteTableViewCell <
5525 CyteTableViewCellDelegate
5529 _H<NSString> description_;
5531 _H<NSString> source_;
5533 _H<UIImage> placard_;
5537 - (PackageCell *) init;
5538 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5540 - (void) drawContentRect:(CGRect)rect;
5544 @implementation PackageCell
5546 - (PackageCell *) init {
5547 CGRect frame(CGRectMake(0, 0, 320, 74));
5548 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5549 UIView *content([self contentView]);
5550 CGRect bounds([content bounds]);
5552 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5553 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5554 [content addSubview:content_];
5556 [content_ setDelegate:self];
5557 [content_ setOpaque:YES];
5561 - (NSString *) accessibilityLabel {
5565 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5566 summarized_ = summary;
5576 [content_ setBackgroundColor:[UIColor whiteColor]];
5580 Source *source = [package source];
5582 icon_ = [package icon];
5584 if (NSString *name = [package name])
5585 name_ = [NSString stringWithString:name];
5587 NSString *description(nil);
5589 if (description == nil && IsWildcat_)
5590 description = [package longDescription];
5591 if (description == nil)
5592 description = [package shortDescription];
5594 if (description != nil)
5595 description_ = [NSString stringWithString:description];
5597 commercial_ = [package isCommercial];
5599 NSString *label = nil;
5600 bool trusted = false;
5602 if (source != nil) {
5603 label = [source label];
5604 trusted = [source trusted];
5605 } else if ([[package id] isEqualToString:@"firmware"])
5606 label = UCLocalize("APPLE");
5608 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5610 NSString *from(label);
5612 NSString *section = [package simpleSection];
5613 if (section != nil && ![section isEqualToString:label]) {
5614 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5615 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5618 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5620 if (NSString *purpose = [package primaryPurpose])
5621 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5626 if (NSString *mode = [package mode]) {
5627 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5628 color = RemovingColor_;
5629 //placard = @"removing";
5631 color = InstallingColor_;
5632 //placard = @"installing";
5635 // XXX: the removing/installing placards are not @2x
5638 color = [UIColor whiteColor];
5640 if ([package installed] != nil)
5641 placard = @"installed";
5646 [content_ setBackgroundColor:color];
5649 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5652 [self setNeedsDisplay];
5653 [content_ setNeedsDisplay];
5656 - (void) drawSummaryContentRect:(CGRect)rect {
5657 bool highlighted(highlighted_);
5658 float width([self bounds].size.width);
5662 rect.size = [(UIImage *) icon_ size];
5664 while (rect.size.width > 16 || rect.size.height > 16) {
5665 rect.size.width /= 2;
5666 rect.size.height /= 2;
5669 rect.origin.x = 18 - rect.size.width / 2;
5670 rect.origin.y = 18 - rect.size.height / 2;
5672 [icon_ drawInRect:rect];
5675 if (badge_ != nil) {
5677 rect.size = [(UIImage *) badge_ size];
5679 rect.size.width /= 4;
5680 rect.size.height /= 4;
5682 rect.origin.x = 23 - rect.size.width / 2;
5683 rect.origin.y = 23 - rect.size.height / 2;
5685 [badge_ drawInRect:rect];
5692 UISetColor(commercial_ ? Purple_ : Black_);
5693 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5695 if (placard_ != nil)
5696 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5699 - (void) drawNormalContentRect:(CGRect)rect {
5700 bool highlighted(highlighted_);
5701 float width([self bounds].size.width);
5705 rect.size = [(UIImage *) icon_ size];
5707 while (rect.size.width > 32 || rect.size.height > 32) {
5708 rect.size.width /= 2;
5709 rect.size.height /= 2;
5712 rect.origin.x = 25 - rect.size.width / 2;
5713 rect.origin.y = 25 - rect.size.height / 2;
5715 [icon_ drawInRect:rect];
5718 if (badge_ != nil) {
5720 rect.size = [(UIImage *) badge_ size];
5722 rect.size.width /= 2;
5723 rect.size.height /= 2;
5725 rect.origin.x = 36 - rect.size.width / 2;
5726 rect.origin.y = 36 - rect.size.height / 2;
5728 [badge_ drawInRect:rect];
5735 UISetColor(commercial_ ? Purple_ : Black_);
5736 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5737 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5740 UISetColor(commercial_ ? Purplish_ : Gray_);
5741 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5743 if (placard_ != nil)
5744 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5747 - (void) drawContentRect:(CGRect)rect {
5749 [self drawSummaryContentRect:rect];
5751 [self drawNormalContentRect:rect];
5756 /* Section Cell {{{ */
5757 @interface SectionCell : CyteTableViewCell <
5758 CyteTableViewCellDelegate
5760 _H<NSString> basic_;
5761 _H<NSString> section_;
5763 _H<NSString> count_;
5765 _H<UISwitch> switch_;
5769 - (void) setSection:(Section *)section editing:(BOOL)editing;
5773 @implementation SectionCell
5775 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5776 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5777 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5778 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5779 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5781 UIView *content([self contentView]);
5782 CGRect bounds([content bounds]);
5784 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5785 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5786 [content addSubview:content_];
5787 [content_ setBackgroundColor:[UIColor whiteColor]];
5789 [content_ setDelegate:self];
5793 - (void) onSwitch:(id)sender {
5794 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5795 if (metadata == nil) {
5796 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5797 [Sections_ setObject:metadata forKey:basic_];
5800 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5804 - (void) setSection:(Section *)section editing:(BOOL)editing {
5805 if (editing != editing_) {
5807 [switch_ removeFromSuperview];
5809 [self addSubview:switch_];
5818 if (section == nil) {
5819 name_ = UCLocalize("ALL_PACKAGES");
5822 basic_ = [section name];
5823 section_ = [section localized];
5825 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5826 count_ = [NSString stringWithFormat:@"%d", [section count]];
5829 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5832 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5833 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5835 [content_ setNeedsDisplay];
5838 - (void) setFrame:(CGRect)frame {
5839 [super setFrame:frame];
5841 CGRect rect([switch_ frame]);
5842 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5845 - (NSString *) accessibilityLabel {
5849 - (void) drawContentRect:(CGRect)rect {
5850 bool highlighted(highlighted_ && !editing_);
5852 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5857 float width(rect.size.width);
5863 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5865 CGSize size = [count_ sizeWithFont:Font14_];
5869 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5875 /* File Table {{{ */
5876 @interface FileTable : CyteViewController <
5877 UITableViewDataSource,
5880 _transient Database *database_;
5881 _H<Package> package_;
5883 _H<NSMutableArray> files_;
5884 _H<UITableView, 2> list_;
5887 - (id) initWithDatabase:(Database *)database;
5888 - (void) setPackage:(Package *)package;
5892 @implementation FileTable
5894 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5895 return files_ == nil ? 0 : [files_ count];
5898 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5902 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5903 static NSString *reuseIdentifier = @"Cell";
5905 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5907 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5908 [cell setFont:[UIFont systemFontOfSize:16]];
5910 [cell setText:[files_ objectAtIndex:indexPath.row]];
5911 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5916 - (NSURL *) navigationURL {
5917 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5921 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5922 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5923 [list_ setRowHeight:24.0f];
5924 [(UITableView *) list_ setDataSource:self];
5925 [list_ setDelegate:self];
5926 [self setView:list_];
5929 - (void) viewDidLoad {
5930 [super viewDidLoad];
5932 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5935 - (void) releaseSubviews {
5941 [super releaseSubviews];
5944 - (id) initWithDatabase:(Database *)database {
5945 if ((self = [super init]) != nil) {
5946 database_ = database;
5950 - (void) setPackage:(Package *)package {
5954 files_ = [NSMutableArray arrayWithCapacity:32];
5956 if (package != nil) {
5958 name_ = [package id];
5960 if (NSArray *files = [package files])
5961 [files_ addObjectsFromArray:files];
5963 if ([files_ count] != 0) {
5964 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5965 [files_ removeObjectAtIndex:0];
5966 [files_ sortUsingSelector:@selector(compareByPath:)];
5968 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5969 [stack addObject:@"/"];
5971 for (int i(0), e([files_ count]); i != e; ++i) {
5972 NSString *file = [files_ objectAtIndex:i];
5973 while (![file hasPrefix:[stack lastObject]])
5974 [stack removeLastObject];
5975 NSString *directory = [stack lastObject];
5976 [stack addObject:[file stringByAppendingString:@"/"]];
5977 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5978 ([stack count] - 2) * 3, "",
5979 [file substringFromIndex:[directory length]]
5988 - (void) reloadData {
5991 [self setPackage:[database_ packageWithName:name_]];
5996 /* Package Controller {{{ */
5997 @interface CYPackageController : CydiaWebViewController <
5998 UIActionSheetDelegate
6000 _transient Database *database_;
6001 _H<Package> package_;
6004 _H<NSMutableArray> buttons_;
6005 _H<UIBarButtonItem> button_;
6008 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6012 @implementation CYPackageController
6014 - (NSURL *) navigationURL {
6015 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6018 /* XXX: this is not safe at all... localization of /fail/ */
6019 - (void) _clickButtonWithName:(NSString *)name {
6020 if ([name isEqualToString:UCLocalize("CLEAR")])
6021 [delegate_ clearPackage:package_];
6022 else if ([name isEqualToString:UCLocalize("INSTALL")])
6023 [delegate_ installPackage:package_];
6024 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6025 [delegate_ installPackage:package_];
6026 else if ([name isEqualToString:UCLocalize("REMOVE")])
6027 [delegate_ removePackage:package_];
6028 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6029 [delegate_ installPackage:package_];
6030 else _assert(false);
6033 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6034 NSString *context([sheet context]);
6036 if ([context isEqualToString:@"modify"]) {
6037 if (button != [sheet cancelButtonIndex]) {
6038 NSString *buttonName = [buttons_ objectAtIndex:button];
6039 [self _clickButtonWithName:buttonName];
6042 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6046 - (bool) _allowJavaScriptPanel {
6051 - (void) _customButtonClicked {
6052 int count([buttons_ count]);
6057 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6059 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6060 [buttons addObjectsFromArray:buttons_];
6062 UIActionSheet *sheet = [[[UIActionSheet alloc]
6065 cancelButtonTitle:nil
6066 destructiveButtonTitle:nil
6067 otherButtonTitles:nil
6070 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6072 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6073 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6075 [sheet setContext:@"modify"];
6077 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6081 - (void) reloadButtonClicked {
6082 if (commercial_ && function_ == nil && [package_ uninstalled])
6084 [self customButtonClicked];
6087 - (void) applyLoadingTitle {
6088 // Don't show "Loading" as the title. Ever.
6091 - (UIBarButtonItem *) rightButton {
6096 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6097 if ((self = [super init]) != nil) {
6098 database_ = database;
6099 buttons_ = [NSMutableArray arrayWithCapacity:4];
6100 name_ = name == nil ? @"" : [NSString stringWithString:name];
6101 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6105 - (void) reloadData {
6108 package_ = [database_ packageWithName:name_];
6110 [buttons_ removeAllObjects];
6112 if (package_ != nil) {
6113 [(Package *) package_ parse];
6115 commercial_ = [package_ isCommercial];
6117 if ([package_ mode] != nil)
6118 [buttons_ addObject:UCLocalize("CLEAR")];
6119 if ([package_ source] == nil);
6120 else if ([package_ upgradableAndEssential:NO])
6121 [buttons_ addObject:UCLocalize("UPGRADE")];
6122 else if ([package_ uninstalled])
6123 [buttons_ addObject:UCLocalize("INSTALL")];
6125 [buttons_ addObject:UCLocalize("REINSTALL")];
6126 if (![package_ uninstalled])
6127 [buttons_ addObject:UCLocalize("REMOVE")];
6131 switch ([buttons_ count]) {
6132 case 0: title = nil; break;
6133 case 1: title = [buttons_ objectAtIndex:0]; break;
6134 default: title = UCLocalize("MODIFY"); break;
6137 button_ = [[[UIBarButtonItem alloc]
6139 style:UIBarButtonItemStylePlain
6141 action:@selector(customButtonClicked)
6145 - (bool) isLoading {
6146 return commercial_ ? [super isLoading] : false;
6152 /* Package List Controller {{{ */
6153 @interface PackageListController : CyteViewController <
6154 UITableViewDataSource,
6157 _transient Database *database_;
6159 _H<NSArray> packages_;
6160 _H<NSMutableArray> sections_;
6161 _H<UITableView, 2> list_;
6162 _H<NSMutableArray> index_;
6163 _H<NSMutableDictionary> indices_;
6164 _H<NSString> title_;
6165 unsigned reloading_;
6168 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6169 - (void) setDelegate:(id)delegate;
6170 - (void) resetCursor;
6175 @implementation PackageListController
6177 - (NSURL *) referrerURL {
6178 return [self navigationURL];
6181 - (bool) isSummarized {
6185 - (bool) showsSections {
6189 - (void) deselectWithAnimation:(BOOL)animated {
6190 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6193 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6194 CGRect base = [[self view] bounds];
6195 base.size.height -= bounds.size.height;
6196 base.origin = [list_ frame].origin;
6198 [UIView beginAnimations:nil context:NULL];
6199 [UIView setAnimationBeginsFromCurrentState:YES];
6200 [UIView setAnimationCurve:curve];
6201 [UIView setAnimationDuration:duration];
6202 [list_ setFrame:base];
6203 [UIView commitAnimations];
6206 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6207 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6210 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6211 [self resizeForKeyboardBounds:bounds duration:0];
6214 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6215 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6216 *curve = UIViewAnimationCurveEaseInOut;
6218 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6220 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6223 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6226 - (void) keyboardWillShow:(NSNotification *)notification {
6229 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6230 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6232 NSTimeInterval duration;
6233 UIViewAnimationCurve curve;
6234 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6236 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);
6237 UIViewController *base = self;
6238 while ([base parentOrPresentingViewController] != nil)
6239 base = [base parentOrPresentingViewController];
6240 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6241 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6243 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6244 intersection.size.height += CYStatusBarHeight();
6246 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6249 - (void) keyboardWillHide:(NSNotification *)notification {
6250 NSTimeInterval duration;
6251 UIViewAnimationCurve curve;
6252 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6254 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6257 - (void) viewWillAppear:(BOOL)animated {
6258 [super viewWillAppear:animated];
6260 [self resizeForKeyboardBounds:CGRectZero];
6261 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6262 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6265 - (void) viewWillDisappear:(BOOL)animated {
6266 [super viewWillDisappear:animated];
6268 [self resizeForKeyboardBounds:CGRectZero];
6269 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6270 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6273 - (void) viewDidAppear:(BOOL)animated {
6274 [super viewDidAppear:animated];
6275 [self deselectWithAnimation:animated];
6278 - (void) didSelectPackage:(Package *)package {
6279 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6280 [view setDelegate:delegate_];
6281 [[self navigationController] pushViewController:view animated:YES];
6284 #if TryIndexedCollation
6285 + (BOOL) hasIndexedCollation {
6286 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6290 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6291 NSInteger count([sections_ count]);
6292 return count == 0 ? 1 : count;
6295 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6296 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6298 return [[sections_ objectAtIndex:section] name];
6301 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6302 if ([sections_ count] == 0)
6304 return [[sections_ objectAtIndex:section] count];
6307 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6308 @synchronized (database_) {
6309 if ([database_ era] != era_)
6312 Section *section([sections_ objectAtIndex:[path section]]);
6313 NSInteger row([path row]);
6314 Package *package([packages_ objectAtIndex:([section row] + row)]);
6315 return [[package retain] autorelease];
6318 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6319 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6321 cell = [[[PackageCell alloc] init] autorelease];
6323 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6324 [cell setPackage:package asSummary:[self isSummarized]];
6328 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6329 Package *package([self packageAtIndexPath:path]);
6330 package = [database_ packageWithName:[package id]];
6331 [self didSelectPackage:package];
6334 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6335 if (![self showsSections])
6341 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6342 #if TryIndexedCollation
6343 if ([[self class] hasIndexedCollation]) {
6344 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6351 - (void) updateHeight {
6352 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6355 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6356 if ((self = [super init]) != nil) {
6357 database_ = database;
6358 title_ = [title copy];
6359 [[self navigationItem] setTitle:title_];
6364 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6365 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6366 [self setView:view];
6368 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6369 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6370 [view addSubview:list_];
6372 // XXX: is 20 the most optimal number here?
6373 [list_ setSectionIndexMinimumDisplayRowCount:20];
6375 [(UITableView *) list_ setDataSource:self];
6376 [list_ setDelegate:self];
6378 [self updateHeight];
6381 - (void) releaseSubviews {
6389 [super releaseSubviews];
6392 - (void) setDelegate:(id)delegate {
6393 delegate_ = delegate;
6396 - (bool) shouldYield {
6400 - (bool) shouldBlock {
6404 - (NSMutableArray *) _reloadPackages {
6405 @synchronized (database_) {
6406 era_ = [database_ era];
6407 NSArray *packages([database_ packages]);
6409 return [NSMutableArray arrayWithArray:packages];
6412 - (void) _reloadData {
6413 if (reloading_ != 0) {
6421 if ([self shouldYield]) {
6425 if (![self shouldBlock])
6428 hud = [delegate_ addProgressHUD];
6429 [hud setText:UCLocalize("LOADING")];
6433 packages = [self yieldToSelector:@selector(_reloadPackages)];
6436 [delegate_ removeProgressHUD:hud];
6437 } while (reloading_ == 2);
6439 packages = [self _reloadPackages];
6442 @synchronized (database_) {
6443 if (era_ != [database_ era])
6447 packages_ = packages;
6449 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6450 sections_ = [NSMutableArray arrayWithCapacity:16];
6452 Section *section = nil;
6454 #if TryIndexedCollation
6455 if ([[self class] hasIndexedCollation]) {
6456 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6458 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6459 NSArray *titles = [collation sectionIndexTitles];
6462 _profile(PackageTable$reloadData$Section)
6463 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6467 _profile(PackageTable$reloadData$Section$Package)
6468 package = [packages_ objectAtIndex:offset];
6469 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6472 while (secidx < index) {
6475 _profile(PackageTable$reloadData$Section$Allocate)
6476 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6479 _profile(PackageTable$reloadData$Section$Add)
6480 [sections_ addObject:section];
6484 [section addToCount];
6490 index_ = [NSMutableArray arrayWithCapacity:32];
6492 bool sectioned([self showsSections]);
6494 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6495 [sections_ addObject:section];
6498 _profile(PackageTable$reloadData$Section)
6499 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6503 _profile(PackageTable$reloadData$Section$Package)
6504 package = [packages_ objectAtIndex:offset];
6505 index = [package index];
6508 if (sectioned && (section == nil || [section index] != index)) {
6509 _profile(PackageTable$reloadData$Section$Allocate)
6510 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6513 [index_ addObject:[section name]];
6514 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6516 _profile(PackageTable$reloadData$Section$Add)
6517 [sections_ addObject:section];
6521 [section addToCount];
6526 [self updateHeight];
6528 _profile(PackageTable$reloadData$List)
6529 [(UITableView *) list_ setDataSource:self];
6534 - (void) reloadData {
6537 if ([self shouldYield])
6538 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6543 - (void) resetCursor {
6544 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6547 - (void) clearData {
6548 [self updateHeight];
6550 [list_ setDataSource:nil];
6558 /* Filtered Package List Controller {{{ */
6559 @interface FilteredPackageListController : PackageListController {
6562 _H<NSObject> object_;
6565 - (void) setObject:(id)object;
6566 - (void) setObject:(id)object forFilter:(SEL)filter;
6569 - (void) setFilter:(SEL)filter;
6571 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6575 @implementation FilteredPackageListController
6581 - (void) setFilter:(SEL)filter {
6582 @synchronized (self) {
6585 /* XXX: this is an unsafe optimization of doomy hell */
6586 Method method(class_getInstanceMethod([Package class], filter));
6587 _assert(method != NULL);
6588 imp_ = method_getImplementation(method);
6589 _assert(imp_ != NULL);
6592 - (void) setObject:(id)object {
6593 @synchronized (self) {
6597 - (void) setObject:(id)object forFilter:(SEL)filter {
6598 @synchronized (self) {
6599 [self setFilter:filter];
6600 [self setObject:object];
6603 - (NSMutableArray *) _reloadPackages {
6604 @synchronized (database_) {
6605 era_ = [database_ era];
6606 NSArray *packages([database_ packages]);
6608 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6612 _H<NSObject> object;
6614 @synchronized (self) {
6620 _profile(PackageTable$reloadData$Filter)
6621 for (Package *package in packages)
6622 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6623 [filtered addObject:package];
6629 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6630 if ((self = [super initWithDatabase:database title:title]) != nil) {
6631 [self setFilter:filter];
6632 [self setObject:object];
6639 /* Home Controller {{{ */
6640 @interface HomeController : CydiaWebViewController {
6641 CFRunLoopRef runloop_;
6642 SCNetworkReachabilityRef reachability_;
6647 @implementation HomeController
6649 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6650 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6654 if ((self = [super init]) != nil) {
6655 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6658 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6659 if (reachability_ != NULL) {
6660 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6661 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6663 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6664 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6671 if (reachability_ != NULL && runloop_ != NULL)
6672 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6676 - (NSURL *) navigationURL {
6677 return [NSURL URLWithString:@"cydia://home"];
6680 - (void) aboutButtonClicked {
6681 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6683 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6684 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6685 [alert setCancelButtonIndex:0];
6688 @"Copyright \u00a9 2008-2012\n"
6691 "Jay Freeman (saurik)\n"
6692 "saurik@saurik.com\n"
6693 "http://www.saurik.com/"
6699 - (UIBarButtonItem *) leftButton {
6700 return [[[UIBarButtonItem alloc]
6701 initWithTitle:UCLocalize("ABOUT")
6702 style:UIBarButtonItemStylePlain
6704 action:@selector(aboutButtonClicked)
6710 /* Manage Controller {{{ */
6711 @interface ManageController : CydiaWebViewController {
6714 - (void) queueStatusDidChange;
6718 @implementation ManageController
6721 if ((self = [super init]) != nil) {
6722 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6726 - (NSURL *) navigationURL {
6727 return [NSURL URLWithString:@"cydia://manage"];
6730 - (UIBarButtonItem *) leftButton {
6731 return [[[UIBarButtonItem alloc]
6732 initWithTitle:UCLocalize("SETTINGS")
6733 style:UIBarButtonItemStylePlain
6735 action:@selector(settingsButtonClicked)
6739 - (void) settingsButtonClicked {
6740 [delegate_ showSettings];
6743 - (void) queueButtonClicked {
6747 - (UIBarButtonItem *) rightButton {
6748 return Queuing_ ? [[[UIBarButtonItem alloc]
6749 initWithTitle:UCLocalize("QUEUE")
6750 style:UIBarButtonItemStyleDone
6752 action:@selector(queueButtonClicked)
6753 ] autorelease] : nil;
6756 - (void) queueStatusDidChange {
6757 [self applyRightButton];
6760 - (bool) isLoading {
6761 return !Queuing_ && [super isLoading];
6767 /* Refresh Bar {{{ */
6768 @interface RefreshBar : UINavigationBar {
6769 _H<UIProgressIndicator> indicator_;
6770 _H<UITextLabel> prompt_;
6771 _H<UINavigationButton> cancel_;
6776 @implementation RefreshBar
6778 - (void) positionViews {
6779 CGRect frame = [cancel_ frame];
6780 frame.size = [cancel_ sizeThatFits:frame.size];
6781 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6782 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6783 [cancel_ setFrame:frame];
6785 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6786 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6787 CGRect indrect = {{indoffset, indoffset}, indsize};
6788 [indicator_ setFrame:indrect];
6790 CGSize prmsize = {215, indsize.height + 4};
6792 indoffset * 2 + indsize.width,
6793 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6795 [prompt_ setFrame:prmrect];
6798 - (void) setFrame:(CGRect)frame {
6799 [super setFrame:frame];
6800 [self positionViews];
6803 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6804 if ((self = [super initWithFrame:frame]) != nil) {
6805 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6807 [self setBarStyle:UIBarStyleBlack];
6809 UIBarStyle barstyle([self _barStyle:NO]);
6810 bool ugly(barstyle == UIBarStyleDefault);
6812 UIProgressIndicatorStyle style = ugly ?
6813 UIProgressIndicatorStyleMediumBrown :
6814 UIProgressIndicatorStyleMediumWhite;
6816 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6817 [(UIProgressIndicator *) indicator_ setStyle:style];
6818 [indicator_ startAnimation];
6819 [self addSubview:indicator_];
6821 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6822 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6823 [prompt_ setBackgroundColor:[UIColor clearColor]];
6824 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6825 [self addSubview:prompt_];
6827 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6828 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6829 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6830 [cancel_ setBarStyle:barstyle];
6832 [self positionViews];
6836 - (void) setCancellable:(bool)cancellable {
6838 [self addSubview:cancel_];
6840 [cancel_ removeFromSuperview];
6844 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6848 [self setCancellable:NO];
6851 - (void) setPrompt:(NSString *)prompt {
6852 [prompt_ setText:prompt];
6855 - (void) setProgress:(float)progress {
6861 /* Cydia Navigation Controller Interface {{{ */
6862 @interface UINavigationController (Cydia)
6864 - (NSArray *) navigationURLCollection;
6865 - (void) unloadData;
6870 /* Cydia Tab Bar Controller {{{ */
6871 @interface CYTabBarController : UITabBarController <
6872 UITabBarControllerDelegate,
6875 _transient Database *database_;
6876 _H<RefreshBar, 1> refreshbar_;
6880 // XXX: ok, "updatedelegate_"?...
6881 _transient NSObject<CydiaDelegate> *updatedelegate_;
6883 _H<UIViewController> remembered_;
6884 _transient UIViewController *transient_;
6887 - (NSArray *) navigationURLCollection;
6888 - (void) dropBar:(BOOL)animated;
6889 - (void) beginUpdate;
6890 - (void) raiseBar:(BOOL)animated;
6892 - (void) unloadData;
6896 @implementation CYTabBarController
6898 - (void) didReceiveMemoryWarning {
6899 [super didReceiveMemoryWarning];
6901 // presenting a UINavigationController on 2.x does not update its transitionView
6902 // it thereby will not allow its topViewController to be unloaded by memory pressure
6903 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6904 UIViewController *selected([self selectedViewController]);
6905 for (UINavigationController *controller in [self viewControllers])
6906 if (controller != selected)
6907 if (UIViewController *top = [controller topViewController])
6912 - (void) setUnselectedViewController:(UIViewController *)transient {
6913 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6914 if (transient != nil) {
6915 [[[self viewControllers] objectAtIndex:0] pushViewController:transient animated:YES];
6916 [self setSelectedIndex:0];
6920 NSMutableArray *controllers = [[[self viewControllers] mutableCopy] autorelease];
6921 if (transient != nil) {
6922 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
6923 [navigation setViewControllers:[NSArray arrayWithObject:transient]];
6924 transient = navigation;
6926 if (transient_ == nil)
6927 remembered_ = [controllers objectAtIndex:0];
6928 transient_ = transient;
6929 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6930 [controllers replaceObjectAtIndex:0 withObject:transient_];
6931 [self setSelectedIndex:0];
6932 [self setViewControllers:controllers];
6933 [self concealTabBarSelection];
6934 } else if (remembered_ != nil) {
6935 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6936 transient_ = transient;
6937 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6939 [self setViewControllers:controllers];
6940 [self revealTabBarSelection];
6944 - (UIViewController *) unselectedViewController {
6948 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6949 if ([self unselectedViewController])
6950 [self setUnselectedViewController:nil];
6952 // presenting a UINavigationController on 2.x does not update its transitionView
6953 // if this view was unloaded, the tranitionView may currently be presenting nothing
6954 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6955 UINavigationController *navigation((UINavigationController *) viewController);
6956 [navigation pushViewController:[[[UIViewController alloc] init] autorelease] animated:NO];
6957 [navigation popViewControllerAnimated:NO];
6961 - (NSArray *) navigationURLCollection {
6962 NSMutableArray *items([NSMutableArray array]);
6964 // XXX: Should this deal with transient view controllers?
6965 for (id navigation in [self viewControllers]) {
6966 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6968 [items addObject:stack];
6974 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6975 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6976 [self setUnselectedViewController:nil];
6978 [super dismissModalViewControllerAnimated:YES];
6981 - (void) unloadData {
6984 for (UINavigationController *controller in [self viewControllers])
6985 [controller unloadData];
6987 if (UIViewController *selected = [self selectedViewController])
6988 [selected reloadData];
6990 if (UIViewController *unselected = [self unselectedViewController]) {
6991 [unselected unloadData];
6992 [unselected reloadData];
6997 [[NSNotificationCenter defaultCenter] removeObserver:self];
7002 - (id) initWithDatabase:(Database *)database {
7003 if ((self = [super init]) != nil) {
7004 database_ = database;
7005 [self setDelegate:self];
7007 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7008 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7010 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
7014 - (void) setUpdate:(NSDate *)date {
7018 - (void) beginUpdate {
7019 [(RefreshBar *) refreshbar_ start];
7022 [updatedelegate_ retainNetworkActivityIndicator];
7026 detachNewThreadSelector:@selector(performUpdate)
7032 - (void) performUpdate {
7033 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7036 status.setDelegate(self);
7037 [database_ updateWithStatus:status];
7040 performSelectorOnMainThread:@selector(completeUpdate)
7048 - (void) stopUpdateWithSelector:(SEL)selector {
7050 [updatedelegate_ releaseNetworkActivityIndicator];
7052 [self raiseBar:YES];
7055 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7058 - (void) completeUpdate {
7061 [self stopUpdateWithSelector:@selector(reloadData)];
7064 - (void) cancelUpdate {
7065 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7068 - (void) cancelPressed {
7069 [self cancelUpdate];
7076 - (void) addProgressEvent:(CydiaProgressEvent *)event {
7077 [refreshbar_ setPrompt:[event compoundMessage]];
7080 - (bool) isProgressCancelled {
7084 - (void) setProgressCancellable:(NSNumber *)cancellable {
7085 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
7088 - (void) setProgressPercent:(NSNumber *)percent {
7089 [refreshbar_ setProgress:[percent floatValue]];
7092 - (void) setProgressStatus:(NSDictionary *)status {
7094 [self setProgressPercent:[status objectForKey:@"Percent"]];
7097 - (void) setUpdateDelegate:(id)delegate {
7098 updatedelegate_ = delegate;
7101 - (UIView *) transitionView {
7102 if ([self respondsToSelector:@selector(_transitionView)])
7103 return [self _transitionView];
7105 return MSHookIvar<id>(self, "_viewControllerTransitionView");
7108 - (void) dropBar:(BOOL)animated {
7113 UIView *transition([self transitionView]);
7114 [[self view] addSubview:refreshbar_];
7116 CGRect barframe([refreshbar_ frame]);
7118 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
7119 barframe.origin.y = CYStatusBarHeight();
7121 barframe.origin.y = 0;
7123 [refreshbar_ setFrame:barframe];
7126 [UIView beginAnimations:nil context:NULL];
7128 CGRect viewframe = [transition frame];
7129 viewframe.origin.y += barframe.size.height;
7130 viewframe.size.height -= barframe.size.height;
7131 [transition setFrame:viewframe];
7134 [UIView commitAnimations];
7136 // Ensure bar has the proper width for our view, it might have changed
7137 barframe.size.width = viewframe.size.width;
7138 [refreshbar_ setFrame:barframe];
7141 - (void) raiseBar:(BOOL)animated {
7146 UIView *transition([self transitionView]);
7147 [refreshbar_ removeFromSuperview];
7149 CGRect barframe([refreshbar_ frame]);
7152 [UIView beginAnimations:nil context:NULL];
7154 CGRect viewframe = [transition frame];
7155 viewframe.origin.y -= barframe.size.height;
7156 viewframe.size.height += barframe.size.height;
7157 [transition setFrame:viewframe];
7160 [UIView commitAnimations];
7163 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7164 bool dropped(dropped_);
7169 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7175 - (void) statusBarFrameChanged:(NSNotification *)notification {
7185 /* Cydia Navigation Controller Implementation {{{ */
7186 @implementation UINavigationController (Cydia)
7188 - (NSArray *) navigationURLCollection {
7189 NSMutableArray *stack([NSMutableArray array]);
7191 for (CyteViewController *controller in [self viewControllers]) {
7192 NSString *url = [[controller navigationURL] absoluteString];
7194 [stack addObject:url];
7200 - (void) reloadData {
7203 UIViewController *visible([self visibleViewController]);
7205 [visible reloadData];
7207 // on the iPad, this view controller is ALSO visible. :(
7209 if (UIViewController *top = [self topViewController])
7214 - (void) unloadData {
7215 for (CyteViewController *page in [self viewControllers])
7224 /* Cydia:// Protocol {{{ */
7225 @interface CydiaURLProtocol : NSURLProtocol {
7230 @implementation CydiaURLProtocol
7232 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7233 NSURL *url([request URL]);
7237 NSString *scheme([[url scheme] lowercaseString]);
7238 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7240 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7246 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7250 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7251 id<NSURLProtocolClient> client([self client]);
7253 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7255 NSData *data(UIImagePNGRepresentation(icon));
7257 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7258 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7259 [client URLProtocol:self didLoadData:data];
7260 [client URLProtocolDidFinishLoading:self];
7264 - (void) startLoading {
7265 id<NSURLProtocolClient> client([self client]);
7266 NSURLRequest *request([self request]);
7268 NSURL *url([request URL]);
7269 NSString *href([url absoluteString]);
7270 NSString *scheme([[url scheme] lowercaseString]);
7274 if ([scheme isEqualToString:@"cydia"])
7275 path = [href substringFromIndex:8];
7276 else if ([scheme isEqualToString:@"about"])
7277 path = [href substringFromIndex:12];
7278 else _assert(false);
7280 NSRange slash([path rangeOfString:@"/"]);
7283 if (slash.location == NSNotFound) {
7287 command = [path substringToIndex:slash.location];
7288 path = [path substringFromIndex:(slash.location + 1)];
7291 Database *database([Database sharedInstance]);
7293 if ([command isEqualToString:@"package-icon"]) {
7296 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7297 Package *package([database packageWithName:path]);
7301 UIImage *icon([package icon]);
7302 [self _returnPNGWithImage:icon forRequest:request];
7303 } else if ([command isEqualToString:@"uikit-image"]) {
7306 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7307 UIImage *icon(_UIImageWithName(path));
7308 [self _returnPNGWithImage:icon forRequest:request];
7309 } else if ([command isEqualToString:@"section-icon"]) {
7312 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7313 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7315 icon = [UIImage applicationImageNamed:@"unknown.png"];
7316 [self _returnPNGWithImage:icon forRequest:request];
7318 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7322 - (void) stopLoading {
7328 /* Section Controller {{{ */
7329 @interface SectionController : FilteredPackageListController {
7330 _H<IndirectDelegate, 1> indirect_;
7331 _H<CydiaObject> cydia_;
7332 _H<NSString> section_;
7333 std::vector< _H<CyteWebViewTableViewCell, 1> > promoted_;
7336 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7340 @implementation SectionController
7342 - (NSURL *) referrerURL {
7343 NSString *name = section_;
7347 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@", UI_, [name stringByAddingPercentEscapesIncludingReserved]]];
7350 - (NSURL *) navigationURL {
7351 NSString *name = section_;
7355 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", [name stringByAddingPercentEscapesIncludingReserved]]];
7358 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7361 title = UCLocalize("ALL_PACKAGES");
7362 else if (![name isEqual:@""])
7363 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7365 title = UCLocalize("NO_SECTION");
7367 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7368 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7369 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7374 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7375 return [super numberOfSectionsInTableView:list] + 1;
7378 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7379 return section == 0 ? nil : [super tableView:list titleForHeaderInSection:(section - 1)];
7382 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7383 return section == 0 ? promoted_.size() : [super tableView:list numberOfRowsInSection:(section - 1)];
7386 + (NSIndexPath *) adjustedIndexPath:(NSIndexPath *)path {
7387 return [NSIndexPath indexPathForRow:[path row] inSection:([path section] - 1)];
7390 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7391 if ([path section] != 0)
7392 return [super tableView:table cellForRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7394 return promoted_[[path row]];
7397 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
7398 if ([path section] != 0)
7399 return [super tableView:table didSelectRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7402 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
7403 NSInteger section([super tableView:tableView sectionForSectionIndexTitle:title atIndex:index]);
7404 return section == 0 ? 0 : section + 1;
7407 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7408 NSURL *url([request URL]);
7412 if ([frame isEqualToString:@"_open"])
7413 [delegate_ openURL:url];
7415 WebFrame *frame(nil);
7416 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7417 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7419 frame = [view mainFrame];
7421 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7423 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7424 [controller setDelegate:delegate_];
7425 [[self navigationController] pushViewController:controller animated:YES];
7431 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7432 return [CydiaWebViewController requestWithHeaders:request];
7435 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7436 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7442 // XXX: this code is horrible. I mean, wtf Jay?
7443 if (ShowPromoted_ && [[Metadata_ objectForKey:@"ShowPromoted"] boolValue]) {
7444 promoted_.resize(1);
7446 for (unsigned i(0); i != promoted_.size(); ++i) {
7447 CyteWebViewTableViewCell *promoted([CyteWebViewTableViewCell cellWithRequest:[NSURLRequest
7448 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sectionhead/%u/%@",
7449 UI_, i, section_ == nil ? @"" : [section_ stringByAddingPercentEscapesIncludingReserved]]
7452 cachePolicy:NSURLRequestUseProtocolCachePolicy
7456 [promoted setDelegate:self];
7457 promoted_[i] = promoted;
7462 - (void) setDelegate:(id)delegate {
7463 [super setDelegate:delegate];
7464 [cydia_ setDelegate:delegate];
7467 - (void) releaseSubviews {
7469 [super releaseSubviews];
7474 /* Sections Controller {{{ */
7475 @interface SectionsController : CyteViewController <
7476 UITableViewDataSource,
7479 _transient Database *database_;
7480 _H<NSMutableArray> sections_;
7481 _H<NSMutableArray> filtered_;
7482 _H<UITableView, 2> list_;
7485 - (id) initWithDatabase:(Database *)database;
7486 - (void) editButtonClicked;
7490 @implementation SectionsController
7492 - (NSURL *) navigationURL {
7493 return [NSURL URLWithString:@"cydia://sections"];
7496 - (void) updateNavigationItem {
7497 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7498 if ([sections_ count] == 0) {
7499 [[self navigationItem] setRightBarButtonItem:nil];
7501 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7502 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7504 action:@selector(editButtonClicked)
7505 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7509 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7510 [super setEditing:editing animated:animated];
7515 [delegate_ updateData];
7517 [self updateNavigationItem];
7520 - (void) viewDidAppear:(BOOL)animated {
7521 [super viewDidAppear:animated];
7522 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7525 - (void) viewWillDisappear:(BOOL)animated {
7526 [super viewWillDisappear:animated];
7527 [self setEditing:NO];
7530 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7531 Section *section = nil;
7532 int index = [indexPath row];
7533 if (![self isEditing]) {
7536 section = [filtered_ objectAtIndex:index];
7538 section = [sections_ objectAtIndex:index];
7543 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7544 if ([self isEditing])
7545 return [sections_ count];
7547 return [filtered_ count] + 1;
7550 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7554 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7555 static NSString *reuseIdentifier = @"SectionCell";
7557 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7559 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7561 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7566 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7567 if ([self isEditing])
7570 Section *section = [self sectionAtIndexPath:indexPath];
7572 SectionController *controller = [[[SectionController alloc]
7573 initWithDatabase:database_
7574 section:[section name]
7576 [controller setDelegate:delegate_];
7578 [[self navigationController] pushViewController:controller animated:YES];
7582 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7583 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7584 [list_ setRowHeight:45.0f];
7585 [(UITableView *) list_ setDataSource:self];
7586 [list_ setDelegate:self];
7587 [self setView:list_];
7590 - (void) viewDidLoad {
7591 [super viewDidLoad];
7593 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7596 - (void) releaseSubviews {
7602 [super releaseSubviews];
7605 - (id) initWithDatabase:(Database *)database {
7606 if ((self = [super init]) != nil) {
7607 database_ = database;
7611 - (void) reloadData {
7614 NSArray *packages = [database_ packages];
7616 sections_ = [NSMutableArray arrayWithCapacity:16];
7617 filtered_ = [NSMutableArray arrayWithCapacity:16];
7619 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7622 for (Package *package in packages) {
7623 NSString *name([package section]);
7624 NSString *key(name == nil ? @"" : name);
7628 _profile(SectionsView$reloadData$Section)
7629 section = [sections objectForKey:key];
7630 if (section == nil) {
7631 _profile(SectionsView$reloadData$Section$Allocate)
7632 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7633 [sections setObject:section forKey:key];
7638 [section addToCount];
7640 _profile(SectionsView$reloadData$Filter)
7641 if (![package valid] || ![package visible])
7649 [sections_ addObjectsFromArray:[sections allValues]];
7651 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7653 for (Section *section in (id) sections_) {
7654 size_t count([section row]);
7658 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7659 [section setCount:count];
7660 [filtered_ addObject:section];
7663 [self updateNavigationItem];
7668 - (void) editButtonClicked {
7669 [self setEditing:![self isEditing] animated:YES];
7675 /* Changes Controller {{{ */
7676 @interface ChangesController : CyteViewController <
7677 CyteWebViewDelegate,
7678 UITableViewDataSource,
7681 _transient Database *database_;
7683 _H<NSMutableArray> packages_;
7684 _H<NSMutableArray> sections_;
7685 _H<UITableView, 2> list_;
7686 _H<CyteWebView, 1> dickbar_;
7688 _H<IndirectDelegate, 1> indirect_;
7689 _H<CydiaObject> cydia_;
7692 - (id) initWithDatabase:(Database *)database;
7696 @implementation ChangesController
7698 - (NSURL *) navigationURL {
7699 return [NSURL URLWithString:@"cydia://changes"];
7702 - (void) viewDidAppear:(BOOL)animated {
7703 [super viewDidAppear:animated];
7704 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7707 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7708 NSInteger count([sections_ count]);
7709 return count == 0 ? 1 : count;
7712 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7713 if ([sections_ count] == 0)
7715 return [[sections_ objectAtIndex:section] name];
7718 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7719 if ([sections_ count] == 0)
7721 return [[sections_ objectAtIndex:section] count];
7724 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7725 @synchronized (database_) {
7726 if ([database_ era] != era_)
7729 NSUInteger sectionIndex([path section]);
7730 if (sectionIndex >= [sections_ count])
7732 Section *section([sections_ objectAtIndex:sectionIndex]);
7733 NSInteger row([path row]);
7734 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7737 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7738 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7740 cell = [[[PackageCell alloc] init] autorelease];
7742 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7743 [cell setPackage:package asSummary:false];
7747 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7748 Package *package([self packageAtIndexPath:path]);
7749 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[NSString stringWithFormat:@"%@/#!/changes/", UI_]] autorelease]);
7750 [view setDelegate:delegate_];
7751 [[self navigationController] pushViewController:view animated:YES];
7755 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7756 NSString *context([alert context]);
7758 if ([context isEqualToString:@"norefresh"])
7759 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7762 - (void) refreshButtonClicked {
7763 if (IsReachable("cydia.saurik.com")) {
7764 [delegate_ beginUpdate];
7765 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7767 UIAlertView *alert = [[[UIAlertView alloc]
7768 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
7769 message:@"Host Unreachable" // XXX: Localize
7771 cancelButtonTitle:UCLocalize("OK")
7772 otherButtonTitles:nil
7775 [alert setContext:@"norefresh"];
7780 - (void) upgradeButtonClicked {
7781 [delegate_ distUpgrade];
7782 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7786 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7787 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7788 [self setView:view];
7790 list_ = [[[UITableView alloc] initWithFrame:[view bounds] style:UITableViewStylePlain] autorelease];
7791 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7792 [list_ setRowHeight:73];
7793 [(UITableView *) list_ setDataSource:self];
7794 [list_ setDelegate:self];
7795 [view addSubview:list_];
7797 if (AprilFools_ && kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
7798 CGRect dickframe([view bounds]);
7799 dickframe.size.height = 44;
7801 dickbar_ = [[[CyteWebView alloc] initWithFrame:dickframe] autorelease];
7802 [dickbar_ setDelegate:self];
7803 [view addSubview:dickbar_];
7805 [dickbar_ setBackgroundColor:[UIColor clearColor]];
7806 [dickbar_ setScalesPageToFit:YES];
7808 UIWebDocumentView *document([dickbar_ _documentView]);
7809 [document setBackgroundColor:[UIColor clearColor]];
7810 [document setDrawsBackground:NO];
7812 WebView *webview([document webView]);
7813 [webview setShouldUpdateWhileOffscreen:NO];
7815 UIScrollView *scroller([dickbar_ scrollView]);
7816 [scroller setScrollingEnabled:NO];
7817 [scroller setFixedBackgroundPattern:YES];
7818 [scroller setBackgroundColor:[UIColor clearColor]];
7820 WebPreferences *preferences([webview preferences]);
7821 [preferences setCacheModel:WebCacheModelDocumentBrowser];
7822 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
7823 [preferences setOfflineWebApplicationCacheEnabled:YES];
7825 [dickbar_ loadRequest:[NSURLRequest
7826 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/dickbar/", UI_]]]
7827 cachePolicy:NSURLRequestUseProtocolCachePolicy
7831 UIEdgeInsets inset = {44, 0, 0, 0};
7832 [list_ setContentInset:inset];
7834 [dickbar_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7838 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7839 NSURL *url([request URL]);
7843 if ([frame isEqualToString:@"_open"])
7844 [delegate_ openURL:url];
7846 WebFrame *frame(nil);
7847 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7848 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7850 frame = [view mainFrame];
7852 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7854 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7855 [controller setDelegate:delegate_];
7856 [[self navigationController] pushViewController:controller animated:YES];
7862 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7863 return [CydiaWebViewController requestWithHeaders:request];
7866 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7867 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7870 - (void) setDelegate:(id)delegate {
7871 [super setDelegate:delegate];
7872 [cydia_ setDelegate:delegate];
7875 - (void) viewDidLoad {
7876 [super viewDidLoad];
7878 [[self navigationItem] setTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES"))];
7881 - (void) releaseSubviews {
7888 [super releaseSubviews];
7891 - (id) initWithDatabase:(Database *)database {
7892 if ((self = [super init]) != nil) {
7893 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7894 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7895 database_ = database;
7899 - (NSMutableArray *) _reloadPackages {
7900 @synchronized (database_) {
7901 era_ = [database_ era];
7902 NSArray *packages([database_ packages]);
7904 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7907 _profile(ChangesController$_reloadPackages$Filter)
7908 for (Package *package in packages)
7909 if ([package upgradableAndEssential:YES] || [package visible])
7910 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7913 _profile(ChangesController$_reloadPackages$radixSort)
7914 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7921 - (void) _reloadData {
7922 NSMutableArray *packages;
7926 UIProgressHUD *hud([delegate_ addProgressHUD]);
7927 [hud setText:UCLocalize("LOADING")];
7928 //NSLog(@"HUD:%@::%@", delegate_, hud);
7929 packages = [self yieldToSelector:@selector(_reloadPackages)];
7930 [delegate_ removeProgressHUD:hud];
7932 packages = [self _reloadPackages];
7935 @synchronized (database_) {
7936 if (era_ != [database_ era])
7939 packages_ = packages;
7940 sections_ = [NSMutableArray arrayWithCapacity:16];
7942 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7943 Section *ignored = nil;
7944 Section *section = nil;
7948 bool unseens = false;
7950 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7952 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7953 Package *package = [packages_ objectAtIndex:offset];
7955 BOOL uae = [package upgradableAndEssential:YES];
7959 time_t seen([package seen]);
7961 if (section == nil || last != seen) {
7965 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7968 _profile(ChangesController$reloadData$Allocate)
7969 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7970 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7971 [sections_ addObject:section];
7975 [section addToCount];
7976 } else if ([package ignored]) {
7977 if (ignored == nil) {
7978 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7980 [ignored addToCount];
7983 [upgradable addToCount];
7988 CFRelease(formatter);
7991 Section *last = [sections_ lastObject];
7992 size_t count = [last count];
7993 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7994 [sections_ removeLastObject];
7997 if ([ignored count] != 0)
7998 [sections_ insertObject:ignored atIndex:0];
8000 [sections_ insertObject:upgradable atIndex:0];
8004 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
8005 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
8006 style:UIBarButtonItemStylePlain
8008 action:@selector(upgradeButtonClicked)
8009 ] autorelease]) animated:YES];
8011 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
8012 initWithTitle:UCLocalize("REFRESH")
8013 style:UIBarButtonItemStylePlain
8015 action:@selector(refreshButtonClicked)
8016 ] autorelease]) animated:YES];
8021 - (void) reloadData {
8023 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
8028 /* Search Controller {{{ */
8029 @interface SearchController : FilteredPackageListController <
8032 _H<UISearchBar, 1> search_;
8036 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
8037 - (void) reloadData;
8041 @implementation SearchController
8043 - (NSURL *) referrerURL {
8044 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
8047 - (NSURL *) navigationURL {
8048 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
8049 return [NSURL URLWithString:@"cydia://search"];
8051 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
8054 - (NSArray *) termsForQuery:(NSString *)query {
8055 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
8056 for (NSString *component in [query componentsSeparatedByString:@" "])
8057 if ([component length] != 0)
8058 [terms addObject:component];
8063 - (void) useSearch {
8064 [self setObject:[self termsForQuery:[search_ text]] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
8069 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
8070 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8075 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
8076 [search_ resignFirstResponder];
8080 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
8081 [search_ setText:@""];
8082 [self searchBarButtonClicked:searchBar];
8085 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
8086 [self searchBarButtonClicked:searchBar];
8089 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
8090 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8094 - (bool) shouldYield {
8098 - (bool) shouldBlock {
8099 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
8102 - (bool) isSummarized {
8103 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
8106 - (bool) showsSections {
8110 - (NSMutableArray *) _reloadPackages {
8111 NSMutableArray *packages([super _reloadPackages]);
8112 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8113 [packages radixSortUsingSelector:@selector(rank)];
8117 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
8118 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[self termsForQuery:query]])) {
8119 search_ = [[[UISearchBar alloc] init] autorelease];
8120 [search_ setDelegate:self];
8123 [search_ setText:query];
8127 - (void) viewDidAppear:(BOOL)animated {
8128 [super viewDidAppear:animated];
8130 if (!searchloaded_) {
8131 searchloaded_ = YES;
8132 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
8133 [search_ layoutSubviews];
8134 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
8136 UITextField *textField;
8137 if ([search_ respondsToSelector:@selector(searchField)])
8138 textField = [search_ searchField];
8140 textField = MSHookIvar<UITextField *>(search_, "_searchField");
8142 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8143 [textField setEnablesReturnKeyAutomatically:NO];
8144 [[self navigationItem] setTitleView:textField];
8147 if ([self isSummarized])
8148 [search_ becomeFirstResponder];
8151 - (void) reloadData {
8152 id object([search_ text]);
8153 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8154 object = [self termsForQuery:object];
8156 [self setObject:object];
8162 - (void) didSelectPackage:(Package *)package {
8163 [search_ resignFirstResponder];
8164 [super didSelectPackage:package];
8169 /* Package Settings Controller {{{ */
8170 @interface PackageSettingsController : CyteViewController <
8171 UITableViewDataSource,
8174 _transient Database *database_;
8176 _H<Package> package_;
8177 _H<UITableView, 2> table_;
8178 _H<UISwitch> subscribedSwitch_;
8179 _H<UISwitch> ignoredSwitch_;
8180 _H<UITableViewCell> subscribedCell_;
8181 _H<UITableViewCell> ignoredCell_;
8184 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
8188 @implementation PackageSettingsController
8190 - (NSURL *) navigationURL {
8191 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
8194 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8195 if (package_ == nil)
8198 if ([package_ installed] == nil)
8204 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8205 if (package_ == nil)
8208 // both sections contain just one item right now.
8212 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8216 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8218 return UCLocalize("SHOW_ALL_CHANGES_EX");
8220 return UCLocalize("IGNORE_UPGRADES_EX");
8223 - (void) onSubscribed:(id)control {
8224 bool value([control isOn]);
8225 if (package_ == nil)
8227 if ([package_ setSubscribed:value])
8228 [delegate_ updateData];
8231 - (void) _updateIgnored {
8232 const char *package([name_ UTF8String]);
8233 bool on([ignoredSwitch_ isOn]);
8235 pid_t pid(ExecFork());
8237 FILE *dpkg(popen("dpkg --set-selections", "w"));
8238 fwrite(package, strlen(package), 1, dpkg);
8241 fwrite(" hold\n", 6, 1, dpkg);
8243 fwrite(" install\n", 9, 1, dpkg);
8254 - (void) onIgnored:(id)control {
8255 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8256 [invocation setTarget:self];
8257 [invocation setSelector:@selector(_updateIgnored)];
8259 [delegate_ reloadDataWithInvocation:invocation];
8262 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8263 if (package_ == nil)
8266 switch ([indexPath section]) {
8267 case 0: return subscribedCell_;
8268 case 1: return ignoredCell_;
8277 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8278 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8279 [self setView:view];
8281 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8282 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8283 [(UITableView *) table_ setDataSource:self];
8284 [table_ setDelegate:self];
8285 [view addSubview:table_];
8287 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8288 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8289 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8291 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8292 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8293 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8295 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8296 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8297 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8298 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8300 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8301 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8302 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8303 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8306 - (void) viewDidLoad {
8307 [super viewDidLoad];
8309 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8312 - (void) releaseSubviews {
8314 subscribedCell_ = nil;
8316 ignoredSwitch_ = nil;
8317 subscribedSwitch_ = nil;
8319 [super releaseSubviews];
8322 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8323 if ((self = [super init]) != nil) {
8324 database_ = database;
8329 - (void) reloadData {
8332 package_ = [database_ packageWithName:name_];
8334 if (package_ != nil) {
8335 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8336 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8337 } // XXX: what now, G?
8339 [table_ reloadData];
8345 /* Installed Controller {{{ */
8346 @interface InstalledController : FilteredPackageListController {
8350 - (id) initWithDatabase:(Database *)database;
8352 - (void) updateRoleButton;
8353 - (void) queueStatusDidChange;
8357 @implementation InstalledController
8359 - (NSURL *) referrerURL {
8360 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8363 - (NSURL *) navigationURL {
8364 return [NSURL URLWithString:@"cydia://installed"];
8367 - (id) initWithDatabase:(Database *)database {
8368 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8369 [self updateRoleButton];
8370 [self queueStatusDidChange];
8375 - (void) queueButtonClicked {
8380 - (void) queueStatusDidChange {
8384 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8385 initWithTitle:UCLocalize("QUEUE")
8386 style:UIBarButtonItemStyleDone
8388 action:@selector(queueButtonClicked)
8391 [[self navigationItem] setLeftBarButtonItem:nil];
8397 - (void) updateRoleButton {
8398 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8399 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8400 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8401 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8403 action:@selector(roleButtonClicked)
8407 - (void) roleButtonClicked {
8408 [self setObject:[NSNumber numberWithBool:expert_]];
8412 [self updateRoleButton];
8418 /* Source Cell {{{ */
8419 @interface SourceCell : CyteTableViewCell <
8420 CyteTableViewCellDelegate
8424 _H<NSString> origin_;
8425 _H<NSString> label_;
8428 - (void) setSource:(Source *)source;
8432 @implementation SourceCell
8434 - (void) _setImage:(NSArray *)data {
8435 if ([url_ isEqual:[data objectAtIndex:0]]) {
8436 icon_ = [data objectAtIndex:1];
8437 [content_ setNeedsDisplay];
8441 - (void) _setSource:(NSURL *) url {
8442 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8444 if (NSData *data = [NSURLConnection
8445 sendSynchronousRequest:[NSURLRequest
8447 cachePolicy:NSURLRequestUseProtocolCachePolicy
8451 returningResponse:NULL
8454 if (UIImage *image = [UIImage imageWithData:data])
8455 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8460 - (void) setSource:(Source *)source {
8461 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8463 origin_ = [source name];
8464 label_ = [source rooturi];
8466 [content_ setNeedsDisplay];
8468 url_ = [source iconURL];
8469 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8472 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8473 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8474 UIView *content([self contentView]);
8475 CGRect bounds([content bounds]);
8477 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8478 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8479 [content_ setBackgroundColor:[UIColor whiteColor]];
8480 [content addSubview:content_];
8482 [content_ setDelegate:self];
8483 [content_ setOpaque:YES];
8485 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8489 - (NSString *) accessibilityLabel {
8493 - (void) drawContentRect:(CGRect)rect {
8494 bool highlighted(highlighted_);
8495 float width(rect.size.width);
8499 rect.size = [(UIImage *) icon_ size];
8501 while (rect.size.width > 32 || rect.size.height > 32) {
8502 rect.size.width /= 2;
8503 rect.size.height /= 2;
8506 rect.origin.x = 25 - rect.size.width / 2;
8507 rect.origin.y = 25 - rect.size.height / 2;
8509 [icon_ drawInRect:rect];
8517 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 65) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8521 [label_ drawAtPoint:CGPointMake(48, 29) forWidth:(width - 65) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8526 /* Source Controller {{{ */
8527 @interface SourceController : FilteredPackageListController {
8528 _transient Source *source_;
8532 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8536 @implementation SourceController
8538 - (NSURL *) referrerURL {
8539 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sources/%@", UI_, [key_ stringByAddingPercentEscapesIncludingReserved]]];
8542 - (NSURL *) navigationURL {
8543 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8546 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8547 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8549 key_ = [source key];
8553 - (void) reloadData {
8554 source_ = [database_ sourceWithKey:key_];
8555 key_ = [source_ key];
8556 [self setObject:source_];
8558 [[self navigationItem] setTitle:[source_ label]];
8565 /* Sources Controller {{{ */
8566 @interface SourcesController : CyteViewController <
8567 UITableViewDataSource,
8570 _transient Database *database_;
8573 _H<UITableView, 2> list_;
8574 _H<NSMutableArray> sources_;
8578 _H<UIProgressHUD> hud_;
8581 //NSURLConnection *installer_;
8582 NSURLConnection *trivial_bz2_;
8583 NSURLConnection *trivial_gz_;
8584 //NSURLConnection *automatic_;
8589 - (id) initWithDatabase:(Database *)database;
8590 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8594 @implementation SourcesController
8596 - (void) _releaseConnection:(NSURLConnection *)connection {
8597 if (connection != nil) {
8598 [connection cancel];
8599 //[connection setDelegate:nil];
8600 [connection release];
8605 //[self _releaseConnection:installer_];
8606 [self _releaseConnection:trivial_gz_];
8607 [self _releaseConnection:trivial_bz2_];
8608 //[self _releaseConnection:automatic_];
8613 - (NSURL *) navigationURL {
8614 return [NSURL URLWithString:@"cydia://sources"];
8617 - (void) viewDidAppear:(BOOL)animated {
8618 [super viewDidAppear:animated];
8619 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8622 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8626 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8630 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8631 return [sources_ count];
8634 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8635 @synchronized (database_) {
8636 if ([database_ era] != era_)
8639 NSUInteger index([indexPath row]);
8640 return index < [sources_ count] ? [sources_ objectAtIndex:index] : nil;
8643 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8644 static NSString *cellIdentifier = @"SourceCell";
8646 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8647 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8648 [cell setSource:[self sourceAtIndexPath:indexPath]];
8649 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8654 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8655 Source *source = [self sourceAtIndexPath:indexPath];
8656 if (source == nil) return;
8658 SourceController *controller = [[[SourceController alloc]
8659 initWithDatabase:database_
8663 [controller setDelegate:delegate_];
8665 [[self navigationController] pushViewController:controller animated:YES];
8668 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8669 Source *source = [self sourceAtIndexPath:indexPath];
8670 return [source record] != nil;
8673 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8674 if (editingStyle == UITableViewCellEditingStyleDelete) {
8675 Source *source = [self sourceAtIndexPath:indexPath];
8676 if (source == nil) return;
8678 [Sources_ removeObjectForKey:[source key]];
8681 [delegate_ _saveConfig];
8682 [delegate_ reloadDataWithInvocation:nil];
8687 [delegate_ addTrivialSource:href_];
8690 [delegate_ syncData];
8693 - (NSString *) getWarning {
8694 NSString *href(href_);
8695 NSRange colon([href rangeOfString:@"://"]);
8696 if (colon.location != NSNotFound)
8697 href = [href substringFromIndex:(colon.location + 3)];
8698 href = [href stringByAddingPercentEscapes];
8699 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8701 NSURL *url([NSURL URLWithString:href]);
8703 NSStringEncoding encoding;
8704 NSError *error(nil);
8706 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8707 return [warning length] == 0 ? nil : warning;
8711 - (void) _endConnection:(NSURLConnection *)connection {
8712 // XXX: the memory management in this method is horribly awkward
8714 NSURLConnection **field = NULL;
8715 if (connection == trivial_bz2_)
8716 field = &trivial_bz2_;
8717 else if (connection == trivial_gz_)
8718 field = &trivial_gz_;
8719 _assert(field != NULL);
8720 [connection release];
8724 trivial_bz2_ == nil &&
8727 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8729 [delegate_ releaseNetworkActivityIndicator];
8731 [delegate_ removeProgressHUD:hud_];
8735 if (warning != nil) {
8736 UIAlertView *alert = [[[UIAlertView alloc]
8737 initWithTitle:UCLocalize("SOURCE_WARNING")
8740 cancelButtonTitle:UCLocalize("CANCEL")
8742 UCLocalize("ADD_ANYWAY"),
8746 [alert setContext:@"warning"];
8747 [alert setNumberOfRows:1];
8750 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8756 } else if (error_ != nil) {
8757 UIAlertView *alert = [[[UIAlertView alloc]
8758 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8759 message:[error_ localizedDescription]
8761 cancelButtonTitle:UCLocalize("OK")
8762 otherButtonTitles:nil
8765 [alert setContext:@"urlerror"];
8770 UIAlertView *alert = [[[UIAlertView alloc]
8771 initWithTitle:UCLocalize("NOT_REPOSITORY")
8772 message:UCLocalize("NOT_REPOSITORY_EX")
8774 cancelButtonTitle:UCLocalize("OK")
8775 otherButtonTitles:nil
8778 [alert setContext:@"trivial"];
8788 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8789 switch ([response statusCode]) {
8795 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8796 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8798 [self _endConnection:connection];
8801 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8802 [self _endConnection:connection];
8805 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8806 NSURL *url([NSURL URLWithString:href]);
8808 NSMutableURLRequest *request = [NSMutableURLRequest
8810 cachePolicy:NSURLRequestUseProtocolCachePolicy
8814 [request setHTTPMethod:method];
8816 if (Machine_ != NULL)
8817 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8819 if (UniqueID_ != nil)
8820 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8822 if ([url isCydiaSecure]) {
8823 if (UniqueID_ != nil)
8824 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8827 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8830 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8831 NSString *context([alert context]);
8833 if ([context isEqualToString:@"source"]) {
8836 NSString *href = [[alert textField] text];
8838 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8840 if (![href hasSuffix:@"/"])
8841 href_ = [href stringByAppendingString:@"/"];
8845 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8846 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8847 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8851 // XXX: this is stupid
8852 hud_ = [delegate_ addProgressHUD];
8853 [hud_ setText:UCLocalize("VERIFYING_URL")];
8854 [delegate_ retainNetworkActivityIndicator];
8863 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8864 } else if ([context isEqualToString:@"trivial"])
8865 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8866 else if ([context isEqualToString:@"urlerror"])
8867 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8868 else if ([context isEqualToString:@"warning"]) {
8871 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8880 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8885 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8886 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8887 [list_ setRowHeight:53];
8888 [(UITableView *) list_ setDataSource:self];
8889 [list_ setDelegate:self];
8890 [self setView:list_];
8893 - (void) viewDidLoad {
8894 [super viewDidLoad];
8896 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8897 [self updateButtonsForEditingStatusAnimated:NO];
8900 - (void) viewWillAppear:(BOOL)animated {
8901 [super viewWillAppear:animated];
8903 [list_ setEditing:NO];
8904 [self updateButtonsForEditingStatusAnimated:NO];
8907 - (void) releaseSubviews {
8912 [super releaseSubviews];
8915 - (id) initWithDatabase:(Database *)database {
8916 if ((self = [super init]) != nil) {
8917 database_ = database;
8921 - (void) reloadData {
8924 @synchronized (database_) {
8925 era_ = [database_ era];
8927 sources_ = [NSMutableArray arrayWithCapacity:16];
8928 [sources_ addObjectsFromArray:[database_ sources]];
8930 [sources_ sortUsingSelector:@selector(compareByName:)];
8933 int count([sources_ count]);
8935 for (int i = 0; i != count; i++) {
8936 if ([[sources_ objectAtIndex:i] record] == nil)
8944 - (void) showAddSourcePrompt {
8945 UIAlertView *alert = [[[UIAlertView alloc]
8946 initWithTitle:UCLocalize("ENTER_APT_URL")
8949 cancelButtonTitle:UCLocalize("CANCEL")
8951 UCLocalize("ADD_SOURCE"),
8955 [alert setContext:@"source"];
8957 [alert setNumberOfRows:1];
8958 [alert addTextFieldWithValue:@"http://" label:@""];
8960 UITextInputTraits *traits = [[alert textField] textInputTraits];
8961 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8962 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8963 [traits setKeyboardType:UIKeyboardTypeURL];
8964 // XXX: UIReturnKeyDone
8965 [traits setReturnKeyType:UIReturnKeyNext];
8970 - (void) addButtonClicked {
8971 [self showAddSourcePrompt];
8974 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8975 BOOL editing([list_ isEditing]);
8977 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8978 initWithTitle:UCLocalize("ADD")
8979 style:UIBarButtonItemStylePlain
8981 action:@selector(addButtonClicked)
8982 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8984 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8985 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8986 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8988 action:@selector(editButtonClicked)
8989 ] autorelease] animated:animated];
8991 if (IsWildcat_ && !editing)
8992 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8993 initWithTitle:UCLocalize("SETTINGS")
8994 style:UIBarButtonItemStylePlain
8996 action:@selector(settingsButtonClicked)
9000 - (void) settingsButtonClicked {
9001 [delegate_ showSettings];
9004 - (void) editButtonClicked {
9005 [list_ setEditing:![list_ isEditing] animated:YES];
9006 [self updateButtonsForEditingStatusAnimated:YES];
9012 /* Settings Controller {{{ */
9013 @interface SettingsController : CyteViewController <
9014 UITableViewDataSource,
9017 _transient Database *database_;
9018 // XXX: ok, "roledelegate_"?...
9019 _transient id roledelegate_;
9020 _H<UITableView, 2> table_;
9021 _H<UISegmentedControl> segment_;
9022 _H<UIView> container_;
9025 - (void) showDoneButton;
9026 - (void) resizeSegmentedControl;
9030 @implementation SettingsController
9033 table_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
9034 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9035 [table_ setDelegate:self];
9036 [(UITableView *) table_ setDataSource:self];
9037 [self setView:table_];
9039 NSArray *items = [NSArray arrayWithObjects:
9041 UCLocalize("HACKER"),
9042 UCLocalize("DEVELOPER"),
9044 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
9045 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
9046 [container_ addSubview:segment_];
9049 - (void) viewDidLoad {
9050 [super viewDidLoad];
9052 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
9055 if ([Role_ isEqualToString:@"User"]) index = 0;
9056 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
9057 if ([Role_ isEqualToString:@"Developer"]) index = 2;
9059 [segment_ setSelectedSegmentIndex:index];
9060 [self showDoneButton];
9063 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
9064 [self resizeSegmentedControl];
9067 - (void) releaseSubviews {
9072 [super releaseSubviews];
9075 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
9076 if ((self = [super init]) != nil) {
9077 database_ = database;
9078 roledelegate_ = delegate;
9082 - (void) resizeSegmentedControl {
9083 CGFloat width = [[self view] frame].size.width;
9084 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
9087 - (void) viewWillAppear:(BOOL)animated {
9088 [super viewWillAppear:animated];
9089 [self resizeSegmentedControl];
9092 - (void) viewDidAppear:(BOOL)animated {
9093 [super viewDidAppear:animated];
9094 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
9095 [self resizeSegmentedControl];
9098 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
9099 [self resizeSegmentedControl];
9102 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
9103 [self resizeSegmentedControl];
9107 NSString *role(nil);
9109 switch ([segment_ selectedSegmentIndex]) {
9110 case 0: role = @"User"; break;
9111 case 1: role = @"Hacker"; break;
9112 case 2: role = @"Developer"; break;
9117 if (![role isEqualToString:Role_]) {
9118 bool rolling(Role_ == nil);
9121 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
9125 [Metadata_ setObject:Settings_ forKey:@"Settings"];
9129 [roledelegate_ loadData];
9131 [roledelegate_ updateData];
9135 - (void) segmentChanged:(UISegmentedControl *)control {
9136 [self showDoneButton];
9139 - (void) saveAndClose {
9142 [[self navigationItem] setRightBarButtonItem:nil];
9143 [[self navigationController] dismissModalViewControllerAnimated:YES];
9146 - (void) doneButtonClicked {
9147 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
9148 [spinner startAnimating];
9149 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
9150 [[self navigationItem] setRightBarButtonItem:spinItem];
9152 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
9155 - (void) showDoneButton {
9156 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
9157 initWithTitle:UCLocalize("DONE")
9158 style:UIBarButtonItemStyleDone
9160 action:@selector(doneButtonClicked)
9161 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
9164 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
9165 // XXX: For not having a single cell in the table, this sure is a lot of sections.
9169 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
9173 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
9174 return nil; // This method is required by the protocol.
9177 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
9179 return UCLocalize("ROLE_EX");
9181 return [NSString stringWithFormat:
9182 @"%@: %@\n%@: %@\n%@: %@",
9183 UCLocalize("USER"), UCLocalize("USER_EX"),
9184 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
9185 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
9190 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
9191 return section == 3 ? 44.0f : 0;
9194 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
9195 return section == 3 ? container_ : nil;
9198 - (void) reloadData {
9201 [table_ reloadData];
9206 /* Stash Controller {{{ */
9207 @interface StashController : CyteViewController {
9208 _H<UIActivityIndicatorView> spinner_;
9209 _H<UILabel> status_;
9210 _H<UILabel> caption_;
9215 @implementation StashController
9218 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
9219 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
9220 [self setView:view];
9222 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
9224 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
9225 CGRect spinrect = [spinner_ frame];
9226 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
9227 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
9228 [spinner_ setFrame:spinrect];
9229 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
9230 [view addSubview:spinner_];
9231 [spinner_ startAnimating];
9234 captrect.size.width = [[self view] frame].size.width;
9235 captrect.size.height = 40.0f;
9236 captrect.origin.x = 0;
9237 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
9238 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
9239 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
9240 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9241 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
9242 [caption_ setTextColor:[UIColor whiteColor]];
9243 [caption_ setBackgroundColor:[UIColor clearColor]];
9244 [caption_ setShadowColor:[UIColor blackColor]];
9245 [caption_ setTextAlignment:UITextAlignmentCenter];
9246 [view addSubview:caption_];
9249 statusrect.size.width = [[self view] frame].size.width;
9250 statusrect.size.height = 30.0f;
9251 statusrect.origin.x = 0;
9252 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
9253 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
9254 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9255 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
9256 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
9257 [status_ setTextColor:[UIColor whiteColor]];
9258 [status_ setBackgroundColor:[UIColor clearColor]];
9259 [status_ setShadowColor:[UIColor blackColor]];
9260 [status_ setTextAlignment:UITextAlignmentCenter];
9261 [view addSubview:status_];
9264 - (void) releaseSubviews {
9269 [super releaseSubviews];
9275 @interface CYURLCache : SDURLCache {
9280 @implementation CYURLCache
9282 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
9285 else if ([event isEqualToString:@"no-cache"])
9287 else if ([event isEqualToString:@"store"])
9289 else if ([event isEqualToString:@"invalid"])
9291 else if ([event isEqualToString:@"memory"])
9293 else if ([event isEqualToString:@"disk"])
9295 else if ([event isEqualToString:@"miss"])
9298 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
9302 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
9303 if (NSURLResponse *response = [cached response])
9304 if (NSString *mime = [response MIMEType])
9305 if ([mime isEqualToString:@"text/cache-manifest"]) {
9306 NSURL *url([response URL]);
9309 NSLog(@"###: %@", [url absoluteString]);
9312 @synchronized (HostConfig_) {
9313 [CachedURLs_ addObject:url];
9317 [super storeCachedResponse:cached forRequest:request];
9322 @interface Cydia : UIApplication <
9323 ConfirmationControllerDelegate,
9326 UINavigationControllerDelegate,
9327 UITabBarControllerDelegate
9329 _H<UIWindow> window_;
9330 _H<CYTabBarController> tabbar_;
9331 _H<CydiaLoadingViewController> emulated_;
9333 _H<NSMutableArray> essential_;
9334 _H<NSMutableArray> broken_;
9336 Database *database_;
9338 _H<NSURL> starturl_;
9343 _H<StashController> stash_;
9352 @implementation Cydia
9354 - (void) lockSuspend {
9355 if (locked_++ == 0) {
9356 if ($SBSSetInterceptsMenuButtonForever != NULL)
9357 (*$SBSSetInterceptsMenuButtonForever)(true);
9359 [self setIdleTimerDisabled:YES];
9363 - (void) unlockSuspend {
9364 if (--locked_ == 0) {
9365 [self setIdleTimerDisabled:NO];
9367 if ($SBSSetInterceptsMenuButtonForever != NULL)
9368 (*$SBSSetInterceptsMenuButtonForever)(false);
9372 - (void) beginUpdate {
9373 [tabbar_ beginUpdate];
9377 return [tabbar_ updating];
9381 if ([broken_ count] != 0) {
9382 int count = [broken_ count];
9384 UIAlertView *alert = [[[UIAlertView alloc]
9385 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9386 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9388 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9390 UCLocalize("TEMPORARY_IGNORE"),
9394 [alert setContext:@"fixhalf"];
9395 [alert setNumberOfRows:2];
9397 } else if (!Ignored_ && [essential_ count] != 0) {
9398 int count = [essential_ count];
9400 UIAlertView *alert = [[[UIAlertView alloc]
9401 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9402 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9404 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9406 UCLocalize("UPGRADE_ESSENTIAL"),
9407 UCLocalize("COMPLETE_UPGRADE"),
9411 [alert setContext:@"upgrade"];
9416 - (void) returnToCydia {
9420 - (void) _saveConfig {
9421 @synchronized (database_) {
9428 NSString *error(nil);
9430 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9432 NSError *error(nil);
9433 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9434 NSLog(@"failure to save metadata data: %@", error);
9439 NSLog(@"failure to serialize metadata: %@", error);
9443 CydiaWriteSources();
9446 // Navigation controller for the queuing badge.
9447 - (UINavigationController *) queueNavigationController {
9448 NSArray *controllers = [tabbar_ viewControllers];
9449 return [controllers objectAtIndex:3];
9452 - (void) unloadData {
9453 [tabbar_ unloadData];
9456 - (void) _updateData {
9460 UINavigationController *navigation = [self queueNavigationController];
9462 id queuedelegate = nil;
9463 if ([[navigation viewControllers] count] > 0)
9464 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9466 [queuedelegate queueStatusDidChange];
9467 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9470 - (void) _refreshIfPossible:(NSDate *)update {
9471 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9473 bool recently = false;
9474 if (update != nil) {
9475 NSTimeInterval interval([update timeIntervalSinceNow]);
9476 if (interval <= 0 && interval > -(15*60))
9480 // Don't automatic refresh if:
9481 // - We already refreshed recently.
9482 // - We already auto-refreshed this launch.
9483 // - Auto-refresh is disabled.
9484 // - Cydia's server is not reachable
9485 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9486 // If we are cancelling, we need to make sure it knows it's already loaded.
9489 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9491 // We are going to load, so remember that.
9494 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9500 - (void) refreshIfPossible {
9501 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9504 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9505 @synchronized (self) {
9506 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9508 [hud setText:UCLocalize("RELOADING_DATA")];
9510 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9514 [essential_ removeAllObjects];
9515 [broken_ removeAllObjects];
9517 NSArray *packages([database_ packages]);
9518 for (Package *package in packages) {
9520 [broken_ addObject:package];
9521 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9522 if ([package essential] && [package installed] != nil)
9523 [essential_ addObject:package];
9528 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9531 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9532 [changesItem setBadgeValue:badge];
9533 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9534 [self setApplicationIconBadgeNumber:changes];
9537 [changesItem setBadgeValue:nil];
9538 [changesItem setAnimatedBadge:NO];
9539 [self setApplicationIconBadgeNumber:0];
9545 [self removeProgressHUD:hud];
9548 - (void) updateData {
9552 - (void) updateDataAndLoad {
9554 if ([database_ progressDelegate] == nil)
9560 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9563 - (void) disemulate {
9564 if (emulated_ == nil)
9567 [window_ addSubview:[tabbar_ view]];
9568 [[emulated_ view] removeFromSuperview];
9570 [window_ setUserInteractionEnabled:YES];
9573 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9574 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9576 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9578 UIViewController *parent;
9579 if (emulated_ == nil)
9588 [parent presentModalViewController:navigation animated:YES];
9591 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9592 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9594 if (navigation != nil)
9595 [navigation pushViewController:progress animated:YES];
9597 [self presentModalViewController:progress force:YES];
9599 [progress invoke:invocation withTitle:title];
9603 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9604 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9607 - (void) repairWithInvocation:(NSInvocation *)invocation {
9609 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9613 - (void) repairWithSelector:(SEL)selector {
9614 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9617 - (void) reloadData {
9618 [self reloadDataWithInvocation:nil];
9619 if ([database_ progressDelegate] == nil)
9625 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9628 - (void) addSource:(NSDictionary *) source {
9629 CydiaAddSource(source);
9632 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9633 CydiaAddSource(href, distribution, sections);
9636 - (void) addTrivialSource:(NSString *)href {
9637 CydiaAddSource(href, @"./");
9640 - (void) updateValues {
9645 pkgProblemResolver *resolver = [database_ resolver];
9647 resolver->InstallProtect();
9648 if (!resolver->Resolve(true))
9653 // XXX: this is a really crappy way of doing this.
9654 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9655 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9656 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9657 if ([tabbar_ updating])
9658 [tabbar_ cancelUpdate];
9660 if (![database_ prepare])
9663 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9664 [page setDelegate:self];
9665 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9668 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9669 [tabbar_ presentModalViewController:confirm_ animated:YES];
9675 @synchronized (self) {
9680 - (void) clearPackage:(Package *)package {
9681 @synchronized (self) {
9688 - (void) installPackages:(NSArray *)packages {
9689 @synchronized (self) {
9690 for (Package *package in packages)
9697 - (void) installPackage:(Package *)package {
9698 @synchronized (self) {
9705 - (void) removePackage:(Package *)package {
9706 @synchronized (self) {
9713 - (void) distUpgrade {
9714 @synchronized (self) {
9715 if (![database_ upgrade])
9723 system("su -c /usr/bin/uicache mobile");
9728 UIProgressHUD *hud([self addProgressHUD]);
9729 [hud setText:UCLocalize("LOADING")];
9730 [self yieldToSelector:@selector(_uicache)];
9731 [self removeProgressHUD:hud];
9735 [database_ perform];
9736 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9737 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9740 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9743 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9744 [self unlockSuspend];
9747 - (void) showSettings {
9748 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9751 - (void) retainNetworkActivityIndicator {
9752 if (activity_++ == 0)
9753 [self setNetworkActivityIndicatorVisible:YES];
9756 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9760 - (void) releaseNetworkActivityIndicator {
9761 if (--activity_ == 0)
9762 [self setNetworkActivityIndicatorVisible:NO];
9765 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9770 - (void) cancelAndClear:(bool)clear {
9771 @synchronized (self) {
9783 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9784 NSString *context([alert context]);
9786 if ([context isEqualToString:@"conffile"]) {
9787 FILE *input = [database_ input];
9788 if (button == [alert cancelButtonIndex])
9789 fprintf(input, "N\n");
9790 else if (button == [alert firstOtherButtonIndex])
9791 fprintf(input, "Y\n");
9794 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9795 } else if ([context isEqualToString:@"fixhalf"]) {
9796 if (button == [alert cancelButtonIndex]) {
9797 @synchronized (self) {
9798 for (Package *broken in (id) broken_) {
9801 NSString *id = [broken id];
9802 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9803 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9804 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9805 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9811 } else if (button == [alert firstOtherButtonIndex]) {
9812 [broken_ removeAllObjects];
9816 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9817 } else if ([context isEqualToString:@"upgrade"]) {
9818 if (button == [alert firstOtherButtonIndex]) {
9819 @synchronized (self) {
9820 for (Package *essential in (id) essential_)
9821 [essential install];
9826 } else if (button == [alert firstOtherButtonIndex] + 1) {
9828 } else if (button == [alert cancelButtonIndex]) {
9832 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9836 - (void) system:(NSString *)command {
9837 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9840 system([command UTF8String]);
9846 - (void) applicationWillSuspend {
9848 [super applicationWillSuspend];
9851 - (BOOL) isSafeToSuspend {
9854 NSLog(@"isSafeToSuspend: locked_ != 0");
9859 // Use external process status API internally.
9860 // This is probably a really bad idea.
9861 // XXX: what is the point of this? does this solve anything at all?
9862 uint64_t status = 0;
9864 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9865 notify_get_state(notify_token, &status);
9866 notify_cancel(notify_token);
9871 NSLog(@"isSafeToSuspend: status != 0");
9877 NSLog(@"isSafeToSuspend: -> true");
9882 - (void) applicationSuspend:(__GSEvent *)event {
9883 if ([self isSafeToSuspend])
9884 [super applicationSuspend:event];
9887 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9888 if ([self isSafeToSuspend])
9889 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9892 - (void) _setSuspended:(BOOL)value {
9893 if ([self isSafeToSuspend])
9894 [super _setSuspended:value];
9897 - (UIProgressHUD *) addProgressHUD {
9898 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9899 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9901 [window_ setUserInteractionEnabled:NO];
9903 UIViewController *target(tabbar_);
9904 if (UIViewController *modal = [target modalViewController])
9907 [hud showInView:[target view]];
9913 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9914 [self unlockSuspend];
9916 [hud removeFromSuperview];
9917 [window_ setUserInteractionEnabled:YES];
9920 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9921 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9924 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9925 NSString *scheme([[url scheme] lowercaseString]);
9926 if ([[url absoluteString] length] <= [scheme length] + 3)
9928 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9929 NSArray *components([path componentsSeparatedByString:@"/"]);
9931 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9932 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9933 if (controller != nil)
9934 [controller setDelegate:self];
9938 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9941 NSString *base([components objectAtIndex:0]);
9943 CyteViewController *controller = nil;
9945 if ([base isEqualToString:@"url"]) {
9946 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9947 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9948 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9949 } else if (!external && [components count] == 1) {
9950 if ([base isEqualToString:@"manage"]) {
9951 controller = [[[ManageController alloc] init] autorelease];
9954 if ([base isEqualToString:@"storage"]) {
9955 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9958 if ([base isEqualToString:@"sources"]) {
9959 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9962 if ([base isEqualToString:@"home"]) {
9963 controller = [[[HomeController alloc] init] autorelease];
9966 if ([base isEqualToString:@"sections"]) {
9967 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9970 if ([base isEqualToString:@"search"]) {
9971 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9974 if ([base isEqualToString:@"changes"]) {
9975 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9978 if ([base isEqualToString:@"installed"]) {
9979 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9981 } else if ([components count] == 2) {
9982 NSString *argument = [components objectAtIndex:1];
9984 if ([base isEqualToString:@"package"]) {
9985 controller = [self pageForPackage:argument withReferrer:referrer];
9988 if (!external && [base isEqualToString:@"search"]) {
9989 controller = [[[SearchController alloc] initWithDatabase:database_ query:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9992 if (!external && [base isEqualToString:@"sections"]) {
9993 if ([argument isEqualToString:@"all"])
9995 controller = [[[SectionController alloc] initWithDatabase:database_ section:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9998 if (!external && [base isEqualToString:@"sources"]) {
9999 if ([argument isEqualToString:@"add"]) {
10000 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
10001 [(SourcesController *)controller showAddSourcePrompt];
10003 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
10004 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
10008 if (!external && [base isEqualToString:@"launch"]) {
10009 [self launchApplicationWithIdentifier:argument suspended:NO];
10012 } else if (!external && [components count] == 3) {
10013 NSString *arg1 = [components objectAtIndex:1];
10014 NSString *arg2 = [components objectAtIndex:2];
10016 if ([base isEqualToString:@"package"]) {
10017 if ([arg2 isEqualToString:@"settings"]) {
10018 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
10019 } else if ([arg2 isEqualToString:@"files"]) {
10020 if (Package *package = [database_ packageWithName:arg1]) {
10021 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
10022 [(FileTable *)controller setPackage:package];
10028 [controller setDelegate:self];
10032 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
10033 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
10036 [tabbar_ setUnselectedViewController:page];
10038 return page != nil;
10041 - (void) applicationOpenURL:(NSURL *)url {
10042 [super applicationOpenURL:url];
10047 [self openCydiaURL:url forExternal:YES];
10050 - (void) applicationWillResignActive:(UIApplication *)application {
10051 // Stop refreshing if you get a phone call or lock the device.
10052 if ([tabbar_ updating])
10053 [tabbar_ cancelUpdate];
10055 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
10056 [super applicationWillResignActive:application];
10059 - (void) saveState {
10060 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
10061 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
10062 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
10065 [self _saveConfig];
10068 - (void) applicationWillTerminate:(UIApplication *)application {
10072 - (void) setConfigurationData:(NSString *)data {
10073 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
10075 if (!conffile_r(data)) {
10076 lprintf("E:invalid conffile\n");
10080 NSString *ofile = conffile_r[1];
10081 //NSString *nfile = conffile_r[2];
10083 UIAlertView *alert = [[[UIAlertView alloc]
10084 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
10085 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
10087 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
10089 UCLocalize("ACCEPT_NEW_COPY"),
10090 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
10094 [alert setContext:@"conffile"];
10095 [alert setNumberOfRows:2];
10099 - (void) addStashController {
10100 [self lockSuspend];
10101 stash_ = [[[StashController alloc] init] autorelease];
10102 [window_ addSubview:[stash_ view]];
10105 - (void) removeStashController {
10106 [[stash_ view] removeFromSuperview];
10108 [self unlockSuspend];
10112 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
10113 UpdateExternalStatus(1);
10114 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
10115 UpdateExternalStatus(0);
10117 [self removeStashController];
10119 pid_t pid(ExecFork());
10121 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
10122 perror("launchctl stop");
10129 - (void) setupViewControllers {
10130 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
10132 NSMutableArray *items([NSMutableArray arrayWithObjects:
10133 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
10134 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
10135 [[[UITabBarItem alloc] initWithTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES")) image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
10136 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
10140 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
10141 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10143 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10146 NSMutableArray *controllers([NSMutableArray array]);
10147 for (UITabBarItem *item in items) {
10148 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
10149 [controller setTabBarItem:item];
10150 [controllers addObject:controller];
10152 [tabbar_ setViewControllers:controllers];
10154 [tabbar_ setUpdateDelegate:self];
10157 - (void) _sendMemoryWarningNotification {
10158 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
10159 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
10161 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
10164 - (void) _sendMemoryWarningNotifications {
10166 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
10172 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
10174 [[NSURLCache sharedURLCache] removeAllCachedResponses];
10177 - (void) applicationDidFinishLaunching:(id)unused {
10178 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
10181 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
10182 [self setApplicationSupportsShakeToEdit:NO];
10184 @synchronized (HostConfig_) {
10185 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
10188 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
10189 initWithMemoryCapacity:524288
10190 diskCapacity:10485760
10191 diskPath:[NSString stringWithFormat:@"%@/SDURLCache", Cache_]
10194 [CydiaWebViewController _initialize];
10196 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
10198 // this would disallow http{,s} URLs from accessing this data
10199 //[WebView registerURLSchemeAsLocal:@"cydia"];
10201 Font12_ = [UIFont systemFontOfSize:12];
10202 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
10203 Font14_ = [UIFont systemFontOfSize:14];
10204 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
10205 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
10207 essential_ = [NSMutableArray arrayWithCapacity:4];
10208 broken_ = [NSMutableArray arrayWithCapacity:4];
10210 // XXX: I really need this thing... like, seriously... I'm sorry
10211 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
10213 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
10214 [window_ orderFront:self];
10215 [window_ makeKey:self];
10216 [window_ setHidden:NO];
10218 if (false) stash: {
10219 [self addStashController];
10220 // XXX: this would be much cleaner as a yieldToSelector:
10221 // that way the removeStashController could happen right here inline
10222 // we also could no longer require the useless stash_ field anymore
10223 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
10228 int error(stat("/", &root));
10229 _assert(error != -1);
10231 #define Stash_(path) do { \
10232 struct stat folder; \
10233 int error(lstat((path), &folder)); \
10234 if (error != -1 && ( \
10235 folder.st_dev == root.st_dev && \
10236 S_ISDIR(folder.st_mode) \
10237 ) || error == -1 && ( \
10238 errno == ENOENT || \
10243 Stash_("/Applications");
10244 Stash_("/Library/Ringtones");
10245 Stash_("/Library/Wallpaper");
10246 //Stash_("/usr/bin");
10247 Stash_("/usr/include");
10248 Stash_("/usr/lib/pam");
10249 Stash_("/usr/libexec");
10250 Stash_("/usr/share");
10251 //Stash_("/var/lib");
10253 database_ = [Database sharedInstance];
10254 [database_ setDelegate:self];
10256 [window_ setUserInteractionEnabled:NO];
10257 [self setupViewControllers];
10259 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
10260 [window_ addSubview:[emulated_ view]];
10262 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
10266 - (NSArray *) defaultStartPages {
10267 NSMutableArray *standard = [NSMutableArray array];
10268 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
10269 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
10270 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
10272 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
10274 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
10275 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
10277 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10281 - (void) loadData {
10283 if (Role_ == nil) {
10284 [window_ setUserInteractionEnabled:YES];
10285 [self showSettings];
10288 if ([emulated_ modalViewController] != nil)
10289 [emulated_ dismissModalViewControllerAnimated:YES];
10290 [window_ setUserInteractionEnabled:NO];
10293 [self reloadDataWithInvocation:nil];
10294 [self refreshIfPossible];
10299 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
10300 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
10301 int standardIndex = 0;
10302 NSArray *standard = [self defaultStartPages];
10309 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
10310 if (valid && closed != nil) {
10311 NSTimeInterval interval([closed timeIntervalSinceNow]);
10312 // XXX: Is 30 minutes the optimal time here?
10313 if (interval <= -(30*60))
10317 if (valid && [saved count] != [standard count])
10321 for (unsigned int i = 0; i < [standard count]; i++) {
10322 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10323 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10324 // but it's good enough for now.
10325 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10332 NSArray *items = nil;
10334 [tabbar_ setSelectedIndex:savedIndex];
10337 [tabbar_ setSelectedIndex:standardIndex];
10341 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10342 NSArray *stack = [items objectAtIndex:tab];
10343 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10344 NSMutableArray *current = [NSMutableArray array];
10346 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10347 NSString *addr = [stack objectAtIndex:nav];
10348 NSURL *url = [NSURL URLWithString:addr];
10349 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10351 [current addObject:page];
10354 [navigation setViewControllers:current];
10357 // (Try to) show the startup URL.
10358 if (starturl_ != nil) {
10359 [self openCydiaURL:starturl_ forExternal:NO];
10364 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10365 if (item != nil && IsWildcat_) {
10366 [sheet showFromBarButtonItem:item animated:YES];
10368 [sheet showInView:window_];
10372 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10373 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10374 [progress setTitle:task];
10375 [progress addProgressEvent:event];
10378 - (void) addProgressEventForTask:(NSArray *)data {
10379 CydiaProgressEvent *event([data objectAtIndex:0]);
10380 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10381 [self addProgressEvent:event forTask:task];
10384 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10385 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10391 id Alloc_(id self, SEL selector) {
10392 id object = alloc_(self, selector);
10393 lprintf("[%s]A-%p\n", self->isa->name, object);
10398 id Dealloc_(id self, SEL selector) {
10399 id object = dealloc_(self, selector);
10400 lprintf("[%s]D-%p\n", self->isa->name, object);
10404 static NSSet *MobilizedFiles_;
10406 static NSURL *MobilizeURL(NSURL *url) {
10407 NSString *path([url path]);
10408 if ([path hasPrefix:@"/var/root/"]) {
10409 NSString *file([path substringFromIndex:10]);
10410 if ([MobilizedFiles_ containsObject:file])
10411 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10417 Class $CFXPreferencesPropertyListSource;
10418 @class CFXPreferencesPropertyListSource;
10420 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10421 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10422 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10423 url = MobilizeURL(url);
10424 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10425 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10431 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10432 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10433 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10434 url = MobilizeURL(url);
10435 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10436 //NSLog(@"%@ %@", [url absoluteString], value);
10442 Class $NSURLConnection;
10444 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10445 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10447 NSURL *url([copy URL]);
10449 NSString *host([url host]);
10450 NSString *scheme([[url scheme] lowercaseString]);
10452 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10454 @synchronized (HostConfig_) {
10455 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10456 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10457 [copy setHTTPShouldUsePipelining:YES];
10459 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10460 if ([control isEqualToString:@"max-age=0"])
10461 if ([CachedURLs_ containsObject:url]) {
10463 NSLog(@"~~~: %@", url);
10466 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10468 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10469 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10470 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10474 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10480 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10481 CGSize size([[UIScreen mainScreen] bounds].size);
10482 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10483 if ([$WAKWindow hasLandscapeOrientation])
10484 std::swap(size.width, size.height);*/
10488 Class $NSUserDefaults;
10490 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10491 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10492 return [NSString stringWithFormat:@"%@/LocalStorage", Cache_];
10493 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10496 int main(int argc, char *argv[]) {
10497 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10501 UpdateExternalStatus(0);
10503 if (Class $UIDevice = objc_getClass("UIDevice")) {
10504 UIDevice *device([$UIDevice currentDevice]);
10505 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10507 IsWildcat_ = false;
10509 UIScreen *screen([UIScreen mainScreen]);
10510 if ([screen respondsToSelector:@selector(scale)])
10511 ScreenScale_ = [screen scale];
10515 UIDevice *device([UIDevice currentDevice]);
10516 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10517 Idiom_ = @"iphone";
10519 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10520 if (idiom == UIUserInterfaceIdiomPhone)
10521 Idiom_ = @"iphone";
10522 else if (idiom == UIUserInterfaceIdiomPad)
10525 NSLog(@"unknown UIUserInterfaceIdiom!");
10528 Pcre pattern("^([0-9]+\\.[0-9]+)");
10530 if (pattern([device systemVersion]))
10531 Firmware_ = pattern[1];
10532 if (pattern(Cydia_))
10533 Major_ = pattern[1];
10535 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10537 HostConfig_ = [[[NSObject alloc] init] autorelease];
10538 @synchronized (HostConfig_) {
10539 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10540 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10541 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10542 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10543 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10546 NSString *ui(@"ui/ios");
10548 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10549 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10550 UI_ = CydiaURL(ui);
10552 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10554 MobilizedFiles_ = [NSMutableSet setWithObjects:
10555 @"Library/Preferences/com.apple.Accessibility.plist",
10556 @"Library/Preferences/com.apple.preferences.sounds.plist",
10559 /* Library Hacks {{{ */
10560 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10562 $WAKWindow = objc_getClass("WAKWindow");
10563 if ($WAKWindow != NULL)
10564 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10565 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10567 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10569 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10570 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10571 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10572 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10575 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10576 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10577 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10578 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10581 $NSURLConnection = objc_getClass("NSURLConnection");
10582 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10583 if (NSURLConnection$init$ != NULL) {
10584 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10585 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10588 $NSUserDefaults = objc_getClass("NSUserDefaults");
10589 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10590 if (NSUserDefaults$objectForKey$ != NULL) {
10591 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10592 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10595 /* Set Locale {{{ */
10596 Locale_ = CFLocaleCopyCurrent();
10597 Languages_ = [NSLocale preferredLanguages];
10599 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10600 //NSLog(@"%@", [Languages_ description]);
10603 if (Locale_ != NULL)
10604 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10605 else if (Languages_ != nil && [Languages_ count] != 0)
10606 lang = [[Languages_ objectAtIndex:0] UTF8String];
10608 // XXX: consider just setting to C and then falling through?
10611 if (lang != NULL) {
10612 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10613 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10616 NSLog(@"Setting Language: %s", lang);
10618 if (lang != NULL) {
10619 setenv("LANG", lang, true);
10620 std::setlocale(LC_ALL, lang);
10624 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10626 /* Parse Arguments {{{ */
10627 bool substrate(false);
10633 for (int argi(1); argi != argc; ++argi)
10634 if (strcmp(argv[argi], "--") == 0) {
10636 argv[argi] = argv[0];
10642 for (int argi(1); argi != arge; ++argi)
10643 if (strcmp(args[argi], "--substrate") == 0)
10646 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10650 App_ = [[NSBundle mainBundle] bundlePath];
10656 if (access("/var/mobile/Library/Keyboard/UserDictionary.sqlite", F_OK) == 0)
10657 system("mkdir -p /var/root/Library/Keyboard; cp -af /var/mobile/Library/Keyboard/UserDictionary.sqlite /var/root/Library/Keyboard/");
10659 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/root"] retain];
10661 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10662 alloc_ = alloc->method_imp;
10663 alloc->method_imp = (IMP) &Alloc_;*/
10665 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10666 dealloc_ = dealloc->method_imp;
10667 dealloc->method_imp = (IMP) &Dealloc_;*/
10669 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10670 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10672 /* System Information {{{ */
10676 size = sizeof(maxproc);
10677 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10678 perror("sysctlbyname(\"kern.maxproc\", ?)");
10679 else if (maxproc < 64) {
10681 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10682 perror("sysctlbyname(\"kern.maxproc\", #)");
10685 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10686 char *osversion = new char[size];
10687 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10688 perror("sysctlbyname(\"kern.osversion\", ?)");
10690 System_ = [NSString stringWithUTF8String:osversion];
10692 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10693 char *machine = new char[size];
10694 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10695 perror("sysctlbyname(\"hw.machine\", ?)");
10697 Machine_ = machine;
10699 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10700 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10701 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10703 UniqueID_ = UniqueIdentifier(device);
10705 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10706 Product_ = [info objectForKey:@"SafariProductVersion"];
10707 Safari_ = [info objectForKey:@"CFBundleVersion"];
10710 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10712 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10713 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10714 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10715 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10716 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10717 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10719 UserAgent_ = agent;
10721 /* Load Database {{{ */
10723 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10725 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10727 if (Metadata_ == NULL)
10728 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10730 Settings_ = [Metadata_ objectForKey:@"Settings"];
10732 Packages_ = [Metadata_ objectForKey:@"Packages"];
10734 Values_ = [Metadata_ objectForKey:@"Values"];
10735 Sections_ = [Metadata_ objectForKey:@"Sections"];
10736 Sources_ = [Metadata_ objectForKey:@"Sources"];
10738 Token_ = [Metadata_ objectForKey:@"Token"];
10740 Version_ = [Metadata_ objectForKey:@"Version"];
10743 if (Settings_ != nil)
10744 Role_ = [Settings_ objectForKey:@"Role"];
10746 if (Values_ == nil) {
10747 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10748 [Metadata_ setObject:Values_ forKey:@"Values"];
10751 if (Sections_ == nil) {
10752 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10753 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10756 if (Sources_ == nil) {
10757 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10758 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10761 if (Version_ == nil) {
10762 Version_ = [NSNumber numberWithUnsignedInt:0];
10763 [Metadata_ setObject:Version_ forKey:@"Version"];
10766 if ([Version_ unsignedIntValue] == 0) {
10767 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10768 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10769 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10770 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10772 Version_ = [NSNumber numberWithUnsignedInt:1];
10773 [Metadata_ setObject:Version_ forKey:@"Version"];
10775 [Metadata_ removeObjectForKey:@"LastUpdate"];
10781 CydiaWriteSources();
10784 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10787 if (Packages_ != nil) {
10789 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10793 [Metadata_ removeObjectForKey:@"Packages"];
10799 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10801 #define MobileSubstrate_(name) \
10802 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10803 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10804 if (handle == NULL) \
10805 NSLog(@"%s", dlerror()); \
10808 MobileSubstrate_(Activator)
10809 MobileSubstrate_(libstatusbar)
10810 MobileSubstrate_(SimulatedKeyEvents)
10811 MobileSubstrate_(WinterBoard)
10813 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10814 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10816 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10818 if (access("/User", F_OK) != 0 || version != 6) {
10820 system("/usr/libexec/cydia/firmware.sh");
10824 _assert([[NSFileManager defaultManager]
10825 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10826 withIntermediateDirectories:YES
10831 if (access("/tmp/cydia.chk", F_OK) == 0) {
10832 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10833 _assert(errno == ENOENT);
10834 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10835 _assert(errno == ENOENT);
10838 /* APT Initialization {{{ */
10839 _assert(pkgInitConfig(*_config));
10840 _assert(pkgInitSystem(*_config, _system));
10843 _config->Set("APT::Acquire::Translation", lang);
10845 // XXX: this timeout might be important :(
10846 //_config->Set("Acquire::http::Timeout", 15);
10848 _config->Set("Acquire::http::MaxParallel", 3);
10850 /* Color Choices {{{ */
10851 space_ = CGColorSpaceCreateDeviceRGB();
10853 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10854 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10855 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10856 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10857 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10858 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10859 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10860 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10861 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10863 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10864 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10866 /* UIKit Configuration {{{ */
10867 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10868 if ($GSFontSetUseLegacyFontMetrics != NULL)
10869 $GSFontSetUseLegacyFontMetrics(YES);
10871 // XXX: I have a feeling this was important
10872 //UIKeyboardDisableAutomaticAppearance();
10875 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10877 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemHasCapability"));
10878 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10880 ShowPromoted_ = fast;
10881 PulseInterval_ = fast ? 50000 : 500000;
10883 Colon_ = UCLocalize("COLON_DELIMITED");
10884 Elision_ = UCLocalize("ELISION");
10885 Error_ = UCLocalize("ERROR");
10886 Warning_ = UCLocalize("WARNING");
10888 AprilFools_ = false;
10891 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10893 CGColorSpaceRelease(space_);
10894 CFRelease(Locale_);