1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2013 Jay Freeman (saurik)
5 /* GNU General Public License, Version 3 {{{ */
7 * Cydia is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
12 * Cydia is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Cydia. If not, see <http://www.gnu.org/licenses/>.
22 // XXX: wtf/FastMalloc.h... wtf?
23 #define USE_SYSTEM_MALLOC 1
25 /* #include Directives {{{ */
26 #include "CyteKit/UCPlatform.h"
27 #include "CyteKit/Localize.h"
29 #include <objc/objc.h>
30 #include <objc/runtime.h>
32 #include <CoreGraphics/CoreGraphics.h>
33 #include <Foundation/Foundation.h>
36 #define DEPLOYMENT_TARGET_MACOSX 1
37 #define CF_BUILDING_CF 1
38 #include <CoreFoundation/CFInternal.h>
41 #include <CoreFoundation/CFPriv.h>
42 #include <CoreFoundation/CFUniChar.h>
44 #include <SystemConfiguration/SystemConfiguration.h>
46 #include <UIKit/UIKit.h>
47 #include "iPhonePrivate.h"
49 #include <IOKit/IOKitLib.h>
51 #include <QuartzCore/CALayer.h>
53 #include <WebCore/WebCoreThread.h>
54 #include <WebKit/DOMHTMLIFrameElement.h>
61 #include <ext/stdio_filebuf.h>
65 #include <apt-pkg/acquire.h>
66 #include <apt-pkg/acquire-item.h>
67 #include <apt-pkg/algorithms.h>
68 #include <apt-pkg/cachefile.h>
69 #include <apt-pkg/clean.h>
70 #include <apt-pkg/configuration.h>
71 #include <apt-pkg/debindexfile.h>
72 #include <apt-pkg/debmetaindex.h>
73 #include <apt-pkg/error.h>
74 #include <apt-pkg/init.h>
75 #include <apt-pkg/mmap.h>
76 #include <apt-pkg/pkgrecords.h>
77 #include <apt-pkg/sha1.h>
78 #include <apt-pkg/sourcelist.h>
79 #include <apt-pkg/sptr.h>
80 #include <apt-pkg/strutl.h>
81 #include <apt-pkg/tagfile.h>
83 #include <apr-1/apr_pools.h>
85 #include <sys/types.h>
87 #include <sys/sysctl.h>
88 #include <sys/param.h>
89 #include <sys/mount.h>
90 #include <sys/reboot.h>
97 #include <mach-o/nlist.h>
106 #include <Cytore.hpp>
109 #include <CydiaSubstrate/CydiaSubstrate.h>
110 #include "Menes/Menes.h"
112 #include "CyteKit/IndirectDelegate.h"
113 #include "CyteKit/PerlCompatibleRegEx.hpp"
114 #include "CyteKit/TableViewCell.h"
115 #include "CyteKit/WebScriptObject-Cyte.h"
116 #include "CyteKit/WebViewController.h"
117 #include "CyteKit/WebViewTableViewCell.h"
118 #include "CyteKit/stringWithUTF8Bytes.h"
120 #include "Cydia/MIMEAddress.h"
121 #include "Cydia/LoadingViewController.h"
122 #include "Cydia/ProgressEvent.h"
124 #include "SDURLCache/SDURLCache.h"
131 #define _timestamp ({ \
133 gettimeofday(&tv, NULL); \
134 tv.tv_sec * 1000000 + tv.tv_usec; \
137 typedef std::vector<class ProfileTime *> TimeList;
147 ProfileTime(const char *name) :
151 times_.push_back(this);
154 void AddTime(uint64_t time) {
161 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
173 ProfileTimer(ProfileTime &time) :
180 time_.AddTime(_timestamp - start_);
185 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
187 std::cerr << "========" << std::endl;
190 #define _profile(name) { \
191 static ProfileTime name(#name); \
192 ProfileTimer _ ## name(name);
197 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
198 #define synchronized(lock) \
199 synchronized(static_cast<NSObject *>(lock))
201 extern NSString *Cydia_;
203 #define lprintf(args...) fprintf(stderr, args)
206 #define TraceLogging (1 && !ForRelease)
207 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
208 #define ProfileTimes (0 && !ForRelease)
209 #define ForSaurik (0 && !ForRelease)
210 #define LogBrowser (0 && !ForRelease)
211 #define TrackResize (0 && !ForRelease)
212 #define ManualRefresh (1 && !ForRelease)
213 #define ShowInternals (0 && !ForRelease)
214 #define AlwaysReload (0 && !ForRelease)
215 #define TryIndexedCollation (0 && !ForRelease)
219 #define _trace(args...)
224 #define _profile(name) {
227 #define PrintTimes() do {} while (false)
230 // Hash Functions/Structures {{{
231 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
239 static bool ShowPromoted_;
241 static NSString *Colon_;
243 static NSString *Error_;
244 static NSString *Warning_;
246 static NSString *Cache_;
248 static bool AprilFools_;
250 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
252 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
254 static NSString *UniqueIdentifier(UIDevice *device = nil) {
255 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
256 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
258 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
261 static bool IsReachable(const char *name) {
262 SCNetworkReachabilityFlags flags; {
263 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
264 SCNetworkReachabilityGetFlags(reachability, &flags);
265 CFRelease(reachability);
268 // XXX: this elaborate mess is what Apple is using to determine this? :(
269 // XXX: do we care if the user has to intervene? maybe that's ok?
271 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
272 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
273 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
274 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
275 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
276 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
281 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
283 static _finline NSString *CydiaURL(NSString *path) {
285 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
286 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
287 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
288 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
289 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
291 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
294 static void ReapZombie(pid_t pid) {
297 if (waitpid(pid, &status, 0) == -1)
303 static _finline void UpdateExternalStatus(uint64_t newStatus) {
305 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
306 notify_set_state(notify_token, newStatus);
307 notify_cancel(notify_token);
309 notify_post("com.saurik.Cydia.status");
312 static CGFloat CYStatusBarHeight() {
313 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
314 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
317 /* NSForcedOrderingSearch doesn't work on the iPhone */
318 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
319 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
320 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
322 /* Insertion Sort {{{ */
324 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
325 const char *ptr = (const char *)list;
327 CFIndex half = count / 2;
328 const char *probe = ptr + elementSize * half;
329 CFComparisonResult cr = comparator(element, probe, context);
330 if (0 == cr) return (probe - (const char *)list) / elementSize;
331 ptr = (cr < 0) ? ptr : probe + elementSize;
332 count = (cr < 0) ? half : (half + (count & 1) - 1);
334 return (ptr - (const char *)list) / elementSize;
337 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
338 const char *ptr = (const char *)list;
340 CFIndex half = count / 2;
341 const char *probe = ptr + elementSize * half;
342 CFComparisonResult cr = comparator(element, probe, context);
343 if (0 == cr) return (probe - (const char *)list) / elementSize;
344 ptr = (cr < 0) ? ptr : probe + elementSize;
345 count = (cr < 0) ? half : (half + (count & 1) - 1);
347 return (ptr - (const char *)list) / elementSize;
350 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
351 if (range.length == 0)
353 const void **values(new const void *[range.length]);
354 CFArrayGetValues(array, range, values);
356 #if HistogramInsertionSort > 0
357 uint32_t total(0), *offsets(new uint32_t[range.length]);
360 for (CFIndex index(1); index != range.length; ++index) {
361 const void *value(values[index]);
362 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
363 CFIndex correct(index);
364 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
365 #if HistogramInsertionSort > 1
366 NSLog(@"%@ < %@", value, values[correct - 1]);
371 if (correct != index) {
372 size_t offset(index - correct);
373 #if HistogramInsertionSort
377 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
379 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
380 values[correct] = value;
384 CFArrayReplaceValues(array, range, values, range.length);
387 #if HistogramInsertionSort > 0
388 for (CFIndex index(0); index != range.length; ++index)
389 if (offsets[index] != 0)
390 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
391 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
398 /* Apple Bug Fixes {{{ */
399 @implementation UIWebDocumentView (Cydia)
401 - (void) _setScrollerOffset:(CGPoint)offset {
402 UIScroller *scroller([self _scroller]);
404 CGSize size([scroller contentSize]);
405 CGSize bounds([scroller bounds].size);
408 max.x = size.width - bounds.width;
409 max.y = size.height - bounds.height;
417 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
418 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
420 [scroller setOffset:offset];
426 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
427 size_t length([self length] - state->state);
430 else if (length > count)
432 for (size_t i(0); i != length; ++i)
433 objects[i] = [self item:state->state++];
434 state->itemsPtr = objects;
435 state->mutationsPtr = (unsigned long *) self;
439 /* Cydia NSString Additions {{{ */
440 @interface NSString (Cydia)
441 - (NSComparisonResult) compareByPath:(NSString *)other;
442 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
445 @implementation NSString (Cydia)
447 - (NSComparisonResult) compareByPath:(NSString *)other {
448 NSString *prefix = [self commonPrefixWithString:other options:0];
449 size_t length = [prefix length];
451 NSRange lrange = NSMakeRange(length, [self length] - length);
452 NSRange rrange = NSMakeRange(length, [other length] - length);
454 lrange = [self rangeOfString:@"/" options:0 range:lrange];
455 rrange = [other rangeOfString:@"/" options:0 range:rrange];
457 NSComparisonResult value;
459 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
460 value = NSOrderedSame;
461 else if (lrange.location == NSNotFound)
462 value = NSOrderedAscending;
463 else if (rrange.location == NSNotFound)
464 value = NSOrderedDescending;
466 value = NSOrderedSame;
468 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
469 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
470 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
471 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
473 NSComparisonResult result = [lpath compare:rpath];
474 return result == NSOrderedSame ? value : result;
477 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
478 return [(id)CFURLCreateStringByAddingPercentEscapes(
483 kCFStringEncodingUTF8
490 /* C++ NSString Wrapper Cache {{{ */
491 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
492 return size == 0 ? NULL :
493 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
494 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
497 static _finline CFStringRef CYStringCreate(const char *data) {
498 return CYStringCreate(data, strlen(data));
507 _finline void clear_() {
508 if (cache_ != NULL) {
515 _finline bool empty() const {
519 _finline size_t size() const {
523 _finline char *data() const {
527 _finline void clear() {
532 _finline CYString() :
539 _finline ~CYString() {
543 void operator =(const CYString &rhs) {
547 if (rhs.cache_ == nil)
550 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
553 void copy(apr_pool_t *pool) {
554 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
555 memcpy(temp, data_, size_);
560 void set(apr_pool_t *pool, const char *data, size_t size) {
566 data_ = const_cast<char *>(data);
574 _finline void set(apr_pool_t *pool, const char *data) {
575 set(pool, data, data == NULL ? 0 : strlen(data));
578 _finline void set(apr_pool_t *pool, const std::string &rhs) {
579 set(pool, rhs.data(), rhs.size());
582 bool operator ==(const CYString &rhs) const {
583 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
586 _finline operator CFStringRef() {
588 cache_ = CYStringCreate(data_, size_);
592 _finline operator id() {
593 return (NSString *) static_cast<CFStringRef>(*this);
596 _finline operator const char *() {
597 return reinterpret_cast<const char *>(data_);
601 /* C++ NSString Algorithm Adapters {{{ */
603 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
606 struct NSStringMapHash :
607 std::unary_function<NSString *, size_t>
609 _finline size_t operator ()(NSString *value) const {
610 return CFStringHashNSString((CFStringRef) value);
614 struct NSStringMapLess :
615 std::binary_function<NSString *, NSString *, bool>
617 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
618 return [lhs compare:rhs] == NSOrderedAscending;
622 struct NSStringMapEqual :
623 std::binary_function<NSString *, NSString *, bool>
625 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
626 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
627 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
628 //[lhs isEqualToString:rhs];
633 /* CoreGraphics Primitives {{{ */
638 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
639 CGFloat color[] = {red, green, blue, alpha};
640 return CGColorCreate(space, color);
649 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
650 color_(Create_(space, red, green, blue, alpha))
652 Set(space, red, green, blue, alpha);
657 CGColorRelease(color_);
664 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
666 color_ = Create_(space, red, green, blue, alpha);
669 operator CGColorRef() {
675 /* Random Global Variables {{{ */
676 static int PulseInterval_ = 500000;
678 static const NSString *UI_;
681 static bool RestartSubstrate_;
682 static NSArray *Finishes_;
684 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
685 #define NotifyConfig_ "/etc/notify.conf"
687 static bool Queuing_;
689 static CYColor Blue_;
690 static CYColor Blueish_;
691 static CYColor Black_;
692 static CYColor Folder_;
694 static CYColor White_;
695 static CYColor Gray_;
696 static CYColor Green_;
697 static CYColor Purple_;
698 static CYColor Purplish_;
700 static UIColor *InstallingColor_;
701 static UIColor *RemovingColor_;
703 static NSString *App_;
705 static BOOL Advanced_;
706 static BOOL Ignored_;
708 static _H<UIFont> Font12_;
709 static _H<UIFont> Font12Bold_;
710 static _H<UIFont> Font14_;
711 static _H<UIFont> Font18Bold_;
712 static _H<UIFont> Font22Bold_;
714 static const char *Machine_ = NULL;
715 static _H<NSString> System_;
716 static NSString *SerialNumber_ = nil;
717 static NSString *ChipID_ = nil;
718 static NSString *BBSNum_ = nil;
719 static _H<NSString> Token_;
720 static _H<NSString> UniqueID_;
721 static _H<NSString> UserAgent_;
722 static _H<NSString> Product_;
723 static _H<NSString> Safari_;
725 static CFLocaleRef Locale_;
726 static NSArray *Languages_;
727 static CGColorSpaceRef space_;
729 static NSDictionary *SectionMap_;
730 static NSMutableDictionary *Metadata_;
731 static _transient NSMutableDictionary *Settings_;
732 static _transient NSString *Role_;
733 static _transient NSMutableDictionary *Packages_;
734 static _transient NSMutableDictionary *Values_;
735 static _transient NSMutableDictionary *Sections_;
736 _H<NSMutableDictionary> Sources_;
737 static _transient NSNumber *Version_;
742 static CGFloat ScreenScale_;
743 static NSString *Idiom_;
744 static _H<NSString> Firmware_;
745 static NSString *Major_;
747 static _H<NSMutableDictionary> SessionData_;
748 static _H<NSObject> HostConfig_;
749 static _H<NSMutableSet> BridgedHosts_;
750 static _H<NSMutableSet> TokenHosts_;
751 static _H<NSMutableSet> InsecureHosts_;
752 static _H<NSMutableSet> PipelinedHosts_;
753 static _H<NSMutableSet> CachedURLs_;
755 static NSString *kCydiaProgressEventTypeError = @"Error";
756 static NSString *kCydiaProgressEventTypeInformation = @"Information";
757 static NSString *kCydiaProgressEventTypeStatus = @"Status";
758 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
761 /* Display Helpers {{{ */
762 inline float Interpolate(float begin, float end, float fraction) {
763 return (end - begin) * fraction + begin;
766 static _finline const char *StripVersion_(const char *version) {
767 const char *colon(strchr(version, ':'));
768 return colon == NULL ? version : colon + 1;
771 NSString *LocalizeSection(NSString *section) {
772 static Pcre title_r("^(.*?) \\((.*)\\)$");
773 if (title_r(section)) {
774 NSString *parent(title_r[1]);
775 NSString *child(title_r[2]);
777 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
778 LocalizeSection(parent),
779 LocalizeSection(child)
783 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
786 NSString *Simplify(NSString *title) {
787 const char *data = [title UTF8String];
788 size_t size = [title length];
790 static Pcre square_r("^\\[(.*)\\]$");
791 if (square_r(data, size))
792 return Simplify(square_r[1]);
794 static Pcre paren_r("^\\((.*)\\)$");
795 if (paren_r(data, size))
796 return Simplify(paren_r[1]);
798 static Pcre title_r("^(.*?) \\((.*)\\)$");
799 if (title_r(data, size))
800 return Simplify(title_r[1]);
806 NSString *GetLastUpdate() {
807 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
810 return UCLocalize("NEVER_OR_UNKNOWN");
812 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
813 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
815 CFRelease(formatter);
817 return [(NSString *) formatted autorelease];
820 bool isSectionVisible(NSString *section) {
821 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
822 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
823 return hidden == nil || ![hidden boolValue];
826 static NSObject *CYIOGetValue(const char *path, NSString *property) {
827 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
828 if (entry == MACH_PORT_NULL)
831 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
832 IOObjectRelease(entry);
836 return [(id) value autorelease];
839 static NSString *CYHex(NSData *data, bool reverse = false) {
843 size_t length([data length]);
844 uint8_t bytes[length];
845 [data getBytes:bytes];
847 char string[length * 2 + 1];
848 for (size_t i(0); i != length; ++i)
849 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
851 return [NSString stringWithUTF8String:string];
856 /* Delegate Prototypes {{{ */
859 @class CydiaProgressEvent;
861 @protocol DatabaseDelegate
862 - (void) repairWithSelector:(SEL)selector;
863 - (void) setConfigurationData:(NSString *)data;
864 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
867 @class CYPackageController;
869 @protocol CydiaDelegate
870 - (void) returnToCydia;
872 - (void) retainNetworkActivityIndicator;
873 - (void) releaseNetworkActivityIndicator;
874 - (void) clearPackage:(Package *)package;
875 - (void) installPackage:(Package *)package;
876 - (void) installPackages:(NSArray *)packages;
877 - (void) removePackage:(Package *)package;
878 - (void) beginUpdate;
880 - (void) distUpgrade;
883 - (void) _saveConfig;
885 - (void) addSource:(NSDictionary *)source;
886 - (void) addTrivialSource:(NSString *)href;
887 - (void) showSettings;
888 - (UIProgressHUD *) addProgressHUD;
889 - (void) removeProgressHUD:(UIProgressHUD *)hud;
890 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
891 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
895 /* Status Delegation {{{ */
897 public pkgAcquireStatus
900 _transient NSObject<ProgressDelegate> *delegate_;
910 void setDelegate(NSObject<ProgressDelegate> *delegate) {
911 delegate_ = delegate;
914 NSObject<ProgressDelegate> *getDelegate() const {
918 virtual bool MediaChange(std::string media, std::string drive) {
922 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
926 virtual void Fetch(pkgAcquire::ItemDesc &item) {
927 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
928 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
929 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
932 virtual void Done(pkgAcquire::ItemDesc &item) {
933 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
934 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
935 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
938 virtual void Fail(pkgAcquire::ItemDesc &item) {
940 item.Owner->Status == pkgAcquire::Item::StatIdle ||
941 item.Owner->Status == pkgAcquire::Item::StatDone
945 std::string &error(item.Owner->ErrorText);
949 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
950 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
953 virtual bool Pulse(pkgAcquire *Owner) {
954 bool value = pkgAcquireStatus::Pulse(Owner);
957 double(CurrentBytes + CurrentItems) /
958 double(TotalBytes + TotalItems)
961 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
962 [NSNumber numberWithDouble:percent], @"Percent",
964 [NSNumber numberWithDouble:CurrentBytes], @"Current",
965 [NSNumber numberWithDouble:TotalBytes], @"Total",
966 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
967 nil] waitUntilDone:YES];
969 if (value && ![delegate_ isProgressCancelled])
977 _finline bool WasCancelled() const {
981 virtual void Start() {
982 pkgAcquireStatus::Start();
983 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
986 virtual void Stop() {
987 pkgAcquireStatus::Stop();
988 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
989 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
993 /* Database Interface {{{ */
994 typedef std::map< unsigned long, _H<Source> > SourceMap;
996 @interface Database : NSObject {
1002 pkgCacheFile cache_;
1003 pkgDepCache::Policy *policy_;
1004 pkgRecords *records_;
1005 pkgProblemResolver *resolver_;
1006 pkgAcquire *fetcher_;
1008 SPtr<pkgPackageManager> manager_;
1009 pkgSourceList *list_;
1011 SourceMap sourceMap_;
1012 _H<NSMutableArray> sourceList_;
1014 CFMutableArrayRef packages_;
1016 _transient NSObject<DatabaseDelegate> *delegate_;
1017 _transient NSObject<ProgressDelegate> *progress_;
1025 std::map<const char *, _H<NSString> > sections_;
1028 + (Database *) sharedInstance;
1031 - (void) _readCydia:(NSNumber *)fd;
1032 - (void) _readStatus:(NSNumber *)fd;
1033 - (void) _readOutput:(NSNumber *)fd;
1037 - (Package *) packageWithName:(NSString *)name;
1039 - (pkgCacheFile &) cache;
1040 - (pkgDepCache::Policy *) policy;
1041 - (pkgRecords *) records;
1042 - (pkgProblemResolver *) resolver;
1043 - (pkgAcquire &) fetcher;
1044 - (pkgSourceList &) list;
1045 - (NSArray *) packages;
1046 - (NSArray *) sources;
1047 - (Source *) sourceWithKey:(NSString *)key;
1048 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1056 - (void) updateWithStatus:(Status &)status;
1058 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1060 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1061 - (NSObject<ProgressDelegate> *) progressDelegate;
1063 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1065 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1069 /* ProgressEvent Implementation {{{ */
1070 @implementation CydiaProgressEvent
1072 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1073 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1076 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1077 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1078 [event setPackage:package];
1082 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1083 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1085 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1086 NSArray *fields([description componentsSeparatedByString:@" "]);
1087 [event setItem:fields];
1089 if ([fields count] > 3) {
1090 [event setPackage:[fields objectAtIndex:2]];
1091 [event setVersion:[fields objectAtIndex:3]];
1094 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1099 + (NSArray *) _attributeKeys {
1100 return [NSArray arrayWithObjects:
1110 - (NSArray *) attributeKeys {
1111 return [[self class] _attributeKeys];
1114 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1115 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1118 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1119 if ((self = [super init]) != nil) {
1125 - (NSString *) message {
1129 - (NSString *) type {
1133 - (NSArray *) item {
1134 return (id) item_ ?: [NSNull null];
1137 - (void) setItem:(NSArray *)item {
1141 - (NSString *) package {
1142 return (id) package_ ?: [NSNull null];
1145 - (void) setPackage:(NSString *)package {
1149 - (NSString *) url {
1150 return (id) url_ ?: [NSNull null];
1153 - (void) setURL:(NSString *)url {
1157 - (void) setVersion:(NSString *)version {
1161 - (NSString *) version {
1162 return (id) version_ ?: [NSNull null];
1165 - (NSString *) compound:(NSString *)value {
1167 NSString *mode(nil); {
1168 NSString *type([self type]);
1169 if ([type isEqualToString:kCydiaProgressEventTypeError])
1170 mode = UCLocalize("ERROR");
1171 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1172 mode = UCLocalize("WARNING");
1176 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1182 - (NSString *) compoundMessage {
1183 return [self compound:[self message]];
1186 - (NSString *) compoundTitle {
1189 if (package_ == nil)
1191 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1192 title = [package name];
1196 return [self compound:title];
1202 // Cytore Definitions {{{
1203 struct PackageValue :
1206 Cytore::Offset<PackageValue> next_;
1208 uint32_t index_ : 23;
1209 uint32_t subscribed_ : 1;
1226 Cytore::Offset<PackageValue> packages_[1 << 16];
1229 static Cytore::File<MetaValue> MetaFile_;
1231 // Cytore Helper Functions {{{
1232 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1233 SplitHash nhash = { hashlittle(name, length) };
1235 PackageValue *metadata;
1237 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1238 offset: if (offset->IsNull()) {
1239 *offset = MetaFile_.New<PackageValue>(length + 1);
1240 metadata = &MetaFile_.Get(*offset);
1242 if (metadata == NULL) {
1246 metadata = new PackageValue();
1247 memset(metadata, 0, sizeof(*metadata));
1250 memcpy(metadata->name_, name, length + 1);
1251 metadata->nhash_ = nhash.u16[1];
1253 metadata = &MetaFile_.Get(*offset);
1255 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1256 offset = &metadata->next_;
1264 static void PackageImport(const void *key, const void *value, void *context) {
1265 bool &fail(*reinterpret_cast<bool *>(context));
1268 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1269 NSLog(@"failed to import package %@", key);
1273 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1274 NSDictionary *package((NSDictionary *) value);
1276 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1277 if ([subscribed boolValue] && !metadata->subscribed_)
1278 metadata->subscribed_ = true;
1280 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1281 time_t time([date timeIntervalSince1970]);
1282 if (metadata->first_ > time || metadata->first_ == 0)
1283 metadata->first_ = time;
1286 NSDate *date([package objectForKey:@"LastSeen"]);
1287 NSString *version([package objectForKey:@"LastVersion"]);
1289 if (date != nil && version != nil) {
1290 time_t time([date timeIntervalSince1970]);
1291 if (metadata->last_ < time || metadata->last_ == 0)
1292 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1293 size_t length(strlen(buffer));
1294 uint16_t vhash(hashlittle(buffer, length));
1296 size_t capped(std::min<size_t>(8, length));
1297 char *latest(buffer + length - capped);
1299 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1300 metadata->vhash_ = vhash;
1302 metadata->last_ = time;
1308 /* Source Class {{{ */
1309 @interface Source : NSObject {
1311 Database *database_;
1314 CYString depiction_;
1315 CYString description_;
1321 CYString distribution_;
1327 _H<NSString> authority_;
1329 CYString defaultIcon_;
1331 _H<NSMutableDictionary> record_;
1335 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1337 - (NSComparisonResult) compareByName:(Source *)source;
1339 - (NSString *) depictionForPackage:(NSString *)package;
1340 - (NSString *) supportForPackage:(NSString *)package;
1342 - (metaIndex *) metaIndex;
1343 - (NSDictionary *) record;
1346 - (NSString *) rooturi;
1347 - (NSString *) distribution;
1348 - (NSString *) type;
1351 - (NSString *) host;
1353 - (NSString *) name;
1354 - (NSString *) shortDescription;
1355 - (NSString *) label;
1356 - (NSString *) origin;
1357 - (NSString *) version;
1359 - (NSString *) defaultIcon;
1360 - (NSURL *) iconURL;
1364 @implementation Source
1368 distribution_.clear();
1373 description_.clear();
1379 defaultIcon_.clear();
1386 + (NSString *) webScriptNameForSelector:(SEL)selector {
1388 else if (selector == @selector(addSection:))
1389 return @"addSection";
1390 else if (selector == @selector(getField:))
1392 else if (selector == @selector(removeSection:))
1393 return @"removeSection";
1394 else if (selector == @selector(remove))
1400 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1401 return [self webScriptNameForSelector:selector] == nil;
1404 + (NSArray *) _attributeKeys {
1405 return [NSArray arrayWithObjects:
1416 @"shortDescription",
1423 - (NSArray *) attributeKeys {
1424 return [[self class] _attributeKeys];
1427 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1428 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1431 - (metaIndex *) metaIndex {
1435 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1438 trusted_ = index->IsTrusted();
1440 uri_.set(pool, index->GetURI());
1441 distribution_.set(pool, index->GetDist());
1442 type_.set(pool, index->GetType());
1444 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1445 if (dindex != NULL) {
1446 base_.set(pool, dindex->MetaIndexURI(""));
1449 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1452 pkgTagFile tags(&fd);
1454 pkgTagSection section;
1461 {"default-icon", &defaultIcon_},
1462 {"depiction", &depiction_},
1463 {"description", &description_},
1465 {"origin", &origin_},
1466 {"support", &support_},
1467 {"version", &version_},
1470 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1471 const char *start, *end;
1473 if (section.Find(names[i].name_, start, end)) {
1474 CYString &value(*names[i].value_);
1475 value.set(pool, start, end - start);
1481 record_ = [Sources_ objectForKey:[self key]];
1483 NSURL *url([NSURL URLWithString:uri_]);
1487 host_ = [host_ lowercaseString];
1492 authority_ = [url path];
1495 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1496 if ((self = [super init]) != nil) {
1497 era_ = [database era];
1498 database_ = database;
1501 [self setMetaIndex:index inPool:pool];
1505 - (NSString *) getField:(NSString *)name {
1506 @synchronized (database_) {
1507 if ([database_ era] != era_ || index_ == NULL)
1510 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1515 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1520 pkgTagFile tags(&fd);
1522 pkgTagSection section;
1525 const char *start, *end;
1526 if (!section.Find([name UTF8String], start, end))
1527 return (NSString *) [NSNull null];
1529 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1532 - (NSComparisonResult) compareByName:(Source *)source {
1533 NSString *lhs = [self name];
1534 NSString *rhs = [source name];
1536 if ([lhs length] != 0 && [rhs length] != 0) {
1537 unichar lhc = [lhs characterAtIndex:0];
1538 unichar rhc = [rhs characterAtIndex:0];
1540 if (isalpha(lhc) && !isalpha(rhc))
1541 return NSOrderedAscending;
1542 else if (!isalpha(lhc) && isalpha(rhc))
1543 return NSOrderedDescending;
1546 return [lhs compare:rhs options:LaxCompareOptions_];
1549 - (NSString *) depictionForPackage:(NSString *)package {
1550 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1553 - (NSString *) supportForPackage:(NSString *)package {
1554 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1557 - (NSArray *) sections {
1558 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1561 - (void) _addSection:(NSString *)section {
1564 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1565 if (![sections containsObject:section]) {
1566 [sections addObject:section];
1570 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1575 - (bool) addSection:(NSString *)section {
1579 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1583 - (void) _removeSection:(NSString *)section {
1587 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1588 if ([sections containsObject:section]) {
1589 [sections removeObject:section];
1594 - (bool) removeSection:(NSString *)section {
1598 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1603 [Sources_ removeObjectForKey:[self key]];
1608 bool value(record_ != nil);
1609 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1613 - (NSDictionary *) record {
1621 - (NSString *) rooturi {
1625 - (NSString *) distribution {
1626 return distribution_;
1629 - (NSString *) type {
1633 - (NSString *) baseuri {
1634 return base_.empty() ? nil : (id) base_;
1637 - (NSString *) iconuri {
1638 if (NSString *base = [self baseuri])
1639 return [base stringByAppendingString:@"CydiaIcon.png"];
1644 - (NSURL *) iconURL {
1645 if (NSString *uri = [self iconuri])
1646 return [NSURL URLWithString:uri];
1650 - (NSString *) key {
1651 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1654 - (NSString *) host {
1658 - (NSString *) name {
1659 return origin_.empty() ? (id) authority_ : origin_;
1662 - (NSString *) shortDescription {
1663 return description_;
1666 - (NSString *) label {
1667 return label_.empty() ? (id) authority_ : label_;
1670 - (NSString *) origin {
1674 - (NSString *) version {
1678 - (NSString *) defaultIcon {
1679 return defaultIcon_;
1684 /* CydiaOperation Class {{{ */
1685 @interface CydiaOperation : NSObject {
1686 _H<NSString> operator_;
1687 _H<NSString> value_;
1690 - (NSString *) operator;
1691 - (NSString *) value;
1695 @implementation CydiaOperation
1697 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1698 if ((self = [super init]) != nil) {
1699 operator_ = [NSString stringWithUTF8String:_operator];
1700 value_ = [NSString stringWithUTF8String:value];
1704 + (NSArray *) _attributeKeys {
1705 return [NSArray arrayWithObjects:
1711 - (NSArray *) attributeKeys {
1712 return [[self class] _attributeKeys];
1715 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1716 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1719 - (NSString *) operator {
1723 - (NSString *) value {
1729 /* CydiaClause Class {{{ */
1730 @interface CydiaClause : NSObject {
1731 _H<NSString> package_;
1732 _H<CydiaOperation> version_;
1735 - (NSString *) package;
1736 - (CydiaOperation *) version;
1740 @implementation CydiaClause
1742 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1743 if ((self = [super init]) != nil) {
1744 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1746 if (const char *version = dep.TargetVer())
1747 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1749 version_ = (id) [NSNull null];
1753 + (NSArray *) _attributeKeys {
1754 return [NSArray arrayWithObjects:
1760 - (NSArray *) attributeKeys {
1761 return [[self class] _attributeKeys];
1764 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1765 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1768 - (NSString *) package {
1772 - (CydiaOperation *) version {
1778 /* CydiaRelation Class {{{ */
1779 @interface CydiaRelation : NSObject {
1780 _H<NSString> relationship_;
1781 _H<NSMutableArray> clauses_;
1784 - (NSString *) relationship;
1785 - (NSArray *) clauses;
1789 @implementation CydiaRelation
1791 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1792 if ((self = [super init]) != nil) {
1793 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1794 clauses_ = [NSMutableArray arrayWithCapacity:8];
1796 pkgCache::DepIterator start;
1797 pkgCache::DepIterator end;
1798 dep.GlobOr(start, end); // ++dep
1801 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1803 // yes, seriously. (wtf?)
1811 + (NSArray *) _attributeKeys {
1812 return [NSArray arrayWithObjects:
1818 - (NSArray *) attributeKeys {
1819 return [[self class] _attributeKeys];
1822 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1823 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1826 - (NSString *) relationship {
1827 return relationship_;
1830 - (NSArray *) clauses {
1834 - (void) addClause:(CydiaClause *)clause {
1835 [clauses_ addObject:clause];
1840 /* Package Class {{{ */
1841 struct ParsedPackage {
1845 CYString architecture_;
1848 CYString depiction_;
1855 @interface Package : NSObject {
1858 uint32_t essential_ : 1;
1859 uint32_t obsolete_ : 1;
1860 uint32_t ignored_ : 1;
1861 uint32_t pooled_ : 1;
1867 _transient Database *database_;
1869 pkgCache::VerIterator version_;
1870 pkgCache::PkgIterator iterator_;
1871 pkgCache::VerFileIterator file_;
1877 CYString installed_;
1879 const char *section_;
1880 _transient NSString *section$_;
1884 PackageValue *metadata_;
1885 ParsedPackage *parsed_;
1887 _H<NSMutableArray> tags_;
1890 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1891 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1893 - (pkgCache::PkgIterator) iterator;
1896 - (NSString *) section;
1897 - (NSString *) simpleSection;
1899 - (NSString *) longSection;
1900 - (NSString *) shortSection;
1904 - (MIMEAddress *) maintainer;
1906 - (NSString *) longDescription;
1907 - (NSString *) shortDescription;
1910 - (PackageValue *) metadata;
1913 - (bool) subscribed;
1914 - (bool) setSubscribed:(bool)subscribed;
1918 - (NSString *) latest;
1919 - (NSString *) installed;
1920 - (BOOL) uninstalled;
1923 - (BOOL) upgradableAndEssential:(BOOL)essential;
1926 - (BOOL) unfiltered;
1930 - (BOOL) halfConfigured;
1931 - (BOOL) halfInstalled;
1933 - (NSString *) mode;
1936 - (NSString *) name;
1938 - (NSString *) homepage;
1939 - (NSString *) depiction;
1940 - (MIMEAddress *) author;
1942 - (NSString *) support;
1944 - (NSArray *) files;
1945 - (NSArray *) warnings;
1946 - (NSArray *) applications;
1948 - (Source *) source;
1951 - (BOOL) matches:(NSArray *)query;
1953 - (bool) hasSupportingRole;
1954 - (BOOL) hasTag:(NSString *)tag;
1955 - (NSString *) primaryPurpose;
1956 - (NSArray *) purposes;
1957 - (bool) isCommercial;
1959 - (void) setIndex:(size_t)index;
1961 - (CYString &) cyname;
1963 - (uint32_t) compareBySection:(NSArray *)sections;
1968 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1969 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1970 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1971 - (bool) isVisibleInSection:(NSString *)section;
1972 - (bool) isVisibleInSource:(Source *)source;
1976 uint32_t PackageChangesRadix(Package *self, void *) {
1981 uint32_t timestamp : 30;
1982 uint32_t ignored : 1;
1983 uint32_t upgradable : 1;
1987 bool upgradable([self upgradableAndEssential:YES]);
1988 value.bits.upgradable = upgradable ? 1 : 0;
1991 value.bits.timestamp = 0;
1992 value.bits.ignored = [self ignored] ? 0 : 1;
1993 value.bits.upgradable = 1;
1995 value.bits.timestamp = [self seen] >> 2;
1996 value.bits.ignored = 0;
1997 value.bits.upgradable = 0;
2000 return _not(uint32_t) - value.key;
2003 uint32_t PackagePrefixRadix(Package *self, void *context) {
2004 size_t offset(reinterpret_cast<size_t>(context));
2005 CYString &name([self cyname]);
2007 size_t size(name.size());
2010 char *text(name.data());
2013 if (!isdigit(text[0]))
2017 while (size != digits && isdigit(text[digits]))
2025 if (offset == 0 && zeros != 0) {
2026 memset(data, '0', zeros);
2027 memcpy(data + zeros, text, 4 - zeros);
2029 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2030 if (size <= offset - zeros)
2033 text += offset - zeros;
2034 size -= offset - zeros;
2037 memcpy(data, text, 4);
2039 memcpy(data, text, size);
2040 memset(data + size, 0, 4 - size);
2043 for (size_t i(0); i != 4; ++i)
2044 if (isalpha(data[i]))
2052 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2054 /* XXX: ntohl may be more honest */
2055 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2058 CYString &(*PackageName)(Package *self, SEL sel);
2060 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2061 _profile(PackageNameCompare)
2062 CYString &lhi(PackageName(lhs, @selector(cyname)));
2063 CYString &rhi(PackageName(rhs, @selector(cyname)));
2064 CFStringRef lhn(lhi), rhn(rhi);
2067 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2068 else if (rhn == NULL)
2069 return NSOrderedDescending;
2071 _profile(PackageNameCompare$NumbersLast)
2072 if (!lhi.empty() && !rhi.empty()) {
2073 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2074 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2075 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2076 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2077 return lha ? NSOrderedAscending : NSOrderedDescending;
2081 CFIndex length = CFStringGetLength(lhn);
2083 _profile(PackageNameCompare$Compare)
2084 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2089 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2090 return PackageNameCompare(*lhs, *rhs, context);
2093 struct PackageNameOrdering :
2094 std::binary_function<Package *, Package *, bool>
2096 _finline bool operator ()(Package *lhs, Package *rhs) const {
2097 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2101 @implementation Package
2103 - (NSString *) description {
2104 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2109 apr_pool_destroy(pool_);
2110 if (parsed_ != NULL)
2115 + (NSString *) webScriptNameForSelector:(SEL)selector {
2117 else if (selector == @selector(clear))
2119 else if (selector == @selector(getField:))
2121 else if (selector == @selector(getRecord))
2122 return @"getRecord";
2123 else if (selector == @selector(hasTag:))
2125 else if (selector == @selector(install))
2127 else if (selector == @selector(remove))
2133 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2134 return [self webScriptNameForSelector:selector] == nil;
2137 + (NSArray *) _attributeKeys {
2138 return [NSArray arrayWithObjects:
2159 @"shortDescription",
2171 - (NSArray *) attributeKeys {
2172 return [[self class] _attributeKeys];
2175 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2176 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2179 - (NSArray *) relations {
2180 @synchronized (database_) {
2181 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2182 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2183 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2187 - (NSString *) architecture {
2189 @synchronized (database_) {
2190 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2193 - (NSString *) getField:(NSString *)name {
2194 @synchronized (database_) {
2195 if ([database_ era] != era_ || file_.end())
2198 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2200 const char *start, *end;
2201 if (!parser.Find([name UTF8String], start, end))
2202 return (NSString *) [NSNull null];
2204 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2207 - (NSString *) getRecord {
2208 @synchronized (database_) {
2209 if ([database_ era] != era_ || file_.end())
2212 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2214 const char *start, *end;
2215 parser.GetRec(start, end);
2217 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2221 if (parsed_ != NULL)
2223 @synchronized (database_) {
2224 if ([database_ era] != era_ || file_.end())
2227 ParsedPackage *parsed(new ParsedPackage);
2230 _profile(Package$parse)
2231 pkgRecords::Parser *parser;
2233 _profile(Package$parse$Lookup)
2234 parser = &[database_ records]->Lookup(file_);
2240 _profile(Package$parse$Find)
2245 {"architecture", &parsed->architecture_},
2246 {"icon", &parsed->icon_},
2247 {"depiction", &parsed->depiction_},
2248 {"homepage", &parsed->homepage_},
2249 {"website", &website},
2251 {"support", &parsed->support_},
2252 {"author", &parsed->author_},
2253 {"md5sum", &parsed->md5sum_},
2256 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2257 const char *start, *end;
2259 if (parser->Find(names[i].name_, start, end)) {
2260 CYString &value(*names[i].value_);
2261 _profile(Package$parse$Value)
2262 value.set(pool_, start, end - start);
2268 _profile(Package$parse$Tagline)
2269 const char *start, *end;
2270 if (parser->ShortDesc(start, end)) {
2271 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2274 while (stop != start && stop[-1] == '\r')
2276 parsed->tagline_.set(pool_, start, stop - start);
2280 _profile(Package$parse$Retain)
2281 if (parsed->homepage_.empty())
2282 parsed->homepage_ = website;
2283 if (parsed->homepage_ == parsed->depiction_)
2284 parsed->homepage_.clear();
2285 if (parsed->support_.empty())
2286 parsed->support_ = bugs;
2291 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2292 if ((self = [super init]) != nil) {
2293 _profile(Package$initWithVersion)
2295 apr_pool_create(&pool_, NULL);
2301 database_ = database;
2302 era_ = [database era];
2306 pkgCache::PkgIterator iterator(version.ParentPkg());
2307 iterator_ = iterator;
2309 _profile(Package$initWithVersion$Version)
2310 if (!version_.end())
2311 file_ = version_.FileList();
2313 pkgCache &cache([database_ cache]);
2314 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2318 _profile(Package$initWithVersion$Cache)
2319 name_.set(NULL, iterator.Display());
2321 latest_.set(NULL, StripVersion_(version_.VerStr()));
2323 pkgCache::VerIterator current(iterator.CurrentVer());
2325 installed_.set(NULL, StripVersion_(current.VerStr()));
2328 _profile(Package$initWithVersion$Tags)
2329 pkgCache::TagIterator tag(iterator.TagList());
2331 tags_ = [NSMutableArray arrayWithCapacity:8];
2333 goto tag; for (; !tag.end(); ++tag) tag: {
2334 const char *name(tag.Name());
2335 NSString *string((NSString *) CYStringCreate(name));
2339 [tags_ addObject:[string autorelease]];
2341 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2342 if (strcmp(name + 6, "enduser") == 0)
2344 else if (strcmp(name + 6, "hacker") == 0)
2346 else if (strcmp(name + 6, "developer") == 0)
2348 else if (strcmp(name + 6, "cydia") == 0)
2354 if (strncmp(name, "cydia::", 7) == 0) {
2355 if (strcmp(name + 7, "essential") == 0)
2357 else if (strcmp(name + 7, "obsolete") == 0)
2364 _profile(Package$initWithVersion$Metadata)
2365 const char *mixed(iterator.Name());
2366 size_t size(strlen(mixed));
2367 char lower[size + 1];
2369 for (size_t i(0); i != size; ++i)
2370 lower[i] = mixed[i] | 0x20;
2373 PackageValue *metadata(PackageFind(lower, size));
2374 metadata_ = metadata;
2376 id_.set(NULL, metadata->name_, size);
2378 const char *latest(version_.VerStr());
2379 size_t length(strlen(latest));
2381 uint16_t vhash(hashlittle(latest, length));
2383 size_t capped(std::min<size_t>(8, length));
2384 latest = latest + length - capped;
2386 if (metadata->first_ == 0)
2387 metadata->first_ = now_;
2389 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2390 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2391 metadata->vhash_ = vhash;
2392 metadata->last_ = now_;
2393 } else if (metadata->last_ == 0)
2394 metadata->last_ = metadata->first_;
2397 _profile(Package$initWithVersion$Section)
2398 section_ = version_.Section();
2401 _profile(Package$initWithVersion$Flags)
2402 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2403 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2408 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2409 pkgCache::VerIterator version;
2411 _profile(Package$packageWithIterator$GetCandidateVer)
2412 version = [database policy]->GetCandidateVer(iterator);
2420 _profile(Package$packageWithIterator$Allocate)
2421 package = [Package allocWithZone:zone];
2424 _profile(Package$packageWithIterator$Initialize)
2426 initWithVersion:version
2433 _profile(Package$packageWithIterator$Autorelease)
2434 package = [package autorelease];
2440 - (pkgCache::PkgIterator) iterator {
2444 - (NSString *) section {
2445 if (section$_ == nil) {
2446 if (section_ == NULL)
2449 _profile(Package$section$mappedSectionForPointer)
2450 section$_ = [database_ mappedSectionForPointer:section_];
2455 - (NSString *) simpleSection {
2456 if (NSString *section = [self section])
2457 return Simplify(section);
2462 - (NSString *) longSection {
2463 return LocalizeSection([self section]);
2466 - (NSString *) shortSection {
2467 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2470 - (NSString *) uri {
2473 pkgIndexFile *index;
2474 pkgCache::PkgFileIterator file(file_.File());
2475 if (![database_ list].FindIndex(file, index))
2477 return [NSString stringWithUTF8String:iterator_->Path];
2478 //return [NSString stringWithUTF8String:file.Site()];
2479 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2483 - (MIMEAddress *) maintainer {
2484 @synchronized (database_) {
2485 if ([database_ era] != era_ || file_.end())
2488 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2489 const std::string &maintainer(parser->Maintainer());
2490 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2493 - (NSString *) md5sum {
2494 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2498 @synchronized (database_) {
2499 if ([database_ era] != era_ || version_.end())
2502 return version_->InstalledSize;
2505 - (NSString *) longDescription {
2506 @synchronized (database_) {
2507 if ([database_ era] != era_ || file_.end())
2510 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2511 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2513 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2514 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2515 if ([lines count] < 2)
2518 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2519 for (size_t i(1), e([lines count]); i != e; ++i) {
2520 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2521 [trimmed addObject:trim];
2524 return [trimmed componentsJoinedByString:@"\n"];
2527 - (NSString *) shortDescription {
2528 if (parsed_ != NULL)
2529 return static_cast<NSString *>(parsed_->tagline_);
2531 @synchronized (database_) {
2532 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2534 const char *start, *end;
2535 if (!parser.ShortDesc(start, end))
2538 if (end - start > 200)
2542 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2545 while (end != start && end[-1] == '\r')
2549 return [(id) CYStringCreate(start, end - start) autorelease];
2553 _profile(Package$index)
2554 CFStringRef name((CFStringRef) [self name]);
2555 if (CFStringGetLength(name) == 0)
2557 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2558 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2560 return toupper(character);
2564 - (PackageValue *) metadata {
2569 PackageValue *metadata([self metadata]);
2570 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2573 - (bool) subscribed {
2574 return [self metadata]->subscribed_;
2577 - (bool) setSubscribed:(bool)subscribed {
2578 PackageValue *metadata([self metadata]);
2579 if (metadata->subscribed_ == subscribed)
2581 metadata->subscribed_ = subscribed;
2589 - (NSString *) latest {
2593 - (NSString *) installed {
2597 - (BOOL) uninstalled {
2598 return installed_.empty();
2602 return !version_.end();
2605 - (BOOL) upgradableAndEssential:(BOOL)essential {
2606 _profile(Package$upgradableAndEssential)
2607 pkgCache::VerIterator current(iterator_.CurrentVer());
2609 return essential && essential_;
2611 return !version_.end() && version_ != current;
2615 - (BOOL) essential {
2620 return [database_ cache][iterator_].InstBroken();
2623 - (BOOL) unfiltered {
2624 _profile(Package$unfiltered$obsolete)
2625 if (_unlikely(obsolete_))
2629 _profile(Package$unfiltered$hasSupportingRole)
2630 if (_unlikely(![self hasSupportingRole]))
2638 if (![self unfiltered])
2643 _profile(Package$visible$section)
2644 section = [self section];
2647 _profile(Package$visible$isSectionVisible)
2648 if (!isSectionVisible(section))
2656 unsigned char current(iterator_->CurrentState);
2657 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2660 - (BOOL) halfConfigured {
2661 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2664 - (BOOL) halfInstalled {
2665 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2669 @synchronized (database_) {
2670 if ([database_ era] != era_ || iterator_.end())
2673 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2674 return state.Mode != pkgDepCache::ModeKeep;
2677 - (NSString *) mode {
2678 @synchronized (database_) {
2679 if ([database_ era] != era_ || iterator_.end())
2682 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2684 switch (state.Mode) {
2685 case pkgDepCache::ModeDelete:
2686 if ((state.iFlags & pkgDepCache::Purge) != 0)
2690 case pkgDepCache::ModeKeep:
2691 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2692 return @"REINSTALL";
2693 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2697 case pkgDepCache::ModeInstall:
2698 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2699 return @"REINSTALL";
2700 else*/ switch (state.Status) {
2702 return @"DOWNGRADE";
2708 return @"NEW_INSTALL";
2719 - (NSString *) name {
2720 return name_.empty() ? id_ : name_;
2723 - (UIImage *) icon {
2724 NSString *section = [self simpleSection];
2727 if (parsed_ != NULL)
2728 if (NSString *href = parsed_->icon_)
2729 if ([href hasPrefix:@"file:///"])
2730 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2731 if (icon == nil) if (section != nil)
2732 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2733 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2734 if ([dicon hasPrefix:@"file:///"])
2735 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2737 icon = [UIImage applicationImageNamed:@"unknown.png"];
2741 - (NSString *) homepage {
2742 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2745 - (NSString *) depiction {
2746 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2749 - (MIMEAddress *) author {
2750 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2753 - (NSString *) support {
2754 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
2757 - (NSArray *) files {
2758 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2759 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2762 fin.open([path UTF8String]);
2767 while (std::getline(fin, line))
2768 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2773 - (NSString *) state {
2774 @synchronized (database_) {
2775 if ([database_ era] != era_ || file_.end())
2778 switch (iterator_->CurrentState) {
2779 case pkgCache::State::NotInstalled:
2780 return @"NotInstalled";
2781 case pkgCache::State::UnPacked:
2783 case pkgCache::State::HalfConfigured:
2784 return @"HalfConfigured";
2785 case pkgCache::State::HalfInstalled:
2786 return @"HalfInstalled";
2787 case pkgCache::State::ConfigFiles:
2788 return @"ConfigFiles";
2789 case pkgCache::State::Installed:
2790 return @"Installed";
2791 case pkgCache::State::TriggersAwaited:
2792 return @"TriggersAwaited";
2793 case pkgCache::State::TriggersPending:
2794 return @"TriggersPending";
2797 return (NSString *) [NSNull null];
2800 - (NSString *) selection {
2801 @synchronized (database_) {
2802 if ([database_ era] != era_ || file_.end())
2805 switch (iterator_->SelectedState) {
2806 case pkgCache::State::Unknown:
2808 case pkgCache::State::Install:
2810 case pkgCache::State::Hold:
2812 case pkgCache::State::DeInstall:
2813 return @"DeInstall";
2814 case pkgCache::State::Purge:
2818 return (NSString *) [NSNull null];
2821 - (NSArray *) warnings {
2822 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2823 const char *name(iterator_.Name());
2825 size_t length(strlen(name));
2826 if (length < 2) invalid:
2827 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2828 else for (size_t i(0); i != length; ++i)
2830 /* XXX: technically this is not allowed */
2831 (name[i] < 'A' || name[i] > 'Z') &&
2832 (name[i] < 'a' || name[i] > 'z') &&
2833 (name[i] < '0' || name[i] > '9') &&
2834 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2837 if (strcmp(name, "cydia") != 0) {
2840 bool _private = false;
2843 bool repository = [[self section] isEqualToString:@"Repositories"];
2845 if (NSArray *files = [self files])
2846 for (NSString *file in files)
2847 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2849 else if (!user && [file isEqualToString:@"/User"])
2851 else if (!_private && [file isEqualToString:@"/private"])
2853 else if (!stash && [file isEqualToString:@"/var/stash"])
2856 /* XXX: this is not sensitive enough. only some folders are valid. */
2857 if (cydia && !repository)
2858 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2860 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2862 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2864 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2867 return [warnings count] == 0 ? nil : warnings;
2870 - (NSArray *) applications {
2871 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2873 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2875 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2876 if (NSArray *files = [self files])
2877 for (NSString *file in files)
2878 if (application_r(file)) {
2879 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2880 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2881 if ([id isEqualToString:me])
2884 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2886 display = application_r[1];
2888 NSString *bundle([file stringByDeletingLastPathComponent]);
2889 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2890 // XXX: maybe this should check if this is really a string, not just for length
2891 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
2893 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2895 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2896 [applications addObject:application];
2898 [application addObject:id];
2899 [application addObject:display];
2900 [application addObject:url];
2903 return [applications count] == 0 ? nil : applications;
2906 - (Source *) source {
2907 if (source_ == nil) {
2908 @synchronized (database_) {
2909 if ([database_ era] != era_ || file_.end())
2910 source_ = (Source *) [NSNull null];
2912 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2916 return source_ == (Source *) [NSNull null] ? nil : source_;
2923 - (BOOL) matches:(NSArray *)query {
2924 if (query == nil || [query count] == 0)
2933 string = [self name];
2934 length = [string length];
2936 for (NSString *term in query) {
2937 range = [string rangeOfString:term options:MatchCompareOptions_];
2938 if (range.location != NSNotFound)
2939 rank_ -= 6 * 1000000 / length;
2944 length = [string length];
2946 for (NSString *term in query) {
2947 range = [string rangeOfString:term options:MatchCompareOptions_];
2948 if (range.location != NSNotFound)
2949 rank_ -= 6 * 1000000 / length;
2953 string = [self shortDescription];
2954 length = [string length];
2955 NSUInteger stop(std::min<NSUInteger>(length, 200));
2957 for (NSString *term in query) {
2958 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2959 if (range.location != NSNotFound)
2960 rank_ -= 2 * 100000;
2966 - (bool) hasSupportingRole {
2971 if ([Role_ isEqualToString:@"User"])
2975 if ([Role_ isEqualToString:@"Hacker"])
2979 if ([Role_ isEqualToString:@"Developer"])
2984 - (NSArray *) tags {
2988 - (BOOL) hasTag:(NSString *)tag {
2989 return tags_ == nil ? NO : [tags_ containsObject:tag];
2992 - (NSString *) primaryPurpose {
2993 for (NSString *tag in (NSArray *) tags_)
2994 if ([tag hasPrefix:@"purpose::"])
2995 return [tag substringFromIndex:9];
2999 - (NSArray *) purposes {
3000 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3001 for (NSString *tag in (NSArray *) tags_)
3002 if ([tag hasPrefix:@"purpose::"])
3003 [purposes addObject:[tag substringFromIndex:9]];
3004 return [purposes count] == 0 ? nil : purposes;
3007 - (bool) isCommercial {
3008 return [self hasTag:@"cydia::commercial"];
3011 - (void) setIndex:(size_t)index {
3012 if (metadata_->index_ != index)
3013 metadata_->index_ = index;
3016 - (CYString &) cyname {
3017 return name_.empty() ? id_ : name_;
3020 - (uint32_t) compareBySection:(NSArray *)sections {
3021 NSString *section([self section]);
3022 for (size_t i(0), e([sections count]); i != e; ++i) {
3023 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3027 return _not(uint32_t);
3031 @synchronized (database_) {
3032 pkgProblemResolver *resolver = [database_ resolver];
3033 resolver->Clear(iterator_);
3035 pkgCacheFile &cache([database_ cache]);
3036 cache->SetReInstall(iterator_, false);
3037 cache->MarkKeep(iterator_, false);
3041 @synchronized (database_) {
3042 pkgProblemResolver *resolver = [database_ resolver];
3043 resolver->Clear(iterator_);
3044 resolver->Protect(iterator_);
3046 pkgCacheFile &cache([database_ cache]);
3047 cache->SetReInstall(iterator_, false);
3048 cache->MarkInstall(iterator_, false);
3050 pkgDepCache::StateCache &state((*cache)[iterator_]);
3051 if (!state.Install())
3052 cache->SetReInstall(iterator_, true);
3056 @synchronized (database_) {
3057 pkgProblemResolver *resolver = [database_ resolver];
3058 resolver->Clear(iterator_);
3059 resolver->Remove(iterator_);
3060 resolver->Protect(iterator_);
3062 pkgCacheFile &cache([database_ cache]);
3063 cache->SetReInstall(iterator_, false);
3064 cache->MarkDelete(iterator_, true);
3067 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3068 _profile(Package$isUnfilteredAndSearchedForBy)
3071 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3072 value &= [self unfiltered];
3075 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3076 value &= [self matches:query];
3083 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3084 if ([search length] == 0)
3087 _profile(Package$isUnfilteredAndSelectedForBy)
3090 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3091 value &= [self unfiltered];
3094 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3095 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3102 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3103 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3106 - (bool) isVisibleInSection:(NSString *)name {
3107 NSString *section([self section]);
3111 section == nil && [name length] == 0 ||
3112 [name isEqualToString:section]
3113 ) && [self visible];
3116 - (bool) isVisibleInSource:(Source *)source {
3117 return [self source] == source && [self visible];
3122 /* Section Class {{{ */
3123 @interface Section : NSObject {
3128 _H<NSString> localized_;
3131 - (NSComparisonResult) compareByLocalized:(Section *)section;
3132 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3133 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3134 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3135 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3136 - (NSString *) name;
3143 - (void) addToCount;
3145 - (void) setCount:(size_t)count;
3146 - (NSString *) localized;
3150 @implementation Section
3152 - (NSComparisonResult) compareByLocalized:(Section *)section {
3153 NSString *lhs(localized_);
3154 NSString *rhs([section localized]);
3156 /*if ([lhs length] != 0 && [rhs length] != 0) {
3157 unichar lhc = [lhs characterAtIndex:0];
3158 unichar rhc = [rhs characterAtIndex:0];
3160 if (isalpha(lhc) && !isalpha(rhc))
3161 return NSOrderedAscending;
3162 else if (!isalpha(lhc) && isalpha(rhc))
3163 return NSOrderedDescending;
3166 return [lhs compare:rhs options:LaxCompareOptions_];
3169 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3170 if ((self = [self initWithName:name localize:NO]) != nil) {
3171 if (localized != nil)
3172 localized_ = localized;
3176 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3177 return [self initWithName:name row:0 localize:localize];
3180 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3181 if ((self = [super init]) != nil) {
3186 localized_ = LocalizeSection(name_);
3190 /* XXX: localize the index thingees */
3191 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3192 if ((self = [super init]) != nil) {
3193 name_ = [NSString stringWithCharacters:&index length:1];
3199 - (NSString *) name {
3219 - (void) addToCount {
3223 - (void) setCount:(size_t)count {
3227 - (NSString *) localized {
3234 class CydiaLogCleaner :
3235 public pkgArchiveCleaner
3238 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3243 /* Database Implementation {{{ */
3244 @implementation Database
3246 + (Database *) sharedInstance {
3247 static _H<Database> instance;
3248 if (instance == nil)
3249 instance = [[[Database alloc] init] autorelease];
3257 - (void) releasePackages {
3258 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3259 CFArrayRemoveAllValues(packages_);
3263 // XXX: actually implement this thing
3265 [self releasePackages];
3266 apr_pool_destroy(pool_);
3267 NSRecycleZone(zone_);
3271 - (void) _readCydia:(NSNumber *)fd {
3272 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3273 std::istream is(&ib);
3276 static Pcre finish_r("^finish:([^:]*)$");
3278 while (std::getline(is, line)) {
3279 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3281 const char *data(line.c_str());
3282 size_t size = line.size();
3283 lprintf("C:%s\n", data);
3285 if (finish_r(data, size)) {
3286 NSString *finish = finish_r[1];
3287 int index = [Finishes_ indexOfObject:finish];
3288 if (index != INT_MAX && index > Finish_)
3298 - (void) _readStatus:(NSNumber *)fd {
3299 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3300 std::istream is(&ib);
3303 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3304 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3306 while (std::getline(is, line)) {
3307 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3309 const char *data(line.c_str());
3310 size_t size(line.size());
3311 lprintf("S:%s\n", data);
3313 if (conffile_r(data, size)) {
3314 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3315 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3316 } else if (strncmp(data, "status: ", 8) == 0) {
3317 // status: <package>: {unpacked,half-configured,installed}
3318 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3319 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3320 } else if (strncmp(data, "processing: ", 12) == 0) {
3321 // processing: configure: config-test
3322 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3323 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3324 } else if (pmstatus_r(data, size)) {
3325 std::string type([pmstatus_r[1] UTF8String]);
3327 NSString *package = pmstatus_r[2];
3328 if ([package isEqualToString:@"dpkg-exec"])
3331 float percent([pmstatus_r[3] floatValue]);
3332 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3334 NSString *string = pmstatus_r[4];
3336 if (type == "pmerror") {
3337 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3338 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3339 } else if (type == "pmstatus") {
3340 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3341 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3342 } else if (type == "pmconffile")
3343 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3345 lprintf("E:unknown pmstatus\n");
3347 lprintf("E:unknown status\n");
3355 - (void) _readOutput:(NSNumber *)fd {
3356 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3357 std::istream is(&ib);
3360 while (std::getline(is, line)) {
3361 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3363 lprintf("O:%s\n", line.c_str());
3365 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3366 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3378 - (Package *) packageWithName:(NSString *)name {
3381 @synchronized (self) {
3382 if (static_cast<pkgDepCache *>(cache_) == NULL)
3384 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3385 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3389 if ((self = [super init]) != nil) {
3396 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3397 apr_pool_create(&pool_, NULL);
3399 size_t capacity(MetaFile_->active_);
3405 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3406 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3410 _assert(pipe(fds) != -1);
3413 _config->Set("APT::Keep-Fds::", cydiafd_);
3414 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3417 detachNewThreadSelector:@selector(_readCydia:)
3419 withObject:[NSNumber numberWithInt:fds[0]]
3422 _assert(pipe(fds) != -1);
3426 detachNewThreadSelector:@selector(_readStatus:)
3428 withObject:[NSNumber numberWithInt:fds[0]]
3431 _assert(pipe(fds) != -1);
3432 _assert(dup2(fds[0], 0) != -1);
3433 _assert(close(fds[0]) != -1);
3435 input_ = fdopen(fds[1], "a");
3437 _assert(pipe(fds) != -1);
3438 _assert(dup2(fds[1], 1) != -1);
3439 _assert(close(fds[1]) != -1);
3442 detachNewThreadSelector:@selector(_readOutput:)
3444 withObject:[NSNumber numberWithInt:fds[0]]
3449 - (pkgCacheFile &) cache {
3453 - (pkgDepCache::Policy *) policy {
3457 - (pkgRecords *) records {
3461 - (pkgProblemResolver *) resolver {
3465 - (pkgAcquire &) fetcher {
3469 - (pkgSourceList &) list {
3473 - (NSArray *) packages {
3474 return (NSArray *) packages_;
3477 - (NSArray *) sources {
3481 - (Source *) sourceWithKey:(NSString *)key {
3482 for (Source *source in [self sources]) {
3483 if ([[source key] isEqualToString:key])
3488 - (bool) popErrorWithTitle:(NSString *)title {
3491 while (!_error->empty()) {
3493 bool warning(!_error->PopMessage(error));
3498 size_t size(error.size());
3499 if (size == 0 || error[size - 1] != '\n')
3501 error.resize(size - 1);
3504 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3506 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3507 if (warning && no_pubkey(error.c_str()))
3510 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3516 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3517 return [self popErrorWithTitle:title] || !success;
3520 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3521 @synchronized (self) {
3524 [self releasePackages];
3527 [sourceList_ removeAllObjects];
3547 apr_pool_clear(pool_);
3549 NSRecycleZone(zone_);
3550 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3552 int chk(creat("/tmp/cydia.chk", 0644));
3556 if (invocation != nil)
3557 [invocation invoke];
3559 NSString *title(UCLocalize("DATABASE"));
3561 list_ = new pkgSourceList();
3562 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3565 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3566 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3567 [sourceList_ addObject:object];
3571 OpProgress progress;
3573 if (!cache_.Open(progress, true)) {
3574 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3575 while (!_error->empty()) {
3577 bool warning(!_error->PopMessage(error));
3579 lprintf("cache_.Open():[%s]\n", error.c_str());
3581 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3585 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3586 repair = @selector(configure);
3587 //else if (error == "The package lists or status file could not be parsed or opened.")
3588 // repair = @selector(update);
3589 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3590 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3591 // else if (error == "Malformed Status line")
3592 // else if (error == "The list of sources could not be read.")
3594 if (repair != NULL) {
3596 [delegate_ repairWithSelector:repair];
3605 unlink("/tmp/cydia.chk");
3607 now_ = [[NSDate date] timeIntervalSince1970];
3609 policy_ = new pkgDepCache::Policy();
3610 records_ = new pkgRecords(cache_);
3611 resolver_ = new pkgProblemResolver(cache_);
3612 fetcher_ = new pkgAcquire(&status_);
3615 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3616 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3620 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3623 if (cache_->BrokenCount() != 0) {
3624 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3627 if (cache_->BrokenCount() != 0) {
3628 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3632 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3636 for (Source *object in (id) sourceList_) {
3637 metaIndex *source([object metaIndex]);
3638 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3639 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3640 // XXX: this could be more intelligent
3641 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3642 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3644 sourceMap_[cached->ID] = object;
3649 /*std::vector<Package *> packages;
3650 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3655 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3656 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3657 //packages.push_back(package);
3658 CFArrayAppendValue(packages_, CFRetain(package));
3662 /*if (packages.empty())
3663 packages_ = [[NSArray alloc] init];
3665 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3668 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3669 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3670 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3678 /*if (!packages.empty())
3679 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3680 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3682 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3684 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3686 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3690 size_t count(CFArrayGetCount(packages_));
3691 MetaFile_->active_ = count;
3693 for (size_t index(0); index != count; ++index)
3694 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3701 @synchronized (self) {
3703 resolver_ = new pkgProblemResolver(cache_);
3705 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3706 if (!cache_[iterator].Keep())
3707 cache_->MarkKeep(iterator, false);
3708 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3709 cache_->SetReInstall(iterator, false);
3712 - (void) configure {
3713 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3715 system([dpkg UTF8String]);
3720 @synchronized (self) {
3721 // XXX: I don't remember this condition
3726 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3728 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3730 if ([self popErrorWithTitle:title])
3734 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3736 CydiaLogCleaner cleaner;
3737 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3744 fetcher_->Shutdown();
3746 pkgRecords records(cache_);
3748 lock_ = new FileFd();
3749 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3751 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3753 if ([self popErrorWithTitle:title])
3757 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3760 manager_ = (_system->CreatePM(cache_));
3761 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3768 bool substrate(RestartSubstrate_);
3769 RestartSubstrate_ = false;
3771 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3773 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3775 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3777 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3778 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3781 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3783 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3785 [self popErrorWithTitle:title];
3789 bool failed = false;
3790 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3791 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3793 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3796 std::string uri = (*item)->DescURI();
3797 std::string error = (*item)->ErrorText;
3799 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3802 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3803 [delegate_ addProgressEventOnMainThread:event forTask:title];
3806 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3814 RestartSubstrate_ = true;
3817 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3818 if ([self popErrorWithTitle:title])
3821 if (result == pkgPackageManager::Failed) {
3826 if (result != pkgPackageManager::Completed) {
3831 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3833 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3835 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3836 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3839 if (![before isEqualToArray:after])
3844 NSString *title(UCLocalize("UPGRADE"));
3845 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3851 [self updateWithStatus:status_];
3854 - (void) updateWithStatus:(Status &)status {
3855 NSString *title(UCLocalize("REFRESHING_DATA"));
3858 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3862 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3863 if ([self popErrorWithTitle:title])
3866 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3868 bool success(ListUpdate(status, list, PulseInterval_));
3869 if (status.WasCancelled())
3872 [self popErrorWithTitle:title forOperation:success];
3873 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3877 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3880 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3881 delegate_ = delegate;
3884 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3885 progress_ = delegate;
3886 status_.setDelegate(delegate);
3889 - (NSObject<ProgressDelegate> *) progressDelegate {
3893 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3894 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3895 return i == sourceMap_.end() ? nil : i->second;
3898 - (NSString *) mappedSectionForPointer:(const char *)section {
3899 _H<NSString> *mapped;
3901 _profile(Database$mappedSectionForPointer$Cache)
3902 mapped = §ions_[section];
3905 if (*mapped == NULL) {
3906 size_t length(strlen(section));
3907 char spaced[length + 1];
3909 _profile(Database$mappedSectionForPointer$Replace)
3910 for (size_t index(0); index != length; ++index)
3911 spaced[index] = section[index] == '_' ? ' ' : section[index];
3912 spaced[length] = '\0';
3917 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3918 string = [NSString stringWithUTF8String:spaced];
3921 _profile(Database$mappedSectionForPointer$Map)
3922 string = [SectionMap_ objectForKey:string] ?: string;
3932 static _H<NSMutableSet> Diversions_;
3934 @interface Diversion : NSObject {
3937 _H<NSString> format_;
3942 @implementation Diversion
3944 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3945 if ((self = [super init]) != nil) {
3946 pattern_ = [from UTF8String];
3952 - (NSString *) divert:(NSString *)url {
3953 return !pattern_(url) ? nil : pattern_->*format_;
3956 + (NSURL *) divertURL:(NSURL *)url {
3958 NSString *href([url absoluteString]);
3960 for (Diversion *diversion in (id) Diversions_)
3961 if (NSString *diverted = [diversion divert:href]) {
3963 NSLog(@"div: %@", diverted);
3965 url = [NSURL URLWithString:diverted];
3972 - (NSString *) key {
3976 - (NSUInteger) hash {
3980 - (BOOL) isEqual:(Diversion *)object {
3981 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3986 @interface CydiaObject : NSObject {
3987 _H<CyteWebViewController> indirect_;
3988 _transient id delegate_;
3991 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3997 @interface CydiaWebViewController : CyteWebViewController {
3998 _H<CydiaObject> cydia_;
4001 + (void) addDiversion:(Diversion *)diversion;
4002 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4003 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4004 - (void) setDelegate:(id)delegate;
4008 /* Web Scripting {{{ */
4009 @implementation CydiaObject
4011 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4012 if ((self = [super init]) != nil) {
4013 indirect_ = (CyteWebViewController *) indirect;
4017 - (void) setDelegate:(id)delegate {
4018 delegate_ = delegate;
4021 + (NSArray *) _attributeKeys {
4022 return [NSArray arrayWithObjects:
4025 @"coreFoundationVersionNumber",
4042 - (NSArray *) attributeKeys {
4043 return [[self class] _attributeKeys];
4046 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4047 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4050 - (NSString *) version {
4054 - (NSString *) build {
4058 - (NSString *) coreFoundationVersionNumber {
4059 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4062 - (NSString *) device {
4063 return UniqueIdentifier();
4066 - (NSString *) firmware {
4067 return [[UIDevice currentDevice] systemVersion];
4070 - (NSString *) hostname {
4071 return [[UIDevice currentDevice] name];
4074 - (NSString *) idiom {
4075 return (id) Idiom_ ?: [NSNull null];
4078 - (NSString *) mcc {
4079 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4080 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4084 - (NSString *) mnc {
4085 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4086 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4090 - (NSString *) operator {
4091 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4092 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4096 - (NSString *) bbsnum {
4097 return (id) BBSNum_ ?: [NSNull null];
4100 - (NSString *) ecid {
4101 return (id) ChipID_ ?: [NSNull null];
4104 - (NSString *) serial {
4105 return SerialNumber_;
4108 - (NSString *) role {
4109 return (id) Role_ ?: [NSNull null];
4112 - (NSString *) model {
4113 return [NSString stringWithUTF8String:Machine_];
4116 - (NSString *) token {
4117 return (id) Token_ ?: [NSNull null];
4120 + (NSString *) webScriptNameForSelector:(SEL)selector {
4122 else if (selector == @selector(addBridgedHost:))
4123 return @"addBridgedHost";
4124 else if (selector == @selector(addInsecureHost:))
4125 return @"addInsecureHost";
4126 else if (selector == @selector(addInternalRedirect::))
4127 return @"addInternalRedirect";
4128 else if (selector == @selector(addPipelinedHost:scheme:))
4129 return @"addPipelinedHost";
4130 else if (selector == @selector(addSource:::))
4131 return @"addSource";
4132 else if (selector == @selector(addTokenHost:))
4133 return @"addTokenHost";
4134 else if (selector == @selector(addTrivialSource:))
4135 return @"addTrivialSource";
4136 else if (selector == @selector(close))
4138 else if (selector == @selector(du:))
4140 else if (selector == @selector(stringWithFormat:arguments:))
4142 else if (selector == @selector(getAllSources))
4143 return @"getAllSources";
4144 else if (selector == @selector(getApplicationInfo:value:))
4145 return @"getApplicationInfoValue";
4146 else if (selector == @selector(getKernelNumber:))
4147 return @"getKernelNumber";
4148 else if (selector == @selector(getKernelString:))
4149 return @"getKernelString";
4150 else if (selector == @selector(getInstalledPackages))
4151 return @"getInstalledPackages";
4152 else if (selector == @selector(getIORegistryEntry::))
4153 return @"getIORegistryEntry";
4154 else if (selector == @selector(getLocaleIdentifier))
4155 return @"getLocaleIdentifier";
4156 else if (selector == @selector(getPreferredLanguages))
4157 return @"getPreferredLanguages";
4158 else if (selector == @selector(getPackageById:))
4159 return @"getPackageById";
4160 else if (selector == @selector(getMetadataKeys))
4161 return @"getMetadataKeys";
4162 else if (selector == @selector(getMetadataValue:))
4163 return @"getMetadataValue";
4164 else if (selector == @selector(getSessionValue:))
4165 return @"getSessionValue";
4166 else if (selector == @selector(installPackages:))
4167 return @"installPackages";
4168 else if (selector == @selector(isReachable:))
4169 return @"isReachable";
4170 else if (selector == @selector(localizedStringForKey:value:table:))
4172 else if (selector == @selector(popViewController:))
4173 return @"popViewController";
4174 else if (selector == @selector(refreshSources))
4175 return @"refreshSources";
4176 else if (selector == @selector(registerFrame:))
4177 return @"registerFrame";
4178 else if (selector == @selector(removeButton))
4179 return @"removeButton";
4180 else if (selector == @selector(saveConfig))
4181 return @"saveConfig";
4182 else if (selector == @selector(setMetadataValue::))
4183 return @"setMetadataValue";
4184 else if (selector == @selector(setSessionValue::))
4185 return @"setSessionValue";
4186 else if (selector == @selector(setShowPromoted:))
4187 return @"setShowPromoted";
4188 else if (selector == @selector(substitutePackageNames:))
4189 return @"substitutePackageNames";
4190 else if (selector == @selector(scrollToBottom:))
4191 return @"scrollToBottom";
4192 else if (selector == @selector(setAllowsNavigationAction:))
4193 return @"setAllowsNavigationAction";
4194 else if (selector == @selector(setBadgeValue:))
4195 return @"setBadgeValue";
4196 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4197 return @"setButtonImage";
4198 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4199 return @"setButtonTitle";
4200 else if (selector == @selector(setHidesBackButton:))
4201 return @"setHidesBackButton";
4202 else if (selector == @selector(setHidesNavigationBar:))
4203 return @"setHidesNavigationBar";
4204 else if (selector == @selector(setNavigationBarStyle:))
4205 return @"setNavigationBarStyle";
4206 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4207 return @"setNavigationBarTintColor";
4208 else if (selector == @selector(setPasteboardString:))
4209 return @"setPasteboardString";
4210 else if (selector == @selector(setPasteboardURL:))
4211 return @"setPasteboardURL";
4212 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4213 return @"setScrollAlwaysBounceVertical";
4214 else if (selector == @selector(setScrollIndicatorStyle:))
4215 return @"setScrollIndicatorStyle";
4216 else if (selector == @selector(setToken:))
4218 else if (selector == @selector(setViewportWidth:))
4219 return @"setViewportWidth";
4220 else if (selector == @selector(statfs:))
4222 else if (selector == @selector(supports:))
4224 else if (selector == @selector(unload))
4230 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4231 return [self webScriptNameForSelector:selector] == nil;
4234 - (BOOL) supports:(NSString *)feature {
4235 return [feature isEqualToString:@"window.open"];
4239 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4242 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4243 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4246 - (void) setScrollIndicatorStyle:(NSString *)style {
4247 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4250 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4251 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4254 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4256 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4257 return (id) [NSNull null];
4258 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4260 return (id) [NSNull null];
4261 return [info objectForKey:key];
4264 - (NSNumber *) getKernelNumber:(NSString *)name {
4265 const char *string([name UTF8String]);
4268 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4269 return (id) [NSNull null];
4271 if (size != sizeof(int))
4272 return (id) [NSNull null];
4275 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4276 return (id) [NSNull null];
4278 return [NSNumber numberWithInt:value];
4281 - (NSString *) getKernelString:(NSString *)name {
4282 const char *string([name UTF8String]);
4285 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4286 return (id) [NSNull null];
4288 char value[size + 1];
4289 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4290 return (id) [NSNull null];
4292 // XXX: just in case you request something ludicrous
4295 return [NSString stringWithCString:value];
4298 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4299 NSObject *value(CYIOGetValue([path UTF8String], entry));
4302 if ([value isKindOfClass:[NSData class]])
4303 value = CYHex((NSData *) value);
4308 - (NSArray *) getMetadataKeys {
4309 @synchronized (Values_) {
4310 return [Values_ allKeys];
4313 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4314 WebFrame *frame([iframe contentFrame]);
4315 [indirect_ registerFrame:frame];
4318 - (void) _setShowPromoted:(NSNumber *)value {
4319 [Metadata_ setObject:value forKey:@"ShowPromoted"];
4323 - (void) setShowPromoted:(NSNumber *)value {
4324 [self performSelectorOnMainThread:@selector(_setShowPromoted:) withObject:value waitUntilDone:NO];
4327 - (id) getMetadataValue:(NSString *)key {
4328 @synchronized (Values_) {
4329 return [Values_ objectForKey:key];
4332 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4333 @synchronized (Values_) {
4334 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4335 [Values_ removeObjectForKey:key];
4337 [Values_ setObject:value forKey:key];
4339 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4342 - (id) getSessionValue:(NSString *)key {
4343 @synchronized (SessionData_) {
4344 return [SessionData_ objectForKey:key];
4347 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4348 @synchronized (SessionData_) {
4349 if (value == (id) [WebUndefined undefined])
4350 [SessionData_ removeObjectForKey:key];
4352 [SessionData_ setObject:value forKey:key];
4355 - (void) addBridgedHost:(NSString *)host {
4356 @synchronized (HostConfig_) {
4357 [BridgedHosts_ addObject:host];
4360 - (void) addInsecureHost:(NSString *)host {
4361 @synchronized (HostConfig_) {
4362 [InsecureHosts_ addObject:host];
4365 - (void) addTokenHost:(NSString *)host {
4366 @synchronized (HostConfig_) {
4367 [TokenHosts_ addObject:host];
4370 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4371 @synchronized (HostConfig_) {
4372 if (scheme != (id) [WebUndefined undefined])
4373 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4375 [PipelinedHosts_ addObject:host];
4378 - (void) popViewController:(NSNumber *)value {
4379 if (value == (id) [WebUndefined undefined])
4380 value = [NSNumber numberWithBool:YES];
4381 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4384 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4385 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4387 for (NSString *section in sections)
4388 [array addObject:section];
4390 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4393 distribution, @"Distribution",
4395 nil] waitUntilDone:NO];
4398 - (void) addTrivialSource:(NSString *)href {
4399 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4402 - (void) refreshSources {
4403 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4406 - (void) saveConfig {
4407 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4410 - (NSArray *) getAllSources {
4411 return [[Database sharedInstance] sources];
4414 - (NSArray *) getInstalledPackages {
4415 Database *database([Database sharedInstance]);
4416 @synchronized (database) {
4417 NSArray *packages([database packages]);
4418 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4419 for (Package *package in packages)
4420 if (![package uninstalled])
4421 [installed addObject:package];
4425 - (Package *) getPackageById:(NSString *)id {
4426 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4430 return (Package *) [NSNull null];
4433 - (NSString *) getLocaleIdentifier {
4434 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4437 - (NSArray *) getPreferredLanguages {
4441 - (NSArray *) statfs:(NSString *)path {
4444 if (path == nil || statfs([path UTF8String], &stat) == -1)
4447 return [NSArray arrayWithObjects:
4448 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4449 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4450 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4454 - (NSNumber *) du:(NSString *)path {
4455 NSNumber *value(nil);
4458 _assert(pipe(fds) != -1);
4460 pid_t pid(ExecFork());
4462 _assert(dup2(fds[1], 1) != -1);
4463 _assert(close(fds[0]) != -1);
4464 _assert(close(fds[1]) != -1);
4465 /* XXX: this should probably not use du */
4466 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4471 _assert(close(fds[1]) != -1);
4473 if (FILE *du = fdopen(fds[0], "r")) {
4475 while (fgets(line, sizeof(line), du) != NULL) {
4476 size_t length(strlen(line));
4477 while (length != 0 && line[length - 1] == '\n')
4478 line[--length] = '\0';
4479 if (char *tab = strchr(line, '\t')) {
4481 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4486 } else _assert(close(fds[0]));
4494 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4497 - (NSNumber *) isReachable:(NSString *)name {
4498 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4501 - (void) installPackages:(NSArray *)packages {
4502 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4505 - (NSString *) substitutePackageNames:(NSString *)message {
4506 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4507 for (size_t i(0), e([words count]); i != e; ++i) {
4508 NSString *word([words objectAtIndex:i]);
4509 if (Package *package = [[Database sharedInstance] packageWithName:word])
4510 [words replaceObjectAtIndex:i withObject:[package name]];
4513 return [words componentsJoinedByString:@" "];
4516 - (void) removeButton {
4517 [indirect_ removeButton];
4520 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4521 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4524 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4525 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4528 - (void) setBadgeValue:(id)value {
4529 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4532 - (void) setAllowsNavigationAction:(NSString *)value {
4533 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4536 - (void) setHidesBackButton:(NSString *)value {
4537 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4540 - (void) setHidesNavigationBar:(NSString *)value {
4541 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4544 - (void) setNavigationBarStyle:(NSString *)value {
4545 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4548 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4549 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4550 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4551 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4554 - (void) setPasteboardString:(NSString *)value {
4555 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4558 - (void) setPasteboardURL:(NSString *)value {
4559 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4562 - (void) _setToken:(NSString *)token {
4566 [Metadata_ removeObjectForKey:@"Token"];
4568 [Metadata_ setObject:Token_ forKey:@"Token"];
4573 - (void) setToken:(NSString *)token {
4574 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4577 - (void) scrollToBottom:(NSNumber *)animated {
4578 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4581 - (void) setViewportWidth:(float)width {
4582 [indirect_ setViewportWidthOnMainThread:width];
4585 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4586 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4587 unsigned count([arguments count]);
4589 for (unsigned i(0); i != count; ++i)
4590 values[i] = [arguments objectAtIndex:i];
4591 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4594 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4595 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4597 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4599 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4605 @interface NSURL (CydiaSecure)
4608 @implementation NSURL (CydiaSecure)
4610 - (bool) isCydiaSecure {
4611 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4614 @synchronized (HostConfig_) {
4615 if ([InsecureHosts_ containsObject:[self host]])
4624 /* Cydia Browser Controller {{{ */
4625 @implementation CydiaWebViewController
4627 - (NSURL *) navigationURL {
4628 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4631 + (void) _initialize {
4632 [super _initialize];
4634 Diversions_ = [NSMutableSet setWithCapacity:0];
4637 + (void) addDiversion:(Diversion *)diversion {
4638 [Diversions_ addObject:diversion];
4641 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4642 [super webView:view didClearWindowObject:window forFrame:frame];
4643 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4646 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4647 WebDataSource *source([frame dataSource]);
4648 NSURLResponse *response([source response]);
4649 NSURL *url([response URL]);
4650 NSString *scheme([[url scheme] lowercaseString]);
4652 bool bridged(false);
4654 @synchronized (HostConfig_) {
4655 if ([scheme isEqualToString:@"file"])
4657 else if ([scheme isEqualToString:@"https"])
4658 if ([BridgedHosts_ containsObject:[url host]])
4663 [window setValue:cydia forKey:@"cydia"];
4666 - (void) _setupMail:(MFMailComposeViewController *)controller {
4667 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4669 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4670 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4673 - (NSURL *) URLWithURL:(NSURL *)url {
4674 return [Diversion divertURL:url];
4677 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4678 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4681 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4682 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4684 NSURL *url([copy URL]);
4685 NSString *href([url absoluteString]);
4686 NSString *host([url host]);
4688 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4689 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4690 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4691 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4694 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4695 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4697 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4701 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4702 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4703 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4704 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4709 @synchronized (HostConfig_) {
4710 bridged = [BridgedHosts_ containsObject:host];
4711 token = [TokenHosts_ containsObject:host];
4714 if ([url isCydiaSecure]) {
4716 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4717 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4719 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4720 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4727 - (void) setDelegate:(id)delegate {
4728 [super setDelegate:delegate];
4729 [cydia_ setDelegate:delegate];
4732 - (NSString *) applicationNameForUserAgent {
4737 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4738 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4744 @interface AppCacheController : CydiaWebViewController {
4749 @implementation AppCacheController
4751 - (void) didReceiveMemoryWarning {
4752 // XXX: this doesn't work
4755 - (bool) retainsNetworkActivityIndicator {
4763 @interface NSObject (CydiaScript)
4764 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4767 @implementation NSObject (CydiaScript)
4769 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4775 @implementation NSArray (CydiaScript)
4777 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4778 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4779 for (size_t i(0), e([self count]); i != e; ++i)
4780 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4786 @implementation NSDictionary (CydiaScript)
4788 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4789 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4791 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4798 /* Confirmation Controller {{{ */
4799 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4800 if (!iterator.end())
4801 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4802 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4804 pkgCache::PkgIterator package(dep.TargetPkg());
4807 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4814 @protocol ConfirmationControllerDelegate
4815 - (void) cancelAndClear:(bool)clear;
4816 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4820 @interface ConfirmationController : CydiaWebViewController {
4821 _transient Database *database_;
4823 _H<UIAlertView> essential_;
4825 _H<NSDictionary> changes_;
4826 _H<NSMutableArray> issues_;
4827 _H<NSDictionary> sizes_;
4832 - (id) initWithDatabase:(Database *)database;
4836 @implementation ConfirmationController
4840 RestartSubstrate_ = true;
4841 [delegate_ confirmWithNavigationController:[self navigationController]];
4844 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4845 NSString *context([alert context]);
4847 if ([context isEqualToString:@"remove"]) {
4848 if (button == [alert cancelButtonIndex])
4849 [self dismissModalViewControllerAnimated:YES];
4850 else if (button == [alert firstOtherButtonIndex]) {
4851 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
4854 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4855 } else if ([context isEqualToString:@"unable"]) {
4856 [self dismissModalViewControllerAnimated:YES];
4857 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4859 [super alertView:alert clickedButtonAtIndex:button];
4863 - (void) _doContinue {
4864 [delegate_ cancelAndClear:NO];
4865 [self dismissModalViewControllerAnimated:YES];
4868 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4869 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4873 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4874 [super webView:view didClearWindowObject:window forFrame:frame];
4876 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4877 (id) changes_, @"changes",
4878 (id) issues_, @"issues",
4879 (id) sizes_, @"sizes",
4881 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4884 - (id) initWithDatabase:(Database *)database {
4885 if ((self = [super init]) != nil) {
4886 database_ = database;
4888 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4889 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4890 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4891 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4892 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4896 pkgCacheFile &cache([database_ cache]);
4897 NSArray *packages([database_ packages]);
4898 pkgDepCache::Policy *policy([database_ policy]);
4900 issues_ = [NSMutableArray arrayWithCapacity:4];
4902 for (Package *package in packages) {
4903 pkgCache::PkgIterator iterator([package iterator]);
4904 NSString *name([package id]);
4906 if ([package broken]) {
4907 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4909 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4911 reasons, @"reasons",
4914 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4918 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4919 pkgCache::DepIterator start;
4920 pkgCache::DepIterator end;
4921 dep.GlobOr(start, end); // ++dep
4923 if (!cache->IsImportantDep(end))
4925 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4928 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4930 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4931 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4932 clauses, @"clauses",
4936 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4938 pkgCache::PkgIterator target(start.TargetPkg());
4939 if (target->ProvidesList != 0)
4940 reason = @"missing";
4942 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4944 reason = @"installed";
4945 installed = [NSString stringWithUTF8String:ver.VerStr()];
4946 } else if (!cache[target].CandidateVerIter(cache).end())
4947 reason = @"uninstalled";
4948 else if (target->ProvidesList == 0)
4949 reason = @"uninstallable";
4951 reason = @"virtual";
4954 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4955 [NSString stringWithUTF8String:start.CompType()], @"operator",
4956 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4959 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4960 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4961 version, @"version",
4963 installed, @"installed",
4966 // yes, seriously. (wtf?)
4974 pkgDepCache::StateCache &state(cache[iterator]);
4976 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4978 if (state.NewInstall())
4979 [installs addObject:name];
4980 // XXX: else if (state.Install())
4981 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4982 [reinstalls addObject:name];
4983 // XXX: move before previous if
4984 else if (state.Upgrade())
4985 [upgrades addObject:name];
4986 else if (state.Downgrade())
4987 [downgrades addObject:name];
4988 else if (!state.Delete())
4989 // XXX: _assert(state.Keep());
4991 else if (special_r(name))
4992 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4993 [NSNull null], @"package",
4994 [NSArray arrayWithObjects:
4995 [NSDictionary dictionaryWithObjectsAndKeys:
4996 @"Conflicts", @"relationship",
4997 [NSArray arrayWithObjects:
4998 [NSDictionary dictionaryWithObjectsAndKeys:
5000 [NSNull null], @"version",
5001 @"installed", @"reason",
5008 if ([package essential])
5010 [removes addObject:name];
5013 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5014 substrate_ |= DepSubstrate(iterator.CurrentVer());
5019 else if (Advanced_) {
5020 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5022 essential_ = [[[UIAlertView alloc]
5023 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5024 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5026 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5028 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5032 [essential_ setContext:@"remove"];
5033 [essential_ setNumberOfRows:2];
5035 essential_ = [[[UIAlertView alloc]
5036 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5037 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5039 cancelButtonTitle:UCLocalize("OKAY")
5040 otherButtonTitles:nil
5043 [essential_ setContext:@"unable"];
5046 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5047 installs, @"installs",
5048 reinstalls, @"reinstalls",
5049 upgrades, @"upgrades",
5050 downgrades, @"downgrades",
5051 removes, @"removes",
5054 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5055 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5056 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5059 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5063 - (UIBarButtonItem *) leftButton {
5064 return [[[UIBarButtonItem alloc]
5065 initWithTitle:UCLocalize("CANCEL")
5066 style:UIBarButtonItemStylePlain
5068 action:@selector(cancelButtonClicked)
5073 - (void) applyRightButton {
5074 if ([issues_ count] == 0 && ![self isLoading])
5075 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5076 initWithTitle:UCLocalize("CONFIRM")
5077 style:UIBarButtonItemStyleDone
5079 action:@selector(confirmButtonClicked)
5082 [[self navigationItem] setRightBarButtonItem:nil];
5086 - (void) cancelButtonClicked {
5087 [delegate_ cancelAndClear:YES];
5088 [self dismissModalViewControllerAnimated:YES];
5092 - (void) confirmButtonClicked {
5093 if (essential_ != nil)
5103 /* Progress Data {{{ */
5104 @interface CydiaProgressData : NSObject {
5105 _transient id delegate_;
5114 _H<NSMutableArray> events_;
5115 _H<NSString> title_;
5117 _H<NSString> status_;
5118 _H<NSString> finish_;
5123 @implementation CydiaProgressData
5125 + (NSArray *) _attributeKeys {
5126 return [NSArray arrayWithObjects:
5138 - (NSArray *) attributeKeys {
5139 return [[self class] _attributeKeys];
5142 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5143 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5147 if ((self = [super init]) != nil) {
5148 events_ = [NSMutableArray arrayWithCapacity:32];
5156 - (void) setDelegate:(id)delegate {
5157 delegate_ = delegate;
5160 - (void) setPercent:(float)value {
5164 - (NSNumber *) percent {
5165 return [NSNumber numberWithFloat:percent_];
5168 - (void) setCurrent:(float)value {
5172 - (NSNumber *) current {
5173 return [NSNumber numberWithFloat:current_];
5176 - (void) setTotal:(float)value {
5180 - (NSNumber *) total {
5181 return [NSNumber numberWithFloat:total_];
5184 - (void) setSpeed:(float)value {
5188 - (NSNumber *) speed {
5189 return [NSNumber numberWithFloat:speed_];
5192 - (NSArray *) events {
5196 - (void) removeAllEvents {
5197 [events_ removeAllObjects];
5200 - (void) addEvent:(CydiaProgressEvent *)event {
5201 [events_ addObject:event];
5204 - (void) setTitle:(NSString *)text {
5208 - (NSString *) title {
5212 - (void) setFinish:(NSString *)text {
5216 - (NSString *) finish {
5217 return (id) finish_ ?: [NSNull null];
5220 - (void) setRunning:(bool)running {
5224 - (NSNumber *) running {
5225 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5230 /* Progress Controller {{{ */
5231 @interface ProgressController : CydiaWebViewController <
5234 _transient Database *database_;
5235 _H<CydiaProgressData, 1> progress_;
5239 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5241 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5243 - (void) setTitle:(NSString *)title;
5244 - (void) setCancellable:(bool)cancellable;
5248 @implementation ProgressController
5251 [database_ setProgressDelegate:nil];
5255 - (UIBarButtonItem *) leftButton {
5256 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5257 initWithTitle:UCLocalize("CANCEL")
5258 style:UIBarButtonItemStylePlain
5260 action:@selector(cancel)
5261 ] autorelease] : nil;
5264 - (void) updateCancel {
5265 [super applyLeftButton];
5268 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5269 if ((self = [super init]) != nil) {
5270 database_ = database;
5271 delegate_ = delegate;
5273 [database_ setProgressDelegate:self];
5275 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5276 [progress_ setDelegate:self];
5278 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5280 [scroller_ setBackgroundColor:[UIColor blackColor]];
5282 [[self navigationItem] setHidesBackButton:YES];
5284 [self updateCancel];
5288 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5289 [super webView:view didClearWindowObject:window forFrame:frame];
5290 [window setValue:progress_ forKey:@"cydiaProgress"];
5293 - (void) updateProgress {
5294 [self dispatchEvent:@"CydiaProgressUpdate"];
5297 - (void) viewWillAppear:(BOOL)animated {
5298 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5299 [super viewWillAppear:animated];
5302 - (void) reloadSpringBoard {
5303 if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
5304 system("/bin/launchctl stop com.apple.backboardd");
5306 system("/usr/bin/killall backboardd SpringBoard sbreload");
5310 pid_t pid(ExecFork());
5315 pid_t pid(ExecFork());
5317 execl("/usr/bin/sbreload", "sbreload", NULL);
5328 system("/usr/bin/killall backboardd SpringBoard sbreload");
5332 UpdateExternalStatus(0);
5335 [delegate_ saveState];
5339 [delegate_ returnToCydia];
5343 [delegate_ terminateWithSuccess];
5344 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5345 [delegate_ suspendWithAnimation:YES];
5347 [delegate_ suspend];*/
5359 UIProgressHUD *hud([delegate_ addProgressHUD]);
5360 [hud setText:UCLocalize("LOADING")];
5361 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5367 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5368 SBReboot(SBSSpringBoardServerPort());
5370 reboot2(RB_AUTOBOOT);
5377 - (void) setTitle:(NSString *)title {
5378 [progress_ setTitle:title];
5379 [self updateProgress];
5382 - (UIBarButtonItem *) rightButton {
5383 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5384 initWithTitle:UCLocalize("CLOSE")
5385 style:UIBarButtonItemStylePlain
5387 action:@selector(close)
5391 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5392 UpdateExternalStatus(1);
5394 [progress_ setRunning:true];
5395 [self setTitle:title];
5396 // implicit updateProgress
5398 SHA1SumValue notifyconf; {
5400 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5403 MMap mmap(file, MMap::ReadOnly);
5405 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5406 notifyconf = sha1.Result();
5410 SHA1SumValue springlist; {
5412 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5415 MMap mmap(file, MMap::ReadOnly);
5417 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5418 springlist = sha1.Result();
5422 if (invocation != nil) {
5423 [invocation yieldToSelector:@selector(invoke)];
5424 [self setTitle:@"COMPLETE"];
5429 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5432 MMap mmap(file, MMap::ReadOnly);
5434 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5435 if (!(notifyconf == sha1.Result()))
5442 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5445 MMap mmap(file, MMap::ReadOnly);
5447 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5448 if (!(springlist == sha1.Result()))
5454 if (RestartSubstrate_)
5458 RestartSubstrate_ = false;
5461 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5462 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5463 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5464 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5465 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5468 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5470 [progress_ setRunning:false];
5471 [self updateProgress];
5473 [self applyRightButton];
5476 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5477 [progress_ addEvent:event];
5478 [self updateProgress];
5481 - (bool) isProgressCancelled {
5482 return cancel_ == 2;
5487 [self updateCancel];
5490 - (void) setCancellable:(bool)cancellable {
5491 unsigned cancel(cancel_);
5495 else if (cancel_ == 0)
5498 if (cancel != cancel_)
5499 [self updateCancel];
5502 - (void) setProgressCancellable:(NSNumber *)cancellable {
5503 [self setCancellable:[cancellable boolValue]];
5506 - (void) setProgressPercent:(NSNumber *)percent {
5507 [progress_ setPercent:[percent floatValue]];
5508 [self updateProgress];
5511 - (void) setProgressStatus:(NSDictionary *)status {
5512 if (status == nil) {
5513 [progress_ setCurrent:0];
5514 [progress_ setTotal:0];
5515 [progress_ setSpeed:0];
5517 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5519 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5520 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5521 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5524 [self updateProgress];
5530 /* Package Cell {{{ */
5531 @interface PackageCell : CyteTableViewCell <
5532 CyteTableViewCellDelegate
5536 _H<NSString> description_;
5538 _H<NSString> source_;
5540 _H<UIImage> placard_;
5544 - (PackageCell *) init;
5545 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5547 - (void) drawContentRect:(CGRect)rect;
5551 @implementation PackageCell
5553 - (PackageCell *) init {
5554 CGRect frame(CGRectMake(0, 0, 320, 74));
5555 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5556 UIView *content([self contentView]);
5557 CGRect bounds([content bounds]);
5559 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5560 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5561 [content addSubview:content_];
5563 [content_ setDelegate:self];
5564 [content_ setOpaque:YES];
5568 - (NSString *) accessibilityLabel {
5572 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5573 summarized_ = summary;
5583 [content_ setBackgroundColor:[UIColor whiteColor]];
5587 Source *source = [package source];
5589 icon_ = [package icon];
5591 if (NSString *name = [package name])
5592 name_ = [NSString stringWithString:name];
5594 if (NSString *description = [package shortDescription])
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 color = [UIColor whiteColor];
5637 if ([package installed] != nil)
5638 placard = @"installed";
5643 [content_ setBackgroundColor:color];
5646 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5649 [self setNeedsDisplay];
5650 [content_ setNeedsDisplay];
5653 - (void) drawSummaryContentRect:(CGRect)rect {
5654 bool highlighted(highlighted_);
5655 float width([self bounds].size.width);
5659 rect.size = [(UIImage *) icon_ size];
5661 while (rect.size.width > 16 || rect.size.height > 16) {
5662 rect.size.width /= 2;
5663 rect.size.height /= 2;
5666 rect.origin.x = 19 - rect.size.width / 2;
5667 rect.origin.y = 19 - rect.size.height / 2;
5669 [icon_ drawInRect:rect];
5672 if (badge_ != nil) {
5674 rect.size = [(UIImage *) badge_ size];
5676 rect.size.width /= 4;
5677 rect.size.height /= 4;
5679 rect.origin.x = 25 - rect.size.width / 2;
5680 rect.origin.y = 25 - rect.size.height / 2;
5682 [badge_ drawInRect:rect];
5685 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5689 UISetColor(commercial_ ? Purple_ : Black_);
5690 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5692 if (placard_ != nil)
5693 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5696 - (void) drawNormalContentRect:(CGRect)rect {
5697 bool highlighted(highlighted_);
5698 float width([self bounds].size.width);
5702 rect.size = [(UIImage *) icon_ size];
5704 while (rect.size.width > 32 || rect.size.height > 32) {
5705 rect.size.width /= 2;
5706 rect.size.height /= 2;
5709 rect.origin.x = 25 - rect.size.width / 2;
5710 rect.origin.y = 25 - rect.size.height / 2;
5712 [icon_ drawInRect:rect];
5715 if (badge_ != nil) {
5717 rect.size = [(UIImage *) badge_ size];
5719 rect.size.width /= 2;
5720 rect.size.height /= 2;
5722 rect.origin.x = 36 - rect.size.width / 2;
5723 rect.origin.y = 36 - rect.size.height / 2;
5725 [badge_ drawInRect:rect];
5728 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5732 UISetColor(commercial_ ? Purple_ : Black_);
5733 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5734 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5737 UISetColor(commercial_ ? Purplish_ : Gray_);
5738 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5740 if (placard_ != nil)
5741 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5744 - (void) drawContentRect:(CGRect)rect {
5746 [self drawSummaryContentRect:rect];
5748 [self drawNormalContentRect:rect];
5753 /* Section Cell {{{ */
5754 @interface SectionCell : CyteTableViewCell <
5755 CyteTableViewCellDelegate
5757 _H<NSString> basic_;
5758 _H<NSString> section_;
5760 _H<NSString> count_;
5762 _H<UISwitch> switch_;
5766 - (void) setSection:(Section *)section editing:(BOOL)editing;
5770 @implementation SectionCell
5772 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5773 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5774 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5775 // XXX: this initial frame is wrong, but is fixed later
5776 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5777 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5779 UIView *content([self contentView]);
5780 CGRect bounds([content bounds]);
5782 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5783 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5784 [content addSubview:content_];
5785 [content_ setBackgroundColor:[UIColor whiteColor]];
5787 [content_ setDelegate:self];
5791 - (void) onSwitch:(id)sender {
5792 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5793 if (metadata == nil) {
5794 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5795 [Sections_ setObject:metadata forKey:basic_];
5798 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5802 - (void) setSection:(Section *)section editing:(BOOL)editing {
5803 if (editing != editing_) {
5805 [switch_ removeFromSuperview];
5807 [self addSubview:switch_];
5816 if (section == nil) {
5817 name_ = UCLocalize("ALL_PACKAGES");
5820 basic_ = [section name];
5821 section_ = [section localized];
5823 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5824 count_ = [NSString stringWithFormat:@"%d", [section count]];
5827 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5830 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5831 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5833 [content_ setNeedsDisplay];
5836 - (void) setFrame:(CGRect)frame {
5837 [super setFrame:frame];
5839 CGRect rect([switch_ frame]);
5840 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
5843 - (NSString *) accessibilityLabel {
5847 - (void) drawContentRect:(CGRect)rect {
5848 bool highlighted(highlighted_ && !editing_);
5850 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
5852 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5855 float width(rect.size.width);
5857 width -= 9 + [switch_ frame].size.width;
5861 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5863 CGSize size = [count_ sizeWithFont:Font14_];
5865 UISetColor(Folder_);
5867 [count_ drawAtPoint:CGPointMake(10 + (30 - size.width) / 2, 18) withFont:Font12Bold_];
5873 /* File Table {{{ */
5874 @interface FileTable : CyteViewController <
5875 UITableViewDataSource,
5878 _transient Database *database_;
5879 _H<Package> package_;
5881 _H<NSMutableArray> files_;
5882 _H<UITableView, 2> list_;
5885 - (id) initWithDatabase:(Database *)database;
5886 - (void) setPackage:(Package *)package;
5890 @implementation FileTable
5892 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5893 return files_ == nil ? 0 : [files_ count];
5896 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5900 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5901 static NSString *reuseIdentifier = @"Cell";
5903 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5905 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5906 [cell setFont:[UIFont systemFontOfSize:16]];
5908 [cell setText:[files_ objectAtIndex:indexPath.row]];
5909 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5914 - (NSURL *) navigationURL {
5915 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5919 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5920 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5921 [list_ setRowHeight:24.0f];
5922 [(UITableView *) list_ setDataSource:self];
5923 [list_ setDelegate:self];
5924 [self setView:list_];
5927 - (void) viewDidLoad {
5928 [super viewDidLoad];
5930 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5933 - (void) releaseSubviews {
5939 [super releaseSubviews];
5942 - (id) initWithDatabase:(Database *)database {
5943 if ((self = [super init]) != nil) {
5944 database_ = database;
5948 - (void) setPackage:(Package *)package {
5952 files_ = [NSMutableArray arrayWithCapacity:32];
5954 if (package != nil) {
5956 name_ = [package id];
5958 if (NSArray *files = [package files])
5959 [files_ addObjectsFromArray:files];
5961 if ([files_ count] != 0) {
5962 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5963 [files_ removeObjectAtIndex:0];
5964 [files_ sortUsingSelector:@selector(compareByPath:)];
5966 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5967 [stack addObject:@"/"];
5969 for (int i(0), e([files_ count]); i != e; ++i) {
5970 NSString *file = [files_ objectAtIndex:i];
5971 while (![file hasPrefix:[stack lastObject]])
5972 [stack removeLastObject];
5973 NSString *directory = [stack lastObject];
5974 [stack addObject:[file stringByAppendingString:@"/"]];
5975 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5976 ([stack count] - 2) * 3, "",
5977 [file substringFromIndex:[directory length]]
5986 - (void) reloadData {
5989 [self setPackage:[database_ packageWithName:name_]];
5994 /* Package Controller {{{ */
5995 @interface CYPackageController : CydiaWebViewController <
5996 UIActionSheetDelegate
5998 _transient Database *database_;
5999 _H<Package> package_;
6002 _H<NSMutableArray> buttons_;
6003 _H<UIBarButtonItem> button_;
6006 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6010 @implementation CYPackageController
6012 - (NSURL *) navigationURL {
6013 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6016 /* XXX: this is not safe at all... localization of /fail/ */
6017 - (void) _clickButtonWithName:(NSString *)name {
6018 if ([name isEqualToString:UCLocalize("CLEAR")])
6019 [delegate_ clearPackage:package_];
6020 else if ([name isEqualToString:UCLocalize("INSTALL")])
6021 [delegate_ installPackage:package_];
6022 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6023 [delegate_ installPackage:package_];
6024 else if ([name isEqualToString:UCLocalize("REMOVE")])
6025 [delegate_ removePackage:package_];
6026 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6027 [delegate_ installPackage:package_];
6028 else _assert(false);
6031 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6032 NSString *context([sheet context]);
6034 if ([context isEqualToString:@"modify"]) {
6035 if (button != [sheet cancelButtonIndex]) {
6036 NSString *buttonName = [buttons_ objectAtIndex:button];
6037 [self _clickButtonWithName:buttonName];
6040 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6044 - (bool) _allowJavaScriptPanel {
6049 - (void) _customButtonClicked {
6050 int count([buttons_ count]);
6055 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6057 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6058 [buttons addObjectsFromArray:buttons_];
6060 UIActionSheet *sheet = [[[UIActionSheet alloc]
6063 cancelButtonTitle:nil
6064 destructiveButtonTitle:nil
6065 otherButtonTitles:nil
6068 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6070 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6071 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6073 [sheet setContext:@"modify"];
6075 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6079 - (void) reloadButtonClicked {
6080 if (commercial_ && function_ == nil && [package_ uninstalled])
6082 [self customButtonClicked];
6085 - (void) applyLoadingTitle {
6086 // Don't show "Loading" as the title. Ever.
6089 - (UIBarButtonItem *) rightButton {
6094 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6095 if ((self = [super init]) != nil) {
6096 database_ = database;
6097 buttons_ = [NSMutableArray arrayWithCapacity:4];
6098 name_ = name == nil ? @"" : [NSString stringWithString:name];
6099 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6103 - (void) reloadData {
6106 package_ = [database_ packageWithName:name_];
6108 [buttons_ removeAllObjects];
6110 if (package_ != nil) {
6111 [(Package *) package_ parse];
6113 commercial_ = [package_ isCommercial];
6115 if ([package_ mode] != nil)
6116 [buttons_ addObject:UCLocalize("CLEAR")];
6117 if ([package_ source] == nil);
6118 else if ([package_ upgradableAndEssential:NO])
6119 [buttons_ addObject:UCLocalize("UPGRADE")];
6120 else if ([package_ uninstalled])
6121 [buttons_ addObject:UCLocalize("INSTALL")];
6123 [buttons_ addObject:UCLocalize("REINSTALL")];
6124 if (![package_ uninstalled])
6125 [buttons_ addObject:UCLocalize("REMOVE")];
6129 switch ([buttons_ count]) {
6130 case 0: title = nil; break;
6131 case 1: title = [buttons_ objectAtIndex:0]; break;
6132 default: title = UCLocalize("MODIFY"); break;
6135 button_ = [[[UIBarButtonItem alloc]
6137 style:UIBarButtonItemStylePlain
6139 action:@selector(customButtonClicked)
6143 - (bool) isLoading {
6144 return commercial_ ? [super isLoading] : false;
6150 /* Package List Controller {{{ */
6151 @interface PackageListController : CyteViewController <
6152 UITableViewDataSource,
6155 _transient Database *database_;
6157 _H<NSArray> packages_;
6158 _H<NSMutableArray> sections_;
6159 _H<UITableView, 2> list_;
6160 _H<NSMutableArray> index_;
6161 _H<NSMutableDictionary> indices_;
6162 _H<NSString> title_;
6163 unsigned reloading_;
6166 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6167 - (void) setDelegate:(id)delegate;
6168 - (void) resetCursor;
6173 @implementation PackageListController
6175 - (NSURL *) referrerURL {
6176 return [self navigationURL];
6179 - (bool) isSummarized {
6183 - (bool) showsSections {
6187 - (void) deselectWithAnimation:(BOOL)animated {
6188 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6191 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6192 CGRect base = [[self view] bounds];
6193 base.size.height -= bounds.size.height;
6194 base.origin = [list_ frame].origin;
6196 [UIView beginAnimations:nil context:NULL];
6197 [UIView setAnimationBeginsFromCurrentState:YES];
6198 [UIView setAnimationCurve:curve];
6199 [UIView setAnimationDuration:duration];
6200 [list_ setFrame:base];
6201 [UIView commitAnimations];
6204 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6205 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6208 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6209 [self resizeForKeyboardBounds:bounds duration:0];
6212 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6213 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6214 *curve = UIViewAnimationCurveEaseInOut;
6216 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6218 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6221 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6224 - (void) keyboardWillShow:(NSNotification *)notification {
6227 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6228 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6230 NSTimeInterval duration;
6231 UIViewAnimationCurve curve;
6232 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6234 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);
6235 UIViewController *base = self;
6236 while ([base parentOrPresentingViewController] != nil)
6237 base = [base parentOrPresentingViewController];
6238 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6239 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6241 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6242 intersection.size.height += CYStatusBarHeight();
6244 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6247 - (void) keyboardWillHide:(NSNotification *)notification {
6248 NSTimeInterval duration;
6249 UIViewAnimationCurve curve;
6250 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6252 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6255 - (void) viewWillAppear:(BOOL)animated {
6256 [super viewWillAppear:animated];
6258 [self resizeForKeyboardBounds:CGRectZero];
6259 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6260 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6263 - (void) viewWillDisappear:(BOOL)animated {
6264 [super viewWillDisappear:animated];
6266 [self resizeForKeyboardBounds:CGRectZero];
6267 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6268 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6271 - (void) viewDidAppear:(BOOL)animated {
6272 [super viewDidAppear:animated];
6273 [self deselectWithAnimation:animated];
6276 - (void) didSelectPackage:(Package *)package {
6277 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6278 [view setDelegate:delegate_];
6279 [[self navigationController] pushViewController:view animated:YES];
6282 #if TryIndexedCollation
6283 + (BOOL) hasIndexedCollation {
6284 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6288 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6289 NSInteger count([sections_ count]);
6290 return count == 0 ? 1 : count;
6293 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6294 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6296 return [[sections_ objectAtIndex:section] name];
6299 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6300 if ([sections_ count] == 0)
6302 return [[sections_ objectAtIndex:section] count];
6305 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6306 @synchronized (database_) {
6307 if ([database_ era] != era_)
6310 Section *section([sections_ objectAtIndex:[path section]]);
6311 NSInteger row([path row]);
6312 Package *package([packages_ objectAtIndex:([section row] + row)]);
6313 return [[package retain] autorelease];
6316 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6317 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6319 cell = [[[PackageCell alloc] init] autorelease];
6321 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6322 [cell setPackage:package asSummary:[self isSummarized]];
6326 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6327 Package *package([self packageAtIndexPath:path]);
6328 package = [database_ packageWithName:[package id]];
6329 [self didSelectPackage:package];
6332 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6333 if (![self showsSections])
6339 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6340 #if TryIndexedCollation
6341 if ([[self class] hasIndexedCollation]) {
6342 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6349 - (void) updateHeight {
6350 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6353 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6354 if ((self = [super init]) != nil) {
6355 database_ = database;
6356 title_ = [title copy];
6357 [[self navigationItem] setTitle:title_];
6362 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6363 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6364 [self setView:view];
6366 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6367 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6368 [view addSubview:list_];
6370 // XXX: is 20 the most optimal number here?
6371 [list_ setSectionIndexMinimumDisplayRowCount:20];
6373 [(UITableView *) list_ setDataSource:self];
6374 [list_ setDelegate:self];
6376 [self updateHeight];
6379 - (void) releaseSubviews {
6387 [super releaseSubviews];
6390 - (void) setDelegate:(id)delegate {
6391 delegate_ = delegate;
6394 - (bool) shouldYield {
6398 - (bool) shouldBlock {
6402 - (NSMutableArray *) _reloadPackages {
6403 @synchronized (database_) {
6404 era_ = [database_ era];
6405 NSArray *packages([database_ packages]);
6407 return [NSMutableArray arrayWithArray:packages];
6410 - (void) _reloadData {
6411 if (reloading_ != 0) {
6419 if ([self shouldYield]) {
6423 if (![self shouldBlock])
6426 hud = [delegate_ addProgressHUD];
6427 [hud setText:UCLocalize("LOADING")];
6431 packages = [self yieldToSelector:@selector(_reloadPackages)];
6434 [delegate_ removeProgressHUD:hud];
6435 } while (reloading_ == 2);
6437 packages = [self _reloadPackages];
6440 @synchronized (database_) {
6441 if (era_ != [database_ era])
6445 packages_ = packages;
6447 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6448 sections_ = [NSMutableArray arrayWithCapacity:16];
6450 Section *section = nil;
6452 #if TryIndexedCollation
6453 if ([[self class] hasIndexedCollation]) {
6454 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6456 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6457 NSArray *titles = [collation sectionIndexTitles];
6460 _profile(PackageTable$reloadData$Section)
6461 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6465 _profile(PackageTable$reloadData$Section$Package)
6466 package = [packages_ objectAtIndex:offset];
6467 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6470 while (secidx < index) {
6473 _profile(PackageTable$reloadData$Section$Allocate)
6474 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6477 _profile(PackageTable$reloadData$Section$Add)
6478 [sections_ addObject:section];
6482 [section addToCount];
6488 index_ = [NSMutableArray arrayWithCapacity:32];
6490 bool sectioned([self showsSections]);
6492 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6493 [sections_ addObject:section];
6496 _profile(PackageTable$reloadData$Section)
6497 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6501 _profile(PackageTable$reloadData$Section$Package)
6502 package = [packages_ objectAtIndex:offset];
6503 index = [package index];
6506 if (sectioned && (section == nil || [section index] != index)) {
6507 _profile(PackageTable$reloadData$Section$Allocate)
6508 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6511 [index_ addObject:[section name]];
6512 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6514 _profile(PackageTable$reloadData$Section$Add)
6515 [sections_ addObject:section];
6519 [section addToCount];
6524 [self updateHeight];
6526 _profile(PackageTable$reloadData$List)
6527 [(UITableView *) list_ setDataSource:self];
6532 - (void) reloadData {
6535 if ([self shouldYield])
6536 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6541 - (void) resetCursor {
6542 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6545 - (void) clearData {
6546 [self updateHeight];
6548 [list_ setDataSource:nil];
6556 /* Filtered Package List Controller {{{ */
6557 @interface FilteredPackageListController : PackageListController {
6560 _H<NSObject> object_;
6563 - (void) setObject:(id)object;
6564 - (void) setObject:(id)object forFilter:(SEL)filter;
6567 - (void) setFilter:(SEL)filter;
6569 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6573 @implementation FilteredPackageListController
6579 - (void) setFilter:(SEL)filter {
6580 @synchronized (self) {
6583 /* XXX: this is an unsafe optimization of doomy hell */
6584 Method method(class_getInstanceMethod([Package class], filter));
6585 _assert(method != NULL);
6586 imp_ = method_getImplementation(method);
6587 _assert(imp_ != NULL);
6590 - (void) setObject:(id)object {
6591 @synchronized (self) {
6595 - (void) setObject:(id)object forFilter:(SEL)filter {
6596 @synchronized (self) {
6597 [self setFilter:filter];
6598 [self setObject:object];
6601 - (NSMutableArray *) _reloadPackages {
6602 @synchronized (database_) {
6603 era_ = [database_ era];
6604 NSArray *packages([database_ packages]);
6606 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6610 _H<NSObject> object;
6612 @synchronized (self) {
6618 _profile(PackageTable$reloadData$Filter)
6619 for (Package *package in packages)
6620 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6621 [filtered addObject:package];
6627 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6628 if ((self = [super initWithDatabase:database title:title]) != nil) {
6629 [self setFilter:filter];
6630 [self setObject:object];
6637 /* Home Controller {{{ */
6638 @interface HomeController : CydiaWebViewController {
6639 CFRunLoopRef runloop_;
6640 SCNetworkReachabilityRef reachability_;
6645 @implementation HomeController
6647 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6648 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6652 if ((self = [super init]) != nil) {
6653 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6656 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6657 if (reachability_ != NULL) {
6658 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6659 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6661 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6662 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6669 if (reachability_ != NULL && runloop_ != NULL)
6670 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6674 - (NSURL *) navigationURL {
6675 return [NSURL URLWithString:@"cydia://home"];
6678 - (void) aboutButtonClicked {
6679 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6681 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6682 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6683 [alert setCancelButtonIndex:0];
6686 @"Copyright \u00a9 2008-2013\n"
6689 "Jay Freeman (saurik)\n"
6690 "saurik@saurik.com\n"
6691 "http://www.saurik.com/"
6697 - (UIBarButtonItem *) leftButton {
6698 return [[[UIBarButtonItem alloc]
6699 initWithTitle:UCLocalize("ABOUT")
6700 style:UIBarButtonItemStylePlain
6702 action:@selector(aboutButtonClicked)
6708 /* Manage Controller {{{ */
6709 @interface ManageController : CydiaWebViewController {
6712 - (void) queueStatusDidChange;
6716 @implementation ManageController
6719 if ((self = [super init]) != nil) {
6720 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6724 - (NSURL *) navigationURL {
6725 return [NSURL URLWithString:@"cydia://manage"];
6728 - (UIBarButtonItem *) leftButton {
6729 return [[[UIBarButtonItem alloc]
6730 initWithTitle:UCLocalize("SETTINGS")
6731 style:UIBarButtonItemStylePlain
6733 action:@selector(settingsButtonClicked)
6737 - (void) settingsButtonClicked {
6738 [delegate_ showSettings];
6741 - (void) queueButtonClicked {
6745 - (UIBarButtonItem *) rightButton {
6746 return Queuing_ ? [[[UIBarButtonItem alloc]
6747 initWithTitle:UCLocalize("QUEUE")
6748 style:UIBarButtonItemStyleDone
6750 action:@selector(queueButtonClicked)
6751 ] autorelease] : nil;
6754 - (void) queueStatusDidChange {
6755 [self applyRightButton];
6758 - (bool) isLoading {
6759 return !Queuing_ && [super isLoading];
6765 /* Refresh Bar {{{ */
6766 @interface RefreshBar : UINavigationBar {
6767 _H<UIProgressIndicator> indicator_;
6768 _H<UITextLabel> prompt_;
6769 _H<UINavigationButton> cancel_;
6774 @implementation RefreshBar
6776 - (void) positionViews {
6777 CGRect frame = [cancel_ frame];
6778 frame.size = [cancel_ sizeThatFits:frame.size];
6779 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6780 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6781 [cancel_ setFrame:frame];
6783 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6784 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6785 CGRect indrect = {{indoffset, indoffset}, indsize};
6786 [indicator_ setFrame:indrect];
6788 CGSize prmsize = {215, indsize.height + 4};
6790 indoffset * 2 + indsize.width,
6791 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6793 [prompt_ setFrame:prmrect];
6796 - (void) setFrame:(CGRect)frame {
6797 [super setFrame:frame];
6798 [self positionViews];
6801 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6802 if ((self = [super initWithFrame:frame]) != nil) {
6803 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6805 [self setBarStyle:UIBarStyleBlack];
6807 UIBarStyle barstyle([self _barStyle:NO]);
6808 bool ugly(barstyle == UIBarStyleDefault);
6810 UIProgressIndicatorStyle style = ugly ?
6811 UIProgressIndicatorStyleMediumBrown :
6812 UIProgressIndicatorStyleMediumWhite;
6814 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6815 [(UIProgressIndicator *) indicator_ setStyle:style];
6816 [indicator_ startAnimation];
6817 [self addSubview:indicator_];
6819 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6820 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6821 [prompt_ setBackgroundColor:[UIColor clearColor]];
6822 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6823 [self addSubview:prompt_];
6825 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6826 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6827 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6828 [cancel_ setBarStyle:barstyle];
6830 [self positionViews];
6834 - (void) setCancellable:(bool)cancellable {
6836 [self addSubview:cancel_];
6838 [cancel_ removeFromSuperview];
6842 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6846 [self setCancellable:NO];
6849 - (void) setPrompt:(NSString *)prompt {
6850 [prompt_ setText:prompt];
6853 - (void) setProgress:(float)progress {
6859 /* Cydia Navigation Controller Interface {{{ */
6860 @interface UINavigationController (Cydia)
6862 - (NSArray *) navigationURLCollection;
6863 - (void) unloadData;
6868 /* Cydia Tab Bar Controller {{{ */
6869 @interface CYTabBarController : UITabBarController <
6870 UITabBarControllerDelegate,
6873 _transient Database *database_;
6874 _H<RefreshBar, 1> refreshbar_;
6878 // XXX: ok, "updatedelegate_"?...
6879 _transient NSObject<CydiaDelegate> *updatedelegate_;
6881 _H<UIViewController> remembered_;
6882 _transient UIViewController *transient_;
6885 - (NSArray *) navigationURLCollection;
6886 - (void) dropBar:(BOOL)animated;
6887 - (void) beginUpdate;
6888 - (void) raiseBar:(BOOL)animated;
6890 - (void) unloadData;
6894 @implementation CYTabBarController
6896 - (void) didReceiveMemoryWarning {
6897 [super didReceiveMemoryWarning];
6899 // presenting a UINavigationController on 2.x does not update its transitionView
6900 // it thereby will not allow its topViewController to be unloaded by memory pressure
6901 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6902 UIViewController *selected([self selectedViewController]);
6903 for (UINavigationController *controller in [self viewControllers])
6904 if (controller != selected)
6905 if (UIViewController *top = [controller topViewController])
6910 - (void) setUnselectedViewController:(UIViewController *)transient {
6911 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6912 if (transient != nil) {
6913 [[[self viewControllers] objectAtIndex:0] pushViewController:transient animated:YES];
6914 [self setSelectedIndex:0];
6918 NSMutableArray *controllers = [[[self viewControllers] mutableCopy] autorelease];
6919 if (transient != nil) {
6920 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
6921 [navigation setViewControllers:[NSArray arrayWithObject:transient]];
6922 transient = navigation;
6924 if (transient_ == nil)
6925 remembered_ = [controllers objectAtIndex:0];
6926 transient_ = transient;
6927 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6928 [controllers replaceObjectAtIndex:0 withObject:transient_];
6929 [self setSelectedIndex:0];
6930 [self setViewControllers:controllers];
6931 [self concealTabBarSelection];
6932 } else if (remembered_ != nil) {
6933 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6934 transient_ = transient;
6935 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6937 [self setViewControllers:controllers];
6938 [self revealTabBarSelection];
6942 - (UIViewController *) unselectedViewController {
6946 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6947 if ([self unselectedViewController])
6948 [self setUnselectedViewController:nil];
6950 // presenting a UINavigationController on 2.x does not update its transitionView
6951 // if this view was unloaded, the tranitionView may currently be presenting nothing
6952 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6953 UINavigationController *navigation((UINavigationController *) viewController);
6954 [navigation pushViewController:[[[UIViewController alloc] init] autorelease] animated:NO];
6955 [navigation popViewControllerAnimated:NO];
6959 - (NSArray *) navigationURLCollection {
6960 NSMutableArray *items([NSMutableArray array]);
6962 // XXX: Should this deal with transient view controllers?
6963 for (id navigation in [self viewControllers]) {
6964 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6966 [items addObject:stack];
6972 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6973 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6974 [self setUnselectedViewController:nil];
6976 [super dismissModalViewControllerAnimated:YES];
6979 - (void) unloadData {
6982 for (UINavigationController *controller in [self viewControllers])
6983 [controller unloadData];
6985 if (UIViewController *selected = [self selectedViewController])
6986 [selected reloadData];
6988 if (UIViewController *unselected = [self unselectedViewController]) {
6989 [unselected unloadData];
6990 [unselected reloadData];
6995 [[NSNotificationCenter defaultCenter] removeObserver:self];
7000 - (id) initWithDatabase:(Database *)database {
7001 if ((self = [super init]) != nil) {
7002 database_ = database;
7003 [self setDelegate:self];
7005 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7006 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7008 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
7012 - (void) setUpdate:(NSDate *)date {
7016 - (void) beginUpdate {
7017 [(RefreshBar *) refreshbar_ start];
7020 [updatedelegate_ retainNetworkActivityIndicator];
7024 detachNewThreadSelector:@selector(performUpdate)
7030 - (void) performUpdate {
7031 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7034 status.setDelegate(self);
7035 [database_ updateWithStatus:status];
7038 performSelectorOnMainThread:@selector(completeUpdate)
7046 - (void) stopUpdateWithSelector:(SEL)selector {
7048 [updatedelegate_ releaseNetworkActivityIndicator];
7050 [self raiseBar:YES];
7053 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7056 - (void) completeUpdate {
7059 [self stopUpdateWithSelector:@selector(reloadData)];
7062 - (void) cancelUpdate {
7063 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7066 - (void) cancelPressed {
7067 [self cancelUpdate];
7074 - (void) addProgressEvent:(CydiaProgressEvent *)event {
7075 [refreshbar_ setPrompt:[event compoundMessage]];
7078 - (bool) isProgressCancelled {
7082 - (void) setProgressCancellable:(NSNumber *)cancellable {
7083 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
7086 - (void) setProgressPercent:(NSNumber *)percent {
7087 [refreshbar_ setProgress:[percent floatValue]];
7090 - (void) setProgressStatus:(NSDictionary *)status {
7092 [self setProgressPercent:[status objectForKey:@"Percent"]];
7095 - (void) setUpdateDelegate:(id)delegate {
7096 updatedelegate_ = delegate;
7099 - (UIView *) transitionView {
7100 if (![self respondsToSelector:@selector(_transitionView)])
7101 return MSHookIvar<id>(self, "_viewControllerTransitionView");
7102 else if (kCFCoreFoundationVersionNumber < 800)
7103 return [self _transitionView];
7105 return [[[self _transitionView] superview] superview];
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 = 0;
7120 else if (kCFCoreFoundationVersionNumber < 800)
7121 barframe.origin.y = CYStatusBarHeight();
7123 barframe.origin.y = -barframe.size.height + CYStatusBarHeight();
7125 [refreshbar_ setFrame:barframe];
7128 [UIView beginAnimations:nil context:NULL];
7130 CGRect viewframe = [transition frame];
7131 float adjust(barframe.size.height);
7132 if (kCFCoreFoundationVersionNumber >= 800)
7133 adjust -= CYStatusBarHeight();
7134 viewframe.origin.y += adjust;
7135 viewframe.size.height -= adjust;
7136 [transition setFrame:viewframe];
7139 [UIView commitAnimations];
7141 // Ensure bar has the proper width for our view, it might have changed
7142 barframe.size.width = viewframe.size.width;
7143 [refreshbar_ setFrame:barframe];
7146 - (void) raiseBar:(BOOL)animated {
7151 UIView *transition([self transitionView]);
7152 [refreshbar_ removeFromSuperview];
7154 CGRect barframe([refreshbar_ frame]);
7157 [UIView beginAnimations:nil context:NULL];
7159 CGRect viewframe = [transition frame];
7160 float adjust(barframe.size.height);
7161 if (kCFCoreFoundationVersionNumber >= 800)
7162 adjust -= CYStatusBarHeight();
7163 viewframe.origin.y -= adjust;
7164 viewframe.size.height += adjust;
7165 [transition setFrame:viewframe];
7168 [UIView commitAnimations];
7171 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7172 bool dropped(dropped_);
7177 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7183 - (void) statusBarFrameChanged:(NSNotification *)notification {
7193 /* Cydia Navigation Controller Implementation {{{ */
7194 @implementation UINavigationController (Cydia)
7196 - (NSArray *) navigationURLCollection {
7197 NSMutableArray *stack([NSMutableArray array]);
7199 for (CyteViewController *controller in [self viewControllers]) {
7200 NSString *url = [[controller navigationURL] absoluteString];
7202 [stack addObject:url];
7208 - (void) reloadData {
7211 UIViewController *visible([self visibleViewController]);
7213 [visible reloadData];
7215 // on the iPad, this view controller is ALSO visible. :(
7217 if (UIViewController *top = [self topViewController])
7222 - (void) unloadData {
7223 for (CyteViewController *page in [self viewControllers])
7232 /* Cydia:// Protocol {{{ */
7233 @interface CydiaURLProtocol : NSURLProtocol {
7238 @implementation CydiaURLProtocol
7240 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7241 NSURL *url([request URL]);
7245 NSString *scheme([[url scheme] lowercaseString]);
7246 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7248 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7254 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7258 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7259 id<NSURLProtocolClient> client([self client]);
7261 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7263 NSData *data(UIImagePNGRepresentation(icon));
7265 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7266 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7267 [client URLProtocol:self didLoadData:data];
7268 [client URLProtocolDidFinishLoading:self];
7272 - (void) startLoading {
7273 id<NSURLProtocolClient> client([self client]);
7274 NSURLRequest *request([self request]);
7276 NSURL *url([request URL]);
7277 NSString *href([url absoluteString]);
7278 NSString *scheme([[url scheme] lowercaseString]);
7282 if ([scheme isEqualToString:@"cydia"])
7283 path = [href substringFromIndex:8];
7284 else if ([scheme isEqualToString:@"about"])
7285 path = [href substringFromIndex:12];
7286 else _assert(false);
7288 NSRange slash([path rangeOfString:@"/"]);
7291 if (slash.location == NSNotFound) {
7295 command = [path substringToIndex:slash.location];
7296 path = [path substringFromIndex:(slash.location + 1)];
7299 Database *database([Database sharedInstance]);
7301 if ([command isEqualToString:@"package-icon"]) {
7304 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7305 Package *package([database packageWithName:path]);
7309 UIImage *icon([package icon]);
7310 [self _returnPNGWithImage:icon forRequest:request];
7311 } else if ([command isEqualToString:@"uikit-image"]) {
7314 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7315 UIImage *icon(_UIImageWithName(path));
7316 [self _returnPNGWithImage:icon forRequest:request];
7317 } else if ([command isEqualToString:@"section-icon"]) {
7320 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7321 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7323 icon = [UIImage applicationImageNamed:@"unknown.png"];
7324 [self _returnPNGWithImage:icon forRequest:request];
7326 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7330 - (void) stopLoading {
7336 /* Section Controller {{{ */
7337 @interface SectionController : FilteredPackageListController {
7338 _H<IndirectDelegate, 1> indirect_;
7339 _H<CydiaObject> cydia_;
7340 _H<NSString> section_;
7341 std::vector< _H<CyteWebViewTableViewCell, 1> > promoted_;
7344 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7348 @implementation SectionController
7350 - (NSURL *) referrerURL {
7351 NSString *name = section_;
7355 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@", UI_, [name stringByAddingPercentEscapesIncludingReserved]]];
7358 - (NSURL *) navigationURL {
7359 NSString *name = section_;
7363 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", [name stringByAddingPercentEscapesIncludingReserved]]];
7366 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7369 title = UCLocalize("ALL_PACKAGES");
7370 else if (![name isEqual:@""])
7371 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7373 title = UCLocalize("NO_SECTION");
7375 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7376 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7377 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7382 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7383 return [super numberOfSectionsInTableView:list] + 1;
7386 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7387 return section == 0 ? nil : [super tableView:list titleForHeaderInSection:(section - 1)];
7390 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7391 return section == 0 ? promoted_.size() : [super tableView:list numberOfRowsInSection:(section - 1)];
7394 + (NSIndexPath *) adjustedIndexPath:(NSIndexPath *)path {
7395 return [NSIndexPath indexPathForRow:[path row] inSection:([path section] - 1)];
7398 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7399 if ([path section] != 0)
7400 return [super tableView:table cellForRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7402 return promoted_[[path row]];
7405 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
7406 if ([path section] != 0)
7407 return [super tableView:table didSelectRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7410 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
7411 NSInteger section([super tableView:tableView sectionForSectionIndexTitle:title atIndex:index]);
7412 return section == 0 ? 0 : section + 1;
7415 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7416 NSURL *url([request URL]);
7420 if ([frame isEqualToString:@"_open"])
7421 [delegate_ openURL:url];
7423 WebFrame *frame(nil);
7424 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7425 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7427 frame = [view mainFrame];
7429 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7431 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7432 [controller setDelegate:delegate_];
7433 [[self navigationController] pushViewController:controller animated:YES];
7439 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7440 return [CydiaWebViewController requestWithHeaders:request];
7443 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7444 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7450 // XXX: this code is horrible. I mean, wtf Jay?
7451 if (ShowPromoted_ && [[Metadata_ objectForKey:@"ShowPromoted"] boolValue]) {
7452 promoted_.resize(1);
7454 for (unsigned i(0); i != promoted_.size(); ++i) {
7455 CyteWebViewTableViewCell *promoted([CyteWebViewTableViewCell cellWithRequest:[NSURLRequest
7456 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sectionhead/%u/%@",
7457 UI_, i, section_ == nil ? @"" : [section_ stringByAddingPercentEscapesIncludingReserved]]
7460 cachePolicy:NSURLRequestUseProtocolCachePolicy
7464 [promoted setDelegate:self];
7465 promoted_[i] = promoted;
7470 - (void) setDelegate:(id)delegate {
7471 [super setDelegate:delegate];
7472 [cydia_ setDelegate:delegate];
7475 - (void) releaseSubviews {
7477 [super releaseSubviews];
7482 /* Sections Controller {{{ */
7483 @interface SectionsController : CyteViewController <
7484 UITableViewDataSource,
7487 _transient Database *database_;
7488 _H<NSMutableArray> sections_;
7489 _H<NSMutableArray> filtered_;
7490 _H<UITableView, 2> list_;
7493 - (id) initWithDatabase:(Database *)database;
7494 - (void) editButtonClicked;
7498 @implementation SectionsController
7500 - (NSURL *) navigationURL {
7501 return [NSURL URLWithString:@"cydia://sections"];
7504 - (void) updateNavigationItem {
7505 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7506 if ([sections_ count] == 0) {
7507 [[self navigationItem] setRightBarButtonItem:nil];
7509 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7510 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7512 action:@selector(editButtonClicked)
7513 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7517 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7518 [super setEditing:editing animated:animated];
7523 [delegate_ updateData];
7525 [self updateNavigationItem];
7528 - (void) viewDidAppear:(BOOL)animated {
7529 [super viewDidAppear:animated];
7530 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7533 - (void) viewWillDisappear:(BOOL)animated {
7534 [super viewWillDisappear:animated];
7535 [self setEditing:NO];
7538 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7539 Section *section = nil;
7540 int index = [indexPath row];
7541 if (![self isEditing]) {
7544 section = [filtered_ objectAtIndex:index];
7546 section = [sections_ objectAtIndex:index];
7551 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7552 if ([self isEditing])
7553 return [sections_ count];
7555 return [filtered_ count] + 1;
7558 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7562 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7563 static NSString *reuseIdentifier = @"SectionCell";
7565 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7567 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7569 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7574 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7575 if ([self isEditing])
7578 Section *section = [self sectionAtIndexPath:indexPath];
7580 SectionController *controller = [[[SectionController alloc]
7581 initWithDatabase:database_
7582 section:[section name]
7584 [controller setDelegate:delegate_];
7586 [[self navigationController] pushViewController:controller animated:YES];
7590 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7591 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7592 [list_ setRowHeight:46];
7593 [(UITableView *) list_ setDataSource:self];
7594 [list_ setDelegate:self];
7595 [self setView:list_];
7598 - (void) viewDidLoad {
7599 [super viewDidLoad];
7601 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7604 - (void) releaseSubviews {
7610 [super releaseSubviews];
7613 - (id) initWithDatabase:(Database *)database {
7614 if ((self = [super init]) != nil) {
7615 database_ = database;
7619 - (void) reloadData {
7622 NSArray *packages = [database_ packages];
7624 sections_ = [NSMutableArray arrayWithCapacity:16];
7625 filtered_ = [NSMutableArray arrayWithCapacity:16];
7627 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7630 for (Package *package in packages) {
7631 NSString *name([package section]);
7632 NSString *key(name == nil ? @"" : name);
7636 _profile(SectionsView$reloadData$Section)
7637 section = [sections objectForKey:key];
7638 if (section == nil) {
7639 _profile(SectionsView$reloadData$Section$Allocate)
7640 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7641 [sections setObject:section forKey:key];
7646 [section addToCount];
7648 _profile(SectionsView$reloadData$Filter)
7649 if (![package valid] || ![package visible])
7657 [sections_ addObjectsFromArray:[sections allValues]];
7659 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7661 for (Section *section in (id) sections_) {
7662 size_t count([section row]);
7666 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7667 [section setCount:count];
7668 [filtered_ addObject:section];
7671 [self updateNavigationItem];
7676 - (void) editButtonClicked {
7677 [self setEditing:![self isEditing] animated:YES];
7683 /* Changes Controller {{{ */
7684 @interface ChangesController : CyteViewController <
7685 CyteWebViewDelegate,
7686 UITableViewDataSource,
7689 _transient Database *database_;
7691 _H<NSMutableArray> packages_;
7692 _H<NSMutableArray> sections_;
7693 _H<UITableView, 2> list_;
7694 _H<CyteWebView, 1> dickbar_;
7696 _H<IndirectDelegate, 1> indirect_;
7697 _H<CydiaObject> cydia_;
7700 - (id) initWithDatabase:(Database *)database;
7704 @implementation ChangesController
7706 - (NSURL *) navigationURL {
7707 return [NSURL URLWithString:@"cydia://changes"];
7710 - (void) viewDidAppear:(BOOL)animated {
7711 [super viewDidAppear:animated];
7712 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7715 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7716 NSInteger count([sections_ count]);
7717 return count == 0 ? 1 : count;
7720 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7721 if ([sections_ count] == 0)
7723 return [[sections_ objectAtIndex:section] name];
7726 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7727 if ([sections_ count] == 0)
7729 return [[sections_ objectAtIndex:section] count];
7732 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7733 @synchronized (database_) {
7734 if ([database_ era] != era_)
7737 NSUInteger sectionIndex([path section]);
7738 if (sectionIndex >= [sections_ count])
7740 Section *section([sections_ objectAtIndex:sectionIndex]);
7741 NSInteger row([path row]);
7742 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7745 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7746 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7748 cell = [[[PackageCell alloc] init] autorelease];
7750 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7751 [cell setPackage:package asSummary:false];
7755 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7756 Package *package([self packageAtIndexPath:path]);
7757 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[NSString stringWithFormat:@"%@/#!/changes/", UI_]] autorelease]);
7758 [view setDelegate:delegate_];
7759 [[self navigationController] pushViewController:view animated:YES];
7763 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7764 NSString *context([alert context]);
7766 if ([context isEqualToString:@"norefresh"])
7767 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7770 - (void) refreshButtonClicked {
7771 if (IsReachable("cydia.saurik.com")) {
7772 [delegate_ beginUpdate];
7773 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7775 UIAlertView *alert = [[[UIAlertView alloc]
7776 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
7777 message:@"Host Unreachable" // XXX: Localize
7779 cancelButtonTitle:UCLocalize("OK")
7780 otherButtonTitles:nil
7783 [alert setContext:@"norefresh"];
7788 - (void) upgradeButtonClicked {
7789 [delegate_ distUpgrade];
7790 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7794 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7795 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7796 [self setView:view];
7798 list_ = [[[UITableView alloc] initWithFrame:[view bounds] style:UITableViewStylePlain] autorelease];
7799 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7800 [list_ setRowHeight:73];
7801 [(UITableView *) list_ setDataSource:self];
7802 [list_ setDelegate:self];
7803 [view addSubview:list_];
7805 if (AprilFools_ && kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
7806 CGRect dickframe([view bounds]);
7807 dickframe.size.height = 44;
7809 dickbar_ = [[[CyteWebView alloc] initWithFrame:dickframe] autorelease];
7810 [dickbar_ setDelegate:self];
7811 [view addSubview:dickbar_];
7813 [dickbar_ setBackgroundColor:[UIColor clearColor]];
7814 [dickbar_ setScalesPageToFit:YES];
7816 UIWebDocumentView *document([dickbar_ _documentView]);
7817 [document setBackgroundColor:[UIColor clearColor]];
7818 [document setDrawsBackground:NO];
7820 WebView *webview([document webView]);
7821 [webview setShouldUpdateWhileOffscreen:NO];
7823 UIScrollView *scroller([dickbar_ scrollView]);
7824 [scroller setScrollingEnabled:NO];
7825 [scroller setFixedBackgroundPattern:YES];
7826 [scroller setBackgroundColor:[UIColor clearColor]];
7828 WebPreferences *preferences([webview preferences]);
7829 [preferences setCacheModel:WebCacheModelDocumentBrowser];
7830 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
7831 [preferences setOfflineWebApplicationCacheEnabled:YES];
7833 [dickbar_ loadRequest:[NSURLRequest
7834 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/dickbar/", UI_]]]
7835 cachePolicy:NSURLRequestUseProtocolCachePolicy
7839 UIEdgeInsets inset = {44, 0, 0, 0};
7840 [list_ setContentInset:inset];
7842 [dickbar_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7846 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7847 NSURL *url([request URL]);
7851 if ([frame isEqualToString:@"_open"])
7852 [delegate_ openURL:url];
7854 WebFrame *frame(nil);
7855 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7856 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7858 frame = [view mainFrame];
7860 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7862 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7863 [controller setDelegate:delegate_];
7864 [[self navigationController] pushViewController:controller animated:YES];
7870 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7871 return [CydiaWebViewController requestWithHeaders:request];
7874 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7875 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7878 - (void) setDelegate:(id)delegate {
7879 [super setDelegate:delegate];
7880 [cydia_ setDelegate:delegate];
7883 - (void) viewDidLoad {
7884 [super viewDidLoad];
7886 [[self navigationItem] setTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES"))];
7889 - (void) releaseSubviews {
7896 [super releaseSubviews];
7899 - (id) initWithDatabase:(Database *)database {
7900 if ((self = [super init]) != nil) {
7901 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7902 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7903 database_ = database;
7907 - (NSMutableArray *) _reloadPackages {
7908 @synchronized (database_) {
7909 era_ = [database_ era];
7910 NSArray *packages([database_ packages]);
7912 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7915 _profile(ChangesController$_reloadPackages$Filter)
7916 for (Package *package in packages)
7917 if ([package upgradableAndEssential:YES] || [package visible])
7918 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7921 _profile(ChangesController$_reloadPackages$radixSort)
7922 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7929 - (void) _reloadData {
7930 NSMutableArray *packages;
7934 UIProgressHUD *hud([delegate_ addProgressHUD]);
7935 [hud setText:UCLocalize("LOADING")];
7936 //NSLog(@"HUD:%@::%@", delegate_, hud);
7937 packages = [self yieldToSelector:@selector(_reloadPackages)];
7938 [delegate_ removeProgressHUD:hud];
7940 packages = [self _reloadPackages];
7943 @synchronized (database_) {
7944 if (era_ != [database_ era])
7947 packages_ = packages;
7948 sections_ = [NSMutableArray arrayWithCapacity:16];
7950 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7951 Section *ignored = nil;
7952 Section *section = nil;
7956 bool unseens = false;
7958 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7960 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7961 Package *package = [packages_ objectAtIndex:offset];
7963 BOOL uae = [package upgradableAndEssential:YES];
7967 time_t seen([package seen]);
7969 if (section == nil || last != seen) {
7973 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7976 _profile(ChangesController$reloadData$Allocate)
7977 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7978 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7979 [sections_ addObject:section];
7983 [section addToCount];
7984 } else if ([package ignored]) {
7985 if (ignored == nil) {
7986 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7988 [ignored addToCount];
7991 [upgradable addToCount];
7996 CFRelease(formatter);
7999 Section *last = [sections_ lastObject];
8000 size_t count = [last count];
8001 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
8002 [sections_ removeLastObject];
8005 if ([ignored count] != 0)
8006 [sections_ insertObject:ignored atIndex:0];
8008 [sections_ insertObject:upgradable atIndex:0];
8012 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
8013 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
8014 style:UIBarButtonItemStylePlain
8016 action:@selector(upgradeButtonClicked)
8017 ] autorelease]) animated:YES];
8019 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
8020 initWithTitle:UCLocalize("REFRESH")
8021 style:UIBarButtonItemStylePlain
8023 action:@selector(refreshButtonClicked)
8024 ] autorelease]) animated:YES];
8029 - (void) reloadData {
8031 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
8036 /* Search Controller {{{ */
8037 @interface SearchController : FilteredPackageListController <
8040 _H<UISearchBar, 1> search_;
8044 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
8045 - (void) reloadData;
8049 @implementation SearchController
8051 - (NSURL *) referrerURL {
8052 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
8055 - (NSURL *) navigationURL {
8056 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
8057 return [NSURL URLWithString:@"cydia://search"];
8059 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
8062 - (NSArray *) termsForQuery:(NSString *)query {
8063 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
8064 for (NSString *component in [query componentsSeparatedByString:@" "])
8065 if ([component length] != 0)
8066 [terms addObject:component];
8071 - (void) useSearch {
8072 [self setObject:[self termsForQuery:[search_ text]] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
8077 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
8078 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8083 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
8084 [search_ resignFirstResponder];
8088 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
8089 [search_ setText:@""];
8090 [self searchBarButtonClicked:searchBar];
8093 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
8094 [self searchBarButtonClicked:searchBar];
8097 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
8098 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8102 - (bool) shouldYield {
8106 - (bool) shouldBlock {
8107 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
8110 - (bool) isSummarized {
8111 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
8114 - (bool) showsSections {
8118 - (NSMutableArray *) _reloadPackages {
8119 NSMutableArray *packages([super _reloadPackages]);
8120 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8121 [packages radixSortUsingSelector:@selector(rank)];
8125 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
8126 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[self termsForQuery:query]])) {
8127 search_ = [[[UISearchBar alloc] init] autorelease];
8128 [search_ setDelegate:self];
8131 [search_ setText:query];
8135 - (void) viewDidAppear:(BOOL)animated {
8136 [super viewDidAppear:animated];
8138 if (!searchloaded_) {
8139 searchloaded_ = YES;
8140 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
8141 [search_ layoutSubviews];
8142 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
8144 UITextField *textField;
8145 if ([search_ respondsToSelector:@selector(searchField)])
8146 textField = [search_ searchField];
8148 textField = MSHookIvar<UITextField *>(search_, "_searchField");
8150 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8151 [textField setEnablesReturnKeyAutomatically:NO];
8152 [[self navigationItem] setTitleView:textField];
8155 if ([self isSummarized])
8156 [search_ becomeFirstResponder];
8159 - (void) reloadData {
8160 id object([search_ text]);
8161 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8162 object = [self termsForQuery:object];
8164 [self setObject:object];
8170 - (void) didSelectPackage:(Package *)package {
8171 [search_ resignFirstResponder];
8172 [super didSelectPackage:package];
8177 /* Package Settings Controller {{{ */
8178 @interface PackageSettingsController : CyteViewController <
8179 UITableViewDataSource,
8182 _transient Database *database_;
8184 _H<Package> package_;
8185 _H<UITableView, 2> table_;
8186 _H<UISwitch> subscribedSwitch_;
8187 _H<UISwitch> ignoredSwitch_;
8188 _H<UITableViewCell> subscribedCell_;
8189 _H<UITableViewCell> ignoredCell_;
8192 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
8196 @implementation PackageSettingsController
8198 - (NSURL *) navigationURL {
8199 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
8202 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8203 if (package_ == nil)
8206 if ([package_ installed] == nil)
8212 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8213 if (package_ == nil)
8216 // both sections contain just one item right now.
8220 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8224 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8226 return UCLocalize("SHOW_ALL_CHANGES_EX");
8228 return UCLocalize("IGNORE_UPGRADES_EX");
8231 - (void) onSubscribed:(id)control {
8232 bool value([control isOn]);
8233 if (package_ == nil)
8235 if ([package_ setSubscribed:value])
8236 [delegate_ updateData];
8239 - (void) _updateIgnored {
8240 const char *package([name_ UTF8String]);
8241 bool on([ignoredSwitch_ isOn]);
8243 pid_t pid(ExecFork());
8245 FILE *dpkg(popen("dpkg --set-selections", "w"));
8246 fwrite(package, strlen(package), 1, dpkg);
8249 fwrite(" hold\n", 6, 1, dpkg);
8251 fwrite(" install\n", 9, 1, dpkg);
8262 - (void) onIgnored:(id)control {
8263 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8264 [invocation setTarget:self];
8265 [invocation setSelector:@selector(_updateIgnored)];
8267 [delegate_ reloadDataWithInvocation:invocation];
8270 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8271 if (package_ == nil)
8274 switch ([indexPath section]) {
8275 case 0: return subscribedCell_;
8276 case 1: return ignoredCell_;
8285 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8286 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8287 [self setView:view];
8289 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8290 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8291 [(UITableView *) table_ setDataSource:self];
8292 [table_ setDelegate:self];
8293 [view addSubview:table_];
8295 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8296 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8297 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8299 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8300 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8301 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8303 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8304 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8305 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8306 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8308 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8309 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8310 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8311 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8314 - (void) viewDidLoad {
8315 [super viewDidLoad];
8317 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8320 - (void) releaseSubviews {
8322 subscribedCell_ = nil;
8324 ignoredSwitch_ = nil;
8325 subscribedSwitch_ = nil;
8327 [super releaseSubviews];
8330 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8331 if ((self = [super init]) != nil) {
8332 database_ = database;
8337 - (void) reloadData {
8340 package_ = [database_ packageWithName:name_];
8342 if (package_ != nil) {
8343 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8344 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8345 } // XXX: what now, G?
8347 [table_ reloadData];
8353 /* Installed Controller {{{ */
8354 @interface InstalledController : FilteredPackageListController {
8358 - (id) initWithDatabase:(Database *)database;
8360 - (void) updateRoleButton;
8361 - (void) queueStatusDidChange;
8365 @implementation InstalledController
8367 - (NSURL *) referrerURL {
8368 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8371 - (NSURL *) navigationURL {
8372 return [NSURL URLWithString:@"cydia://installed"];
8375 - (id) initWithDatabase:(Database *)database {
8376 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8377 [self updateRoleButton];
8378 [self queueStatusDidChange];
8383 - (void) queueButtonClicked {
8388 - (void) queueStatusDidChange {
8392 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8393 initWithTitle:UCLocalize("QUEUE")
8394 style:UIBarButtonItemStyleDone
8396 action:@selector(queueButtonClicked)
8399 [[self navigationItem] setLeftBarButtonItem:nil];
8405 - (void) updateRoleButton {
8406 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8407 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8408 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8409 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8411 action:@selector(roleButtonClicked)
8415 - (void) roleButtonClicked {
8416 [self setObject:[NSNumber numberWithBool:expert_]];
8420 [self updateRoleButton];
8426 /* Source Cell {{{ */
8427 @interface SourceCell : CyteTableViewCell <
8428 CyteTableViewCellDelegate
8432 _H<NSString> origin_;
8433 _H<NSString> label_;
8436 - (void) setSource:(Source *)source;
8440 @implementation SourceCell
8442 - (void) _setImage:(NSArray *)data {
8443 if ([url_ isEqual:[data objectAtIndex:0]]) {
8444 icon_ = [data objectAtIndex:1];
8445 [content_ setNeedsDisplay];
8449 - (void) _setSource:(NSURL *) url {
8450 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8452 if (NSData *data = [NSURLConnection
8453 sendSynchronousRequest:[NSURLRequest
8455 cachePolicy:NSURLRequestUseProtocolCachePolicy
8459 returningResponse:NULL
8462 if (UIImage *image = [UIImage imageWithData:data])
8463 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8468 - (void) setSource:(Source *)source {
8469 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8471 origin_ = [source name];
8472 label_ = [source rooturi];
8474 [content_ setNeedsDisplay];
8476 url_ = [source iconURL];
8477 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8480 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8481 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8482 UIView *content([self contentView]);
8483 CGRect bounds([content bounds]);
8485 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8486 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8487 [content_ setBackgroundColor:[UIColor whiteColor]];
8488 [content addSubview:content_];
8490 [content_ setDelegate:self];
8491 [content_ setOpaque:YES];
8493 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8497 - (NSString *) accessibilityLabel {
8501 - (void) drawContentRect:(CGRect)rect {
8502 bool highlighted(highlighted_);
8503 float width(rect.size.width);
8507 rect.size = [(UIImage *) icon_ size];
8509 while (rect.size.width > 32 || rect.size.height > 32) {
8510 rect.size.width /= 2;
8511 rect.size.height /= 2;
8514 rect.origin.x = 26 - rect.size.width / 2;
8515 rect.origin.y = 26 - rect.size.height / 2;
8517 [icon_ drawInRect:rect];
8520 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8525 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 61) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8529 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 61) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8534 /* Source Controller {{{ */
8535 @interface SourceController : FilteredPackageListController {
8536 _transient Source *source_;
8540 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8544 @implementation SourceController
8546 - (NSURL *) referrerURL {
8547 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sources/%@", UI_, [key_ stringByAddingPercentEscapesIncludingReserved]]];
8550 - (NSURL *) navigationURL {
8551 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8554 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8555 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8557 key_ = [source key];
8561 - (void) reloadData {
8562 source_ = [database_ sourceWithKey:key_];
8563 key_ = [source_ key];
8564 [self setObject:source_];
8566 [[self navigationItem] setTitle:[source_ label]];
8573 /* Sources Controller {{{ */
8574 @interface SourcesController : CyteViewController <
8575 UITableViewDataSource,
8578 _transient Database *database_;
8581 _H<UITableView, 2> list_;
8582 _H<NSMutableArray> sources_;
8586 _H<UIProgressHUD> hud_;
8589 //NSURLConnection *installer_;
8590 NSURLConnection *trivial_bz2_;
8591 NSURLConnection *trivial_gz_;
8592 //NSURLConnection *automatic_;
8597 - (id) initWithDatabase:(Database *)database;
8598 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8602 @implementation SourcesController
8604 - (void) _releaseConnection:(NSURLConnection *)connection {
8605 if (connection != nil) {
8606 [connection cancel];
8607 //[connection setDelegate:nil];
8608 [connection release];
8613 //[self _releaseConnection:installer_];
8614 [self _releaseConnection:trivial_gz_];
8615 [self _releaseConnection:trivial_bz2_];
8616 //[self _releaseConnection:automatic_];
8621 - (NSURL *) navigationURL {
8622 return [NSURL URLWithString:@"cydia://sources"];
8625 - (void) viewDidAppear:(BOOL)animated {
8626 [super viewDidAppear:animated];
8627 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8630 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8634 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8638 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8639 return [sources_ count];
8642 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8643 @synchronized (database_) {
8644 if ([database_ era] != era_)
8647 NSUInteger index([indexPath row]);
8648 return index < [sources_ count] ? [sources_ objectAtIndex:index] : nil;
8651 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8652 static NSString *cellIdentifier = @"SourceCell";
8654 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8655 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8656 [cell setSource:[self sourceAtIndexPath:indexPath]];
8657 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8662 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8663 Source *source = [self sourceAtIndexPath:indexPath];
8664 if (source == nil) return;
8666 SourceController *controller = [[[SourceController alloc]
8667 initWithDatabase:database_
8671 [controller setDelegate:delegate_];
8673 [[self navigationController] pushViewController:controller animated:YES];
8676 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8677 Source *source = [self sourceAtIndexPath:indexPath];
8678 return [source record] != nil;
8681 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8682 if (editingStyle == UITableViewCellEditingStyleDelete) {
8683 Source *source = [self sourceAtIndexPath:indexPath];
8684 if (source == nil) return;
8686 [Sources_ removeObjectForKey:[source key]];
8689 [delegate_ _saveConfig];
8690 [delegate_ reloadDataWithInvocation:nil];
8695 [delegate_ addTrivialSource:href_];
8698 [delegate_ syncData];
8701 - (NSString *) getWarning {
8702 NSString *href(href_);
8703 NSRange colon([href rangeOfString:@"://"]);
8704 if (colon.location != NSNotFound)
8705 href = [href substringFromIndex:(colon.location + 3)];
8706 href = [href stringByAddingPercentEscapes];
8707 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8709 NSURL *url([NSURL URLWithString:href]);
8711 NSStringEncoding encoding;
8712 NSError *error(nil);
8714 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8715 return [warning length] == 0 ? nil : warning;
8719 - (void) _endConnection:(NSURLConnection *)connection {
8720 // XXX: the memory management in this method is horribly awkward
8722 NSURLConnection **field = NULL;
8723 if (connection == trivial_bz2_)
8724 field = &trivial_bz2_;
8725 else if (connection == trivial_gz_)
8726 field = &trivial_gz_;
8727 _assert(field != NULL);
8728 [connection release];
8732 trivial_bz2_ == nil &&
8735 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8737 [delegate_ releaseNetworkActivityIndicator];
8739 [delegate_ removeProgressHUD:hud_];
8743 if (warning != nil) {
8744 UIAlertView *alert = [[[UIAlertView alloc]
8745 initWithTitle:UCLocalize("SOURCE_WARNING")
8748 cancelButtonTitle:UCLocalize("CANCEL")
8750 UCLocalize("ADD_ANYWAY"),
8754 [alert setContext:@"warning"];
8755 [alert setNumberOfRows:1];
8758 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8764 } else if (error_ != nil) {
8765 UIAlertView *alert = [[[UIAlertView alloc]
8766 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8767 message:[error_ localizedDescription]
8769 cancelButtonTitle:UCLocalize("OK")
8770 otherButtonTitles:nil
8773 [alert setContext:@"urlerror"];
8778 UIAlertView *alert = [[[UIAlertView alloc]
8779 initWithTitle:UCLocalize("NOT_REPOSITORY")
8780 message:UCLocalize("NOT_REPOSITORY_EX")
8782 cancelButtonTitle:UCLocalize("OK")
8783 otherButtonTitles:nil
8786 [alert setContext:@"trivial"];
8796 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8797 switch ([response statusCode]) {
8803 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8804 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8806 [self _endConnection:connection];
8809 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8810 [self _endConnection:connection];
8813 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8814 NSURL *url([NSURL URLWithString:href]);
8816 NSMutableURLRequest *request = [NSMutableURLRequest
8818 cachePolicy:NSURLRequestUseProtocolCachePolicy
8822 [request setHTTPMethod:method];
8824 if (Machine_ != NULL)
8825 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8827 if (UniqueID_ != nil)
8828 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8830 if ([url isCydiaSecure]) {
8831 if (UniqueID_ != nil)
8832 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8835 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8838 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8839 NSString *context([alert context]);
8841 if ([context isEqualToString:@"source"]) {
8844 NSString *href = [[alert textField] text];
8846 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8848 if (![href hasSuffix:@"/"])
8849 href_ = [href stringByAppendingString:@"/"];
8853 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8854 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8855 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8859 // XXX: this is stupid
8860 hud_ = [delegate_ addProgressHUD];
8861 [hud_ setText:UCLocalize("VERIFYING_URL")];
8862 [delegate_ retainNetworkActivityIndicator];
8871 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8872 } else if ([context isEqualToString:@"trivial"])
8873 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8874 else if ([context isEqualToString:@"urlerror"])
8875 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8876 else if ([context isEqualToString:@"warning"]) {
8879 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8888 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8893 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8894 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8895 [list_ setRowHeight:53];
8896 [(UITableView *) list_ setDataSource:self];
8897 [list_ setDelegate:self];
8898 [self setView:list_];
8901 - (void) viewDidLoad {
8902 [super viewDidLoad];
8904 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8905 [self updateButtonsForEditingStatusAnimated:NO];
8908 - (void) viewWillAppear:(BOOL)animated {
8909 [super viewWillAppear:animated];
8911 [list_ setEditing:NO];
8912 [self updateButtonsForEditingStatusAnimated:NO];
8915 - (void) releaseSubviews {
8920 [super releaseSubviews];
8923 - (id) initWithDatabase:(Database *)database {
8924 if ((self = [super init]) != nil) {
8925 database_ = database;
8929 - (void) reloadData {
8932 @synchronized (database_) {
8933 era_ = [database_ era];
8935 sources_ = [NSMutableArray arrayWithCapacity:16];
8936 [sources_ addObjectsFromArray:[database_ sources]];
8938 [sources_ sortUsingSelector:@selector(compareByName:)];
8941 int count([sources_ count]);
8943 for (int i = 0; i != count; i++) {
8944 if ([[sources_ objectAtIndex:i] record] == nil)
8952 - (void) showAddSourcePrompt {
8953 UIAlertView *alert = [[[UIAlertView alloc]
8954 initWithTitle:UCLocalize("ENTER_APT_URL")
8957 cancelButtonTitle:UCLocalize("CANCEL")
8959 UCLocalize("ADD_SOURCE"),
8963 [alert setContext:@"source"];
8965 [alert setNumberOfRows:1];
8966 [alert addTextFieldWithValue:@"http://" label:@""];
8968 UITextInputTraits *traits = [[alert textField] textInputTraits];
8969 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8970 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8971 [traits setKeyboardType:UIKeyboardTypeURL];
8972 // XXX: UIReturnKeyDone
8973 [traits setReturnKeyType:UIReturnKeyNext];
8978 - (void) addButtonClicked {
8979 [self showAddSourcePrompt];
8982 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8983 BOOL editing([list_ isEditing]);
8985 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8986 initWithTitle:UCLocalize("ADD")
8987 style:UIBarButtonItemStylePlain
8989 action:@selector(addButtonClicked)
8990 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8992 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8993 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8994 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8996 action:@selector(editButtonClicked)
8997 ] autorelease] animated:animated];
8999 if (IsWildcat_ && !editing)
9000 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
9001 initWithTitle:UCLocalize("SETTINGS")
9002 style:UIBarButtonItemStylePlain
9004 action:@selector(settingsButtonClicked)
9008 - (void) settingsButtonClicked {
9009 [delegate_ showSettings];
9012 - (void) editButtonClicked {
9013 [list_ setEditing:![list_ isEditing] animated:YES];
9014 [self updateButtonsForEditingStatusAnimated:YES];
9020 /* Settings Controller {{{ */
9021 @interface SettingsController : CyteViewController <
9022 UITableViewDataSource,
9025 _transient Database *database_;
9026 // XXX: ok, "roledelegate_"?...
9027 _transient id roledelegate_;
9028 _H<UITableView, 2> table_;
9029 _H<UISegmentedControl> segment_;
9030 _H<UIView> container_;
9033 - (void) showDoneButton;
9034 - (void) resizeSegmentedControl;
9038 @implementation SettingsController
9041 table_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
9042 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9043 [table_ setDelegate:self];
9044 [(UITableView *) table_ setDataSource:self];
9045 [self setView:table_];
9047 NSArray *items = [NSArray arrayWithObjects:
9049 UCLocalize("HACKER"),
9050 UCLocalize("DEVELOPER"),
9052 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
9053 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
9054 [container_ addSubview:segment_];
9057 - (void) viewDidLoad {
9058 [super viewDidLoad];
9060 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
9063 if ([Role_ isEqualToString:@"User"]) index = 0;
9064 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
9065 if ([Role_ isEqualToString:@"Developer"]) index = 2;
9067 [segment_ setSelectedSegmentIndex:index];
9068 [self showDoneButton];
9071 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
9072 [self resizeSegmentedControl];
9075 - (void) releaseSubviews {
9080 [super releaseSubviews];
9083 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
9084 if ((self = [super init]) != nil) {
9085 database_ = database;
9086 roledelegate_ = delegate;
9090 - (void) resizeSegmentedControl {
9091 CGFloat width = [[self view] frame].size.width;
9092 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
9095 - (void) viewWillAppear:(BOOL)animated {
9096 [super viewWillAppear:animated];
9097 [self resizeSegmentedControl];
9100 - (void) viewDidAppear:(BOOL)animated {
9101 [super viewDidAppear:animated];
9102 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
9103 [self resizeSegmentedControl];
9106 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
9107 [self resizeSegmentedControl];
9110 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
9111 [self resizeSegmentedControl];
9115 NSString *role(nil);
9117 switch ([segment_ selectedSegmentIndex]) {
9118 case 0: role = @"User"; break;
9119 case 1: role = @"Hacker"; break;
9120 case 2: role = @"Developer"; break;
9125 if (![role isEqualToString:Role_]) {
9126 bool rolling(Role_ == nil);
9129 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
9133 [Metadata_ setObject:Settings_ forKey:@"Settings"];
9137 [roledelegate_ loadData];
9139 [roledelegate_ updateData];
9143 - (void) segmentChanged:(UISegmentedControl *)control {
9144 [self showDoneButton];
9147 - (void) saveAndClose {
9150 [[self navigationItem] setRightBarButtonItem:nil];
9151 [[self navigationController] dismissModalViewControllerAnimated:YES];
9154 - (void) doneButtonClicked {
9155 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
9156 [spinner startAnimating];
9157 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
9158 [[self navigationItem] setRightBarButtonItem:spinItem];
9160 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
9163 - (void) showDoneButton {
9164 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
9165 initWithTitle:UCLocalize("DONE")
9166 style:UIBarButtonItemStyleDone
9168 action:@selector(doneButtonClicked)
9169 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
9172 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
9173 // XXX: For not having a single cell in the table, this sure is a lot of sections.
9177 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
9181 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
9182 return nil; // This method is required by the protocol.
9185 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
9187 return UCLocalize("ROLE_EX");
9189 return [NSString stringWithFormat:
9190 @"%@: %@\n%@: %@\n%@: %@",
9191 UCLocalize("USER"), UCLocalize("USER_EX"),
9192 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
9193 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
9198 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
9199 return section == 3 ? 44.0f : 0;
9202 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
9203 return section == 3 ? container_ : nil;
9206 - (void) reloadData {
9209 [table_ reloadData];
9214 /* Stash Controller {{{ */
9215 @interface StashController : CyteViewController {
9216 _H<UIActivityIndicatorView> spinner_;
9217 _H<UILabel> status_;
9218 _H<UILabel> caption_;
9223 @implementation StashController
9226 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
9227 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
9228 [self setView:view];
9230 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
9232 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
9233 CGRect spinrect = [spinner_ frame];
9234 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
9235 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
9236 [spinner_ setFrame:spinrect];
9237 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
9238 [view addSubview:spinner_];
9239 [spinner_ startAnimating];
9242 captrect.size.width = [[self view] frame].size.width;
9243 captrect.size.height = 40.0f;
9244 captrect.origin.x = 0;
9245 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
9246 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
9247 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
9248 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9249 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
9250 [caption_ setTextColor:[UIColor whiteColor]];
9251 [caption_ setBackgroundColor:[UIColor clearColor]];
9252 [caption_ setShadowColor:[UIColor blackColor]];
9253 [caption_ setTextAlignment:UITextAlignmentCenter];
9254 [view addSubview:caption_];
9257 statusrect.size.width = [[self view] frame].size.width;
9258 statusrect.size.height = 30.0f;
9259 statusrect.origin.x = 0;
9260 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
9261 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
9262 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9263 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
9264 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
9265 [status_ setTextColor:[UIColor whiteColor]];
9266 [status_ setBackgroundColor:[UIColor clearColor]];
9267 [status_ setShadowColor:[UIColor blackColor]];
9268 [status_ setTextAlignment:UITextAlignmentCenter];
9269 [view addSubview:status_];
9272 - (void) releaseSubviews {
9277 [super releaseSubviews];
9283 @interface CYURLCache : SDURLCache {
9288 @implementation CYURLCache
9290 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
9293 else if ([event isEqualToString:@"no-cache"])
9295 else if ([event isEqualToString:@"store"])
9297 else if ([event isEqualToString:@"invalid"])
9299 else if ([event isEqualToString:@"memory"])
9301 else if ([event isEqualToString:@"disk"])
9303 else if ([event isEqualToString:@"miss"])
9306 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
9310 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
9311 if (NSURLResponse *response = [cached response])
9312 if (NSString *mime = [response MIMEType])
9313 if ([mime isEqualToString:@"text/cache-manifest"]) {
9314 NSURL *url([response URL]);
9317 NSLog(@"###: %@", [url absoluteString]);
9320 @synchronized (HostConfig_) {
9321 [CachedURLs_ addObject:url];
9325 [super storeCachedResponse:cached forRequest:request];
9330 @interface Cydia : UIApplication <
9331 ConfirmationControllerDelegate,
9334 UINavigationControllerDelegate,
9335 UITabBarControllerDelegate
9337 _H<UIWindow> window_;
9338 _H<CYTabBarController> tabbar_;
9339 _H<CydiaLoadingViewController> emulated_;
9341 _H<NSMutableArray> essential_;
9342 _H<NSMutableArray> broken_;
9344 Database *database_;
9346 _H<NSURL> starturl_;
9351 _H<StashController> stash_;
9360 @implementation Cydia
9362 - (void) lockSuspend {
9363 if (locked_++ == 0) {
9364 if ($SBSSetInterceptsMenuButtonForever != NULL)
9365 (*$SBSSetInterceptsMenuButtonForever)(true);
9367 [self setIdleTimerDisabled:YES];
9371 - (void) unlockSuspend {
9372 if (--locked_ == 0) {
9373 [self setIdleTimerDisabled:NO];
9375 if ($SBSSetInterceptsMenuButtonForever != NULL)
9376 (*$SBSSetInterceptsMenuButtonForever)(false);
9380 - (void) beginUpdate {
9381 [tabbar_ beginUpdate];
9385 return [tabbar_ updating];
9389 if ([broken_ count] != 0) {
9390 int count = [broken_ count];
9392 UIAlertView *alert = [[[UIAlertView alloc]
9393 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9394 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9396 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9398 UCLocalize("TEMPORARY_IGNORE"),
9402 [alert setContext:@"fixhalf"];
9403 [alert setNumberOfRows:2];
9405 } else if (!Ignored_ && [essential_ count] != 0) {
9406 int count = [essential_ count];
9408 UIAlertView *alert = [[[UIAlertView alloc]
9409 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9410 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9412 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9414 UCLocalize("UPGRADE_ESSENTIAL"),
9415 UCLocalize("COMPLETE_UPGRADE"),
9419 [alert setContext:@"upgrade"];
9424 - (void) returnToCydia {
9428 - (void) _saveConfig {
9429 @synchronized (database_) {
9436 NSString *error(nil);
9438 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9440 NSError *error(nil);
9441 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9442 NSLog(@"failure to save metadata data: %@", error);
9447 NSLog(@"failure to serialize metadata: %@", error);
9451 CydiaWriteSources();
9454 // Navigation controller for the queuing badge.
9455 - (UINavigationController *) queueNavigationController {
9456 NSArray *controllers = [tabbar_ viewControllers];
9457 return [controllers objectAtIndex:3];
9460 - (void) unloadData {
9461 [tabbar_ unloadData];
9464 - (void) _updateData {
9468 UINavigationController *navigation = [self queueNavigationController];
9470 id queuedelegate = nil;
9471 if ([[navigation viewControllers] count] > 0)
9472 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9474 [queuedelegate queueStatusDidChange];
9475 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9478 - (void) _refreshIfPossible:(NSDate *)update {
9479 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9481 bool recently = false;
9482 if (update != nil) {
9483 NSTimeInterval interval([update timeIntervalSinceNow]);
9484 if (interval <= 0 && interval > -(15*60))
9488 // Don't automatic refresh if:
9489 // - We already refreshed recently.
9490 // - We already auto-refreshed this launch.
9491 // - Auto-refresh is disabled.
9492 // - Cydia's server is not reachable
9493 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9494 // If we are cancelling, we need to make sure it knows it's already loaded.
9497 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9499 // We are going to load, so remember that.
9502 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9508 - (void) refreshIfPossible {
9509 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9512 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9513 @synchronized (self) {
9514 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9516 [hud setText:UCLocalize("RELOADING_DATA")];
9518 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9522 [essential_ removeAllObjects];
9523 [broken_ removeAllObjects];
9525 NSArray *packages([database_ packages]);
9526 for (Package *package in packages) {
9528 [broken_ addObject:package];
9529 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9530 if ([package essential] && [package installed] != nil)
9531 [essential_ addObject:package];
9536 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9539 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9540 [changesItem setBadgeValue:badge];
9541 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9542 [self setApplicationIconBadgeNumber:changes];
9545 [changesItem setBadgeValue:nil];
9546 [changesItem setAnimatedBadge:NO];
9547 [self setApplicationIconBadgeNumber:0];
9553 [self removeProgressHUD:hud];
9556 - (void) updateData {
9560 - (void) updateDataAndLoad {
9562 if ([database_ progressDelegate] == nil)
9568 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9571 - (void) disemulate {
9572 if (emulated_ == nil)
9575 [window_ addSubview:[tabbar_ view]];
9576 [[emulated_ view] removeFromSuperview];
9578 [window_ setUserInteractionEnabled:YES];
9581 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9582 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9584 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9586 UIViewController *parent;
9587 if (emulated_ == nil)
9596 [parent presentModalViewController:navigation animated:YES];
9599 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9600 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9602 if (navigation != nil)
9603 [navigation pushViewController:progress animated:YES];
9605 [self presentModalViewController:progress force:YES];
9607 [progress invoke:invocation withTitle:title];
9611 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9612 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9615 - (void) repairWithInvocation:(NSInvocation *)invocation {
9617 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9621 - (void) repairWithSelector:(SEL)selector {
9622 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9625 - (void) reloadData {
9626 [self reloadDataWithInvocation:nil];
9627 if ([database_ progressDelegate] == nil)
9633 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9636 - (void) addSource:(NSDictionary *) source {
9637 CydiaAddSource(source);
9640 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9641 CydiaAddSource(href, distribution, sections);
9644 - (void) addTrivialSource:(NSString *)href {
9645 CydiaAddSource(href, @"./");
9648 - (void) updateValues {
9653 pkgProblemResolver *resolver = [database_ resolver];
9655 resolver->InstallProtect();
9656 if (!resolver->Resolve(true))
9661 // XXX: this is a really crappy way of doing this.
9662 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9663 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9664 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9665 if ([tabbar_ updating])
9666 [tabbar_ cancelUpdate];
9668 if (![database_ prepare])
9671 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9672 [page setDelegate:self];
9673 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9676 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9677 [tabbar_ presentModalViewController:confirm_ animated:YES];
9683 @synchronized (self) {
9688 - (void) clearPackage:(Package *)package {
9689 @synchronized (self) {
9696 - (void) installPackages:(NSArray *)packages {
9697 @synchronized (self) {
9698 for (Package *package in packages)
9705 - (void) installPackage:(Package *)package {
9706 @synchronized (self) {
9713 - (void) removePackage:(Package *)package {
9714 @synchronized (self) {
9721 - (void) distUpgrade {
9722 @synchronized (self) {
9723 if (![database_ upgrade])
9731 system("su -c /usr/bin/uicache mobile");
9736 UIProgressHUD *hud([self addProgressHUD]);
9737 [hud setText:UCLocalize("LOADING")];
9738 [self yieldToSelector:@selector(_uicache)];
9739 [self removeProgressHUD:hud];
9743 [database_ perform];
9744 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9745 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9748 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9751 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9752 [self unlockSuspend];
9755 - (void) showSettings {
9756 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9759 - (void) retainNetworkActivityIndicator {
9760 if (activity_++ == 0)
9761 [self setNetworkActivityIndicatorVisible:YES];
9764 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9768 - (void) releaseNetworkActivityIndicator {
9769 if (--activity_ == 0)
9770 [self setNetworkActivityIndicatorVisible:NO];
9773 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9778 - (void) cancelAndClear:(bool)clear {
9779 @synchronized (self) {
9791 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9792 NSString *context([alert context]);
9794 if ([context isEqualToString:@"conffile"]) {
9795 FILE *input = [database_ input];
9796 if (button == [alert cancelButtonIndex])
9797 fprintf(input, "N\n");
9798 else if (button == [alert firstOtherButtonIndex])
9799 fprintf(input, "Y\n");
9802 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9803 } else if ([context isEqualToString:@"fixhalf"]) {
9804 if (button == [alert cancelButtonIndex]) {
9805 @synchronized (self) {
9806 for (Package *broken in (id) broken_) {
9809 NSString *id = [broken id];
9810 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9811 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9812 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9813 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9819 } else if (button == [alert firstOtherButtonIndex]) {
9820 [broken_ removeAllObjects];
9824 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9825 } else if ([context isEqualToString:@"upgrade"]) {
9826 if (button == [alert firstOtherButtonIndex]) {
9827 @synchronized (self) {
9828 for (Package *essential in (id) essential_)
9829 [essential install];
9834 } else if (button == [alert firstOtherButtonIndex] + 1) {
9836 } else if (button == [alert cancelButtonIndex]) {
9840 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9844 - (void) system:(NSString *)command {
9845 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9848 system([command UTF8String]);
9854 - (void) applicationWillSuspend {
9856 [super applicationWillSuspend];
9859 - (BOOL) isSafeToSuspend {
9862 NSLog(@"isSafeToSuspend: locked_ != 0");
9867 // Use external process status API internally.
9868 // This is probably a really bad idea.
9869 // XXX: what is the point of this? does this solve anything at all?
9870 uint64_t status = 0;
9872 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9873 notify_get_state(notify_token, &status);
9874 notify_cancel(notify_token);
9879 NSLog(@"isSafeToSuspend: status != 0");
9885 NSLog(@"isSafeToSuspend: -> true");
9890 - (void) applicationSuspend:(__GSEvent *)event {
9891 if ([self isSafeToSuspend])
9892 [super applicationSuspend:event];
9895 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9896 if ([self isSafeToSuspend])
9897 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9900 - (void) _setSuspended:(BOOL)value {
9901 if ([self isSafeToSuspend])
9902 [super _setSuspended:value];
9905 - (UIProgressHUD *) addProgressHUD {
9906 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9907 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9909 [window_ setUserInteractionEnabled:NO];
9911 UIViewController *target(tabbar_);
9912 if (UIViewController *modal = [target modalViewController])
9915 [hud showInView:[target view]];
9921 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9922 [self unlockSuspend];
9924 [hud removeFromSuperview];
9925 [window_ setUserInteractionEnabled:YES];
9928 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9929 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9932 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9933 NSString *scheme([[url scheme] lowercaseString]);
9934 if ([[url absoluteString] length] <= [scheme length] + 3)
9936 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9937 NSArray *components([path componentsSeparatedByString:@"/"]);
9939 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9940 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9941 if (controller != nil)
9942 [controller setDelegate:self];
9946 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9949 NSString *base([components objectAtIndex:0]);
9951 CyteViewController *controller = nil;
9953 if ([base isEqualToString:@"url"]) {
9954 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9955 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9956 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9957 } else if (!external && [components count] == 1) {
9958 if ([base isEqualToString:@"manage"]) {
9959 controller = [[[ManageController alloc] init] autorelease];
9962 if ([base isEqualToString:@"storage"]) {
9963 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9966 if ([base isEqualToString:@"sources"]) {
9967 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9970 if ([base isEqualToString:@"home"]) {
9971 controller = [[[HomeController alloc] init] autorelease];
9974 if ([base isEqualToString:@"sections"]) {
9975 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9978 if ([base isEqualToString:@"search"]) {
9979 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9982 if ([base isEqualToString:@"changes"]) {
9983 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9986 if ([base isEqualToString:@"installed"]) {
9987 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9989 } else if ([components count] == 2) {
9990 NSString *argument = [components objectAtIndex:1];
9992 if ([base isEqualToString:@"package"]) {
9993 controller = [self pageForPackage:argument withReferrer:referrer];
9996 if (!external && [base isEqualToString:@"search"]) {
9997 controller = [[[SearchController alloc] initWithDatabase:database_ query:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
10000 if (!external && [base isEqualToString:@"sections"]) {
10001 if ([argument isEqualToString:@"all"])
10003 controller = [[[SectionController alloc] initWithDatabase:database_ section:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
10006 if (!external && [base isEqualToString:@"sources"]) {
10007 if ([argument isEqualToString:@"add"]) {
10008 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
10009 [(SourcesController *)controller showAddSourcePrompt];
10011 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
10012 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
10016 if (!external && [base isEqualToString:@"launch"]) {
10017 [self launchApplicationWithIdentifier:argument suspended:NO];
10020 } else if (!external && [components count] == 3) {
10021 NSString *arg1 = [components objectAtIndex:1];
10022 NSString *arg2 = [components objectAtIndex:2];
10024 if ([base isEqualToString:@"package"]) {
10025 if ([arg2 isEqualToString:@"settings"]) {
10026 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
10027 } else if ([arg2 isEqualToString:@"files"]) {
10028 if (Package *package = [database_ packageWithName:arg1]) {
10029 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
10030 [(FileTable *)controller setPackage:package];
10036 [controller setDelegate:self];
10040 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
10041 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
10044 [tabbar_ setUnselectedViewController:page];
10046 return page != nil;
10049 - (void) applicationOpenURL:(NSURL *)url {
10050 [super applicationOpenURL:url];
10055 [self openCydiaURL:url forExternal:YES];
10058 - (void) applicationWillResignActive:(UIApplication *)application {
10059 // Stop refreshing if you get a phone call or lock the device.
10060 if ([tabbar_ updating])
10061 [tabbar_ cancelUpdate];
10063 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
10064 [super applicationWillResignActive:application];
10067 - (void) saveState {
10068 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
10069 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
10070 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
10073 [self _saveConfig];
10076 - (void) applicationWillTerminate:(UIApplication *)application {
10080 - (void) setConfigurationData:(NSString *)data {
10081 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
10083 if (!conffile_r(data)) {
10084 lprintf("E:invalid conffile\n");
10088 NSString *ofile = conffile_r[1];
10089 //NSString *nfile = conffile_r[2];
10091 UIAlertView *alert = [[[UIAlertView alloc]
10092 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
10093 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
10095 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
10097 UCLocalize("ACCEPT_NEW_COPY"),
10098 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
10102 [alert setContext:@"conffile"];
10103 [alert setNumberOfRows:2];
10107 - (void) addStashController {
10108 [self lockSuspend];
10109 stash_ = [[[StashController alloc] init] autorelease];
10110 [window_ addSubview:[stash_ view]];
10113 - (void) removeStashController {
10114 [[stash_ view] removeFromSuperview];
10116 [self unlockSuspend];
10120 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
10121 UpdateExternalStatus(1);
10122 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
10123 UpdateExternalStatus(0);
10125 [self removeStashController];
10127 pid_t pid(ExecFork());
10129 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
10130 perror("launchctl stop");
10137 - (void) setupViewControllers {
10138 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
10140 NSMutableArray *items;
10141 if (kCFCoreFoundationVersionNumber < 800) {
10142 items = [NSMutableArray arrayWithObjects:
10143 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
10144 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
10145 [[[UITabBarItem alloc] initWithTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES")) image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
10146 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
10150 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
10151 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10153 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10156 items = [NSMutableArray arrayWithObjects:
10157 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home7.png"] selectedImage:[UIImage applicationImageNamed:@"home7s.png"]] autorelease],
10158 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install7.png"] selectedImage:[UIImage applicationImageNamed:@"install7s.png"]] autorelease],
10159 [[[UITabBarItem alloc] initWithTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES")) image:[UIImage applicationImageNamed:@"changes7.png"] selectedImage:[UIImage applicationImageNamed:@"changes7s.png"]] autorelease],
10160 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search7.png"] selectedImage:[UIImage applicationImageNamed:@"search7s.png"]] autorelease],
10164 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source7.png"] selectedImage:[UIImage applicationImageNamed:@"source7s.png"]] autorelease] atIndex:3];
10165 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage7.png"] selectedImage:[UIImage applicationImageNamed:@"manage7s.png"]] autorelease] atIndex:3];
10167 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage7.png"] selectedImage:[UIImage applicationImageNamed:@"manage7s.png"]] autorelease] atIndex:3];
10171 NSMutableArray *controllers([NSMutableArray array]);
10172 for (UITabBarItem *item in items) {
10173 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
10174 [controller setTabBarItem:item];
10175 [controllers addObject:controller];
10177 [tabbar_ setViewControllers:controllers];
10179 [tabbar_ setUpdateDelegate:self];
10182 - (void) _sendMemoryWarningNotification {
10183 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
10184 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
10186 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
10189 - (void) _sendMemoryWarningNotifications {
10191 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
10197 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
10199 [[NSURLCache sharedURLCache] removeAllCachedResponses];
10202 - (void) applicationDidFinishLaunching:(id)unused {
10203 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
10206 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
10207 [self setApplicationSupportsShakeToEdit:NO];
10209 @synchronized (HostConfig_) {
10210 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
10213 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
10214 initWithMemoryCapacity:524288
10215 diskCapacity:10485760
10216 diskPath:[NSString stringWithFormat:@"%@/SDURLCache", Cache_]
10219 [CydiaWebViewController _initialize];
10221 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
10223 // this would disallow http{,s} URLs from accessing this data
10224 //[WebView registerURLSchemeAsLocal:@"cydia"];
10226 Font12_ = [UIFont systemFontOfSize:12];
10227 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
10228 Font14_ = [UIFont systemFontOfSize:14];
10229 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
10230 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
10232 essential_ = [NSMutableArray arrayWithCapacity:4];
10233 broken_ = [NSMutableArray arrayWithCapacity:4];
10235 // XXX: I really need this thing... like, seriously... I'm sorry
10236 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
10238 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
10239 [window_ orderFront:self];
10240 [window_ makeKey:self];
10241 [window_ setHidden:NO];
10243 if (false) stash: {
10244 [self addStashController];
10245 // XXX: this would be much cleaner as a yieldToSelector:
10246 // that way the removeStashController could happen right here inline
10247 // we also could no longer require the useless stash_ field anymore
10248 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
10253 int error(stat("/", &root));
10254 _assert(error != -1);
10256 #define Stash_(path) do { \
10257 struct stat folder; \
10258 int error(lstat((path), &folder)); \
10259 if (error != -1 && ( \
10260 folder.st_dev == root.st_dev && \
10261 S_ISDIR(folder.st_mode) \
10262 ) || error == -1 && ( \
10263 errno == ENOENT || \
10268 Stash_("/Applications");
10269 Stash_("/Library/Ringtones");
10270 Stash_("/Library/Wallpaper");
10271 //Stash_("/usr/bin");
10272 Stash_("/usr/include");
10273 Stash_("/usr/lib/pam");
10274 Stash_("/usr/libexec");
10275 Stash_("/usr/share");
10276 //Stash_("/var/lib");
10278 database_ = [Database sharedInstance];
10279 [database_ setDelegate:self];
10281 [window_ setUserInteractionEnabled:NO];
10282 [self setupViewControllers];
10284 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
10285 [window_ addSubview:[emulated_ view]];
10287 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
10291 - (NSArray *) defaultStartPages {
10292 NSMutableArray *standard = [NSMutableArray array];
10293 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
10294 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
10295 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
10297 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
10299 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
10300 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
10302 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10306 - (void) loadData {
10308 if (Role_ == nil) {
10309 [window_ setUserInteractionEnabled:YES];
10310 [self showSettings];
10313 if ([emulated_ modalViewController] != nil)
10314 [emulated_ dismissModalViewControllerAnimated:YES];
10315 [window_ setUserInteractionEnabled:NO];
10318 [self reloadDataWithInvocation:nil];
10319 [self refreshIfPossible];
10324 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
10325 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
10326 int standardIndex = 0;
10327 NSArray *standard = [self defaultStartPages];
10334 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
10335 if (valid && closed != nil) {
10336 NSTimeInterval interval([closed timeIntervalSinceNow]);
10337 // XXX: Is 30 minutes the optimal time here?
10338 if (interval <= -(30*60))
10342 if (valid && [saved count] != [standard count])
10346 for (unsigned int i = 0; i < [standard count]; i++) {
10347 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10348 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10349 // but it's good enough for now.
10350 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10357 NSArray *items = nil;
10359 [tabbar_ setSelectedIndex:savedIndex];
10362 [tabbar_ setSelectedIndex:standardIndex];
10366 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10367 NSArray *stack = [items objectAtIndex:tab];
10368 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10369 NSMutableArray *current = [NSMutableArray array];
10371 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10372 NSString *addr = [stack objectAtIndex:nav];
10373 NSURL *url = [NSURL URLWithString:addr];
10374 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10376 [current addObject:page];
10379 [navigation setViewControllers:current];
10382 // (Try to) show the startup URL.
10383 if (starturl_ != nil) {
10384 [self openCydiaURL:starturl_ forExternal:NO];
10389 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10390 if (item != nil && IsWildcat_) {
10391 [sheet showFromBarButtonItem:item animated:YES];
10393 [sheet showInView:window_];
10397 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10398 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10399 [progress setTitle:task];
10400 [progress addProgressEvent:event];
10403 - (void) addProgressEventForTask:(NSArray *)data {
10404 CydiaProgressEvent *event([data objectAtIndex:0]);
10405 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10406 [self addProgressEvent:event forTask:task];
10409 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10410 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10416 id Alloc_(id self, SEL selector) {
10417 id object = alloc_(self, selector);
10418 lprintf("[%s]A-%p\n", self->isa->name, object);
10423 id Dealloc_(id self, SEL selector) {
10424 id object = dealloc_(self, selector);
10425 lprintf("[%s]D-%p\n", self->isa->name, object);
10429 static NSSet *MobilizedFiles_;
10431 static NSURL *MobilizeURL(NSURL *url) {
10432 NSString *path([url path]);
10433 if ([path hasPrefix:@"/var/root/"]) {
10434 NSString *file([path substringFromIndex:10]);
10435 if ([MobilizedFiles_ containsObject:file])
10436 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10442 Class $CFXPreferencesPropertyListSource;
10443 @class CFXPreferencesPropertyListSource;
10445 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10446 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10447 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10448 url = MobilizeURL(url);
10449 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10450 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10456 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10457 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10458 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10459 url = MobilizeURL(url);
10460 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10461 //NSLog(@"%@ %@", [url absoluteString], value);
10467 Class $NSURLConnection;
10469 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10470 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10472 NSURL *url([copy URL]);
10474 NSString *host([url host]);
10475 NSString *scheme([[url scheme] lowercaseString]);
10477 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10479 @synchronized (HostConfig_) {
10480 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10481 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10482 [copy setHTTPShouldUsePipelining:YES];
10484 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10485 if ([control isEqualToString:@"max-age=0"])
10486 if ([CachedURLs_ containsObject:url]) {
10488 NSLog(@"~~~: %@", url);
10491 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10493 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10494 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10495 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10499 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10505 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10506 CGSize size([[UIScreen mainScreen] bounds].size);
10507 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10508 if ([$WAKWindow hasLandscapeOrientation])
10509 std::swap(size.width, size.height);*/
10513 Class $NSUserDefaults;
10515 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10516 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10517 return [NSString stringWithFormat:@"%@/LocalStorage", Cache_];
10518 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10521 int main(int argc, char *argv[]) {
10522 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10526 UpdateExternalStatus(0);
10528 if (Class $UIDevice = objc_getClass("UIDevice")) {
10529 UIDevice *device([$UIDevice currentDevice]);
10530 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10532 IsWildcat_ = false;
10534 UIScreen *screen([UIScreen mainScreen]);
10535 if ([screen respondsToSelector:@selector(scale)])
10536 ScreenScale_ = [screen scale];
10540 UIDevice *device([UIDevice currentDevice]);
10541 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10542 Idiom_ = @"iphone";
10544 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10545 if (idiom == UIUserInterfaceIdiomPhone)
10546 Idiom_ = @"iphone";
10547 else if (idiom == UIUserInterfaceIdiomPad)
10550 NSLog(@"unknown UIUserInterfaceIdiom!");
10553 Pcre pattern("^([0-9]+\\.[0-9]+)");
10555 if (pattern([device systemVersion]))
10556 Firmware_ = pattern[1];
10557 if (pattern(Cydia_))
10558 Major_ = pattern[1];
10560 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10562 HostConfig_ = [[[NSObject alloc] init] autorelease];
10563 @synchronized (HostConfig_) {
10564 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10565 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10566 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10567 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10568 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10571 NSString *ui(@"ui/ios");
10573 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10574 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10575 UI_ = CydiaURL(ui);
10577 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10579 MobilizedFiles_ = [NSMutableSet setWithObjects:
10580 @"Library/Preferences/com.apple.Accessibility.plist",
10581 @"Library/Preferences/com.apple.preferences.sounds.plist",
10584 /* Library Hacks {{{ */
10585 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10587 $WAKWindow = objc_getClass("WAKWindow");
10588 if ($WAKWindow != NULL)
10589 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10590 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10592 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10594 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10595 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10596 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10597 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10600 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10601 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10602 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10603 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10606 $NSURLConnection = objc_getClass("NSURLConnection");
10607 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10608 if (NSURLConnection$init$ != NULL) {
10609 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10610 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10613 $NSUserDefaults = objc_getClass("NSUserDefaults");
10614 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10615 if (NSUserDefaults$objectForKey$ != NULL) {
10616 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10617 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10620 /* Set Locale {{{ */
10621 Locale_ = CFLocaleCopyCurrent();
10622 Languages_ = [NSLocale preferredLanguages];
10624 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10625 //NSLog(@"%@", [Languages_ description]);
10628 if (Locale_ != NULL)
10629 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10630 else if (Languages_ != nil && [Languages_ count] != 0)
10631 lang = [[Languages_ objectAtIndex:0] UTF8String];
10633 // XXX: consider just setting to C and then falling through?
10636 if (lang != NULL) {
10637 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10638 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10641 NSLog(@"Setting Language: %s", lang);
10643 if (lang != NULL) {
10644 setenv("LANG", lang, true);
10645 std::setlocale(LC_ALL, lang);
10649 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10651 /* Parse Arguments {{{ */
10652 bool substrate(false);
10658 for (int argi(1); argi != argc; ++argi)
10659 if (strcmp(argv[argi], "--") == 0) {
10661 argv[argi] = argv[0];
10667 for (int argi(1); argi != arge; ++argi)
10668 if (strcmp(args[argi], "--substrate") == 0)
10671 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10675 App_ = [[NSBundle mainBundle] bundlePath];
10681 if (access("/var/mobile/Library/Keyboard/UserDictionary.sqlite", F_OK) == 0)
10682 system("mkdir -p /var/root/Library/Keyboard; cp -af /var/mobile/Library/Keyboard/UserDictionary.sqlite /var/root/Library/Keyboard/");
10684 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/root"] retain];
10686 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10687 alloc_ = alloc->method_imp;
10688 alloc->method_imp = (IMP) &Alloc_;*/
10690 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10691 dealloc_ = dealloc->method_imp;
10692 dealloc->method_imp = (IMP) &Dealloc_;*/
10694 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10695 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10697 /* System Information {{{ */
10701 size = sizeof(maxproc);
10702 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10703 perror("sysctlbyname(\"kern.maxproc\", ?)");
10704 else if (maxproc < 64) {
10706 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10707 perror("sysctlbyname(\"kern.maxproc\", #)");
10710 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10711 char *osversion = new char[size];
10712 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10713 perror("sysctlbyname(\"kern.osversion\", ?)");
10715 System_ = [NSString stringWithUTF8String:osversion];
10717 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10718 char *machine = new char[size];
10719 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10720 perror("sysctlbyname(\"hw.machine\", ?)");
10722 Machine_ = machine;
10724 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10725 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10726 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10728 UniqueID_ = UniqueIdentifier(device);
10730 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10731 Product_ = [info objectForKey:@"SafariProductVersion"];
10732 Safari_ = [info objectForKey:@"CFBundleVersion"];
10735 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10737 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10738 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10739 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10740 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10741 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10742 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10744 UserAgent_ = agent;
10746 /* Load Database {{{ */
10748 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10750 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10752 if (Metadata_ == NULL)
10753 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10755 Settings_ = [Metadata_ objectForKey:@"Settings"];
10757 Packages_ = [Metadata_ objectForKey:@"Packages"];
10759 Values_ = [Metadata_ objectForKey:@"Values"];
10760 Sections_ = [Metadata_ objectForKey:@"Sections"];
10761 Sources_ = [Metadata_ objectForKey:@"Sources"];
10763 Token_ = [Metadata_ objectForKey:@"Token"];
10765 Version_ = [Metadata_ objectForKey:@"Version"];
10768 if (Settings_ != nil)
10769 Role_ = [Settings_ objectForKey:@"Role"];
10771 if (Values_ == nil) {
10772 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10773 [Metadata_ setObject:Values_ forKey:@"Values"];
10776 if (Sections_ == nil) {
10777 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10778 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10781 if (Sources_ == nil) {
10782 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10783 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10786 if (Version_ == nil) {
10787 Version_ = [NSNumber numberWithUnsignedInt:0];
10788 [Metadata_ setObject:Version_ forKey:@"Version"];
10791 if ([Version_ unsignedIntValue] == 0) {
10792 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10793 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10794 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10795 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10797 Version_ = [NSNumber numberWithUnsignedInt:1];
10798 [Metadata_ setObject:Version_ forKey:@"Version"];
10800 [Metadata_ removeObjectForKey:@"LastUpdate"];
10806 CydiaWriteSources();
10809 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10812 if (Packages_ != nil) {
10814 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10818 [Metadata_ removeObjectForKey:@"Packages"];
10824 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10826 #define MobileSubstrate_(name) \
10827 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10828 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10829 if (handle == NULL) \
10830 NSLog(@"%s", dlerror()); \
10833 MobileSubstrate_(Activator)
10834 MobileSubstrate_(libstatusbar)
10835 MobileSubstrate_(SimulatedKeyEvents)
10836 MobileSubstrate_(WinterBoard)
10838 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10839 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10841 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10843 if (access("/User", F_OK) != 0 || version != 6) {
10845 system("/usr/libexec/cydia/firmware.sh");
10849 _assert([[NSFileManager defaultManager]
10850 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10851 withIntermediateDirectories:YES
10856 if (access("/tmp/cydia.chk", F_OK) == 0) {
10857 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10858 _assert(errno == ENOENT);
10859 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10860 _assert(errno == ENOENT);
10863 /* APT Initialization {{{ */
10864 _assert(pkgInitConfig(*_config));
10865 _assert(pkgInitSystem(*_config, _system));
10868 _config->Set("APT::Acquire::Translation", lang);
10870 // XXX: this timeout might be important :(
10871 //_config->Set("Acquire::http::Timeout", 15);
10873 _config->Set("Acquire::http::MaxParallel", 3);
10875 /* Color Choices {{{ */
10876 space_ = CGColorSpaceCreateDeviceRGB();
10878 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10879 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10880 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10881 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10882 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10883 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10884 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10885 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10886 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10887 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10889 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10890 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10892 /* UIKit Configuration {{{ */
10893 // XXX: I have a feeling this was important
10894 //UIKeyboardDisableAutomaticAppearance();
10897 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10899 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10900 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10901 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10903 ShowPromoted_ = fast;
10904 PulseInterval_ = fast ? 50000 : 500000;
10906 Colon_ = UCLocalize("COLON_DELIMITED");
10907 Elision_ = UCLocalize("ELISION");
10908 Error_ = UCLocalize("ERROR");
10909 Warning_ = UCLocalize("WARNING");
10911 AprilFools_ = false;
10914 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10916 CGColorSpaceRelease(space_);
10917 CFRelease(Locale_);