1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2012 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_;
693 static CYColor White_;
694 static CYColor Gray_;
695 static CYColor Green_;
696 static CYColor Purple_;
697 static CYColor Purplish_;
699 static UIColor *InstallingColor_;
700 static UIColor *RemovingColor_;
702 static NSString *App_;
704 static BOOL Advanced_;
705 static BOOL Ignored_;
707 static _H<UIFont> Font12_;
708 static _H<UIFont> Font12Bold_;
709 static _H<UIFont> Font14_;
710 static _H<UIFont> Font18Bold_;
711 static _H<UIFont> Font22Bold_;
713 static const char *Machine_ = NULL;
714 static _H<NSString> System_;
715 static NSString *SerialNumber_ = nil;
716 static NSString *ChipID_ = nil;
717 static NSString *BBSNum_ = nil;
718 static _H<NSString> Token_;
719 static _H<NSString> UniqueID_;
720 static _H<NSString> UserAgent_;
721 static _H<NSString> Product_;
722 static _H<NSString> Safari_;
724 static CFLocaleRef Locale_;
725 static NSArray *Languages_;
726 static CGColorSpaceRef space_;
728 static NSDictionary *SectionMap_;
729 static NSMutableDictionary *Metadata_;
730 static _transient NSMutableDictionary *Settings_;
731 static _transient NSString *Role_;
732 static _transient NSMutableDictionary *Packages_;
733 static _transient NSMutableDictionary *Values_;
734 static _transient NSMutableDictionary *Sections_;
735 _H<NSMutableDictionary> Sources_;
736 static _transient NSNumber *Version_;
741 static CGFloat ScreenScale_;
742 static NSString *Idiom_;
743 static _H<NSString> Firmware_;
744 static NSString *Major_;
746 static _H<NSMutableDictionary> SessionData_;
747 static _H<NSObject> HostConfig_;
748 static _H<NSMutableSet> BridgedHosts_;
749 static _H<NSMutableSet> TokenHosts_;
750 static _H<NSMutableSet> InsecureHosts_;
751 static _H<NSMutableSet> PipelinedHosts_;
752 static _H<NSMutableSet> CachedURLs_;
754 static NSString *kCydiaProgressEventTypeError = @"Error";
755 static NSString *kCydiaProgressEventTypeInformation = @"Information";
756 static NSString *kCydiaProgressEventTypeStatus = @"Status";
757 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
760 /* Display Helpers {{{ */
761 inline float Interpolate(float begin, float end, float fraction) {
762 return (end - begin) * fraction + begin;
765 static _finline const char *StripVersion_(const char *version) {
766 const char *colon(strchr(version, ':'));
767 return colon == NULL ? version : colon + 1;
770 NSString *LocalizeSection(NSString *section) {
771 static Pcre title_r("^(.*?) \\((.*)\\)$");
772 if (title_r(section)) {
773 NSString *parent(title_r[1]);
774 NSString *child(title_r[2]);
776 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
777 LocalizeSection(parent),
778 LocalizeSection(child)
782 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
785 NSString *Simplify(NSString *title) {
786 const char *data = [title UTF8String];
787 size_t size = [title length];
789 static Pcre square_r("^\\[(.*)\\]$");
790 if (square_r(data, size))
791 return Simplify(square_r[1]);
793 static Pcre paren_r("^\\((.*)\\)$");
794 if (paren_r(data, size))
795 return Simplify(paren_r[1]);
797 static Pcre title_r("^(.*?) \\((.*)\\)$");
798 if (title_r(data, size))
799 return Simplify(title_r[1]);
805 NSString *GetLastUpdate() {
806 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
809 return UCLocalize("NEVER_OR_UNKNOWN");
811 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
812 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
814 CFRelease(formatter);
816 return [(NSString *) formatted autorelease];
819 bool isSectionVisible(NSString *section) {
820 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
821 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
822 return hidden == nil || ![hidden boolValue];
825 static NSObject *CYIOGetValue(const char *path, NSString *property) {
826 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
827 if (entry == MACH_PORT_NULL)
830 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
831 IOObjectRelease(entry);
835 return [(id) value autorelease];
838 static NSString *CYHex(NSData *data, bool reverse = false) {
842 size_t length([data length]);
843 uint8_t bytes[length];
844 [data getBytes:bytes];
846 char string[length * 2 + 1];
847 for (size_t i(0); i != length; ++i)
848 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
850 return [NSString stringWithUTF8String:string];
855 /* Delegate Prototypes {{{ */
858 @class CydiaProgressEvent;
860 @protocol DatabaseDelegate
861 - (void) repairWithSelector:(SEL)selector;
862 - (void) setConfigurationData:(NSString *)data;
863 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
866 @class CYPackageController;
868 @protocol CydiaDelegate
869 - (void) returnToCydia;
871 - (void) retainNetworkActivityIndicator;
872 - (void) releaseNetworkActivityIndicator;
873 - (void) clearPackage:(Package *)package;
874 - (void) installPackage:(Package *)package;
875 - (void) installPackages:(NSArray *)packages;
876 - (void) removePackage:(Package *)package;
877 - (void) beginUpdate;
879 - (void) distUpgrade;
882 - (void) _saveConfig;
884 - (void) addSource:(NSDictionary *)source;
885 - (void) addTrivialSource:(NSString *)href;
886 - (void) showSettings;
887 - (UIProgressHUD *) addProgressHUD;
888 - (void) removeProgressHUD:(UIProgressHUD *)hud;
889 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
890 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
894 /* Status Delegation {{{ */
896 public pkgAcquireStatus
899 _transient NSObject<ProgressDelegate> *delegate_;
909 void setDelegate(NSObject<ProgressDelegate> *delegate) {
910 delegate_ = delegate;
913 NSObject<ProgressDelegate> *getDelegate() const {
917 virtual bool MediaChange(std::string media, std::string drive) {
921 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
925 virtual void Fetch(pkgAcquire::ItemDesc &item) {
926 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
927 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
928 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
931 virtual void Done(pkgAcquire::ItemDesc &item) {
932 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
933 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
934 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
937 virtual void Fail(pkgAcquire::ItemDesc &item) {
939 item.Owner->Status == pkgAcquire::Item::StatIdle ||
940 item.Owner->Status == pkgAcquire::Item::StatDone
944 std::string &error(item.Owner->ErrorText);
948 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
949 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
952 virtual bool Pulse(pkgAcquire *Owner) {
953 bool value = pkgAcquireStatus::Pulse(Owner);
956 double(CurrentBytes + CurrentItems) /
957 double(TotalBytes + TotalItems)
960 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
961 [NSNumber numberWithDouble:percent], @"Percent",
963 [NSNumber numberWithDouble:CurrentBytes], @"Current",
964 [NSNumber numberWithDouble:TotalBytes], @"Total",
965 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
966 nil] waitUntilDone:YES];
968 if (value && ![delegate_ isProgressCancelled])
976 _finline bool WasCancelled() const {
980 virtual void Start() {
981 pkgAcquireStatus::Start();
982 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
985 virtual void Stop() {
986 pkgAcquireStatus::Stop();
987 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
988 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
992 /* Database Interface {{{ */
993 typedef std::map< unsigned long, _H<Source> > SourceMap;
995 @interface Database : NSObject {
1001 pkgCacheFile cache_;
1002 pkgDepCache::Policy *policy_;
1003 pkgRecords *records_;
1004 pkgProblemResolver *resolver_;
1005 pkgAcquire *fetcher_;
1007 SPtr<pkgPackageManager> manager_;
1008 pkgSourceList *list_;
1010 SourceMap sourceMap_;
1011 _H<NSMutableArray> sourceList_;
1013 CFMutableArrayRef packages_;
1015 _transient NSObject<DatabaseDelegate> *delegate_;
1016 _transient NSObject<ProgressDelegate> *progress_;
1024 std::map<const char *, _H<NSString> > sections_;
1027 + (Database *) sharedInstance;
1030 - (void) _readCydia:(NSNumber *)fd;
1031 - (void) _readStatus:(NSNumber *)fd;
1032 - (void) _readOutput:(NSNumber *)fd;
1036 - (Package *) packageWithName:(NSString *)name;
1038 - (pkgCacheFile &) cache;
1039 - (pkgDepCache::Policy *) policy;
1040 - (pkgRecords *) records;
1041 - (pkgProblemResolver *) resolver;
1042 - (pkgAcquire &) fetcher;
1043 - (pkgSourceList &) list;
1044 - (NSArray *) packages;
1045 - (NSArray *) sources;
1046 - (Source *) sourceWithKey:(NSString *)key;
1047 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1055 - (void) updateWithStatus:(Status &)status;
1057 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1059 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1060 - (NSObject<ProgressDelegate> *) progressDelegate;
1062 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1064 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1068 /* ProgressEvent Implementation {{{ */
1069 @implementation CydiaProgressEvent
1071 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1072 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1075 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1076 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1077 [event setPackage:package];
1081 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1082 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1084 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1085 NSArray *fields([description componentsSeparatedByString:@" "]);
1086 [event setItem:fields];
1088 if ([fields count] > 3) {
1089 [event setPackage:[fields objectAtIndex:2]];
1090 [event setVersion:[fields objectAtIndex:3]];
1093 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1098 + (NSArray *) _attributeKeys {
1099 return [NSArray arrayWithObjects:
1109 - (NSArray *) attributeKeys {
1110 return [[self class] _attributeKeys];
1113 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1114 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1117 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1118 if ((self = [super init]) != nil) {
1124 - (NSString *) message {
1128 - (NSString *) type {
1132 - (NSArray *) item {
1133 return (id) item_ ?: [NSNull null];
1136 - (void) setItem:(NSArray *)item {
1140 - (NSString *) package {
1141 return (id) package_ ?: [NSNull null];
1144 - (void) setPackage:(NSString *)package {
1148 - (NSString *) url {
1149 return (id) url_ ?: [NSNull null];
1152 - (void) setURL:(NSString *)url {
1156 - (void) setVersion:(NSString *)version {
1160 - (NSString *) version {
1161 return (id) version_ ?: [NSNull null];
1164 - (NSString *) compound:(NSString *)value {
1166 NSString *mode(nil); {
1167 NSString *type([self type]);
1168 if ([type isEqualToString:kCydiaProgressEventTypeError])
1169 mode = UCLocalize("ERROR");
1170 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1171 mode = UCLocalize("WARNING");
1175 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1181 - (NSString *) compoundMessage {
1182 return [self compound:[self message]];
1185 - (NSString *) compoundTitle {
1188 if (package_ == nil)
1190 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1191 title = [package name];
1195 return [self compound:title];
1201 // Cytore Definitions {{{
1202 struct PackageValue :
1205 Cytore::Offset<PackageValue> next_;
1207 uint32_t index_ : 23;
1208 uint32_t subscribed_ : 1;
1225 Cytore::Offset<PackageValue> packages_[1 << 16];
1228 static Cytore::File<MetaValue> MetaFile_;
1230 // Cytore Helper Functions {{{
1231 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1232 SplitHash nhash = { hashlittle(name, length) };
1234 PackageValue *metadata;
1236 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1237 offset: if (offset->IsNull()) {
1238 *offset = MetaFile_.New<PackageValue>(length + 1);
1239 metadata = &MetaFile_.Get(*offset);
1241 if (metadata == NULL) {
1245 metadata = new PackageValue();
1246 memset(metadata, 0, sizeof(*metadata));
1249 memcpy(metadata->name_, name, length + 1);
1250 metadata->nhash_ = nhash.u16[1];
1252 metadata = &MetaFile_.Get(*offset);
1254 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1255 offset = &metadata->next_;
1263 static void PackageImport(const void *key, const void *value, void *context) {
1264 bool &fail(*reinterpret_cast<bool *>(context));
1267 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1268 NSLog(@"failed to import package %@", key);
1272 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1273 NSDictionary *package((NSDictionary *) value);
1275 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1276 if ([subscribed boolValue] && !metadata->subscribed_)
1277 metadata->subscribed_ = true;
1279 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1280 time_t time([date timeIntervalSince1970]);
1281 if (metadata->first_ > time || metadata->first_ == 0)
1282 metadata->first_ = time;
1285 NSDate *date([package objectForKey:@"LastSeen"]);
1286 NSString *version([package objectForKey:@"LastVersion"]);
1288 if (date != nil && version != nil) {
1289 time_t time([date timeIntervalSince1970]);
1290 if (metadata->last_ < time || metadata->last_ == 0)
1291 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1292 size_t length(strlen(buffer));
1293 uint16_t vhash(hashlittle(buffer, length));
1295 size_t capped(std::min<size_t>(8, length));
1296 char *latest(buffer + length - capped);
1298 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1299 metadata->vhash_ = vhash;
1301 metadata->last_ = time;
1307 /* Source Class {{{ */
1308 @interface Source : NSObject {
1310 Database *database_;
1313 CYString depiction_;
1314 CYString description_;
1320 CYString distribution_;
1326 _H<NSString> authority_;
1328 CYString defaultIcon_;
1330 _H<NSMutableDictionary> record_;
1334 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1336 - (NSComparisonResult) compareByName:(Source *)source;
1338 - (NSString *) depictionForPackage:(NSString *)package;
1339 - (NSString *) supportForPackage:(NSString *)package;
1341 - (metaIndex *) metaIndex;
1342 - (NSDictionary *) record;
1345 - (NSString *) rooturi;
1346 - (NSString *) distribution;
1347 - (NSString *) type;
1350 - (NSString *) host;
1352 - (NSString *) name;
1353 - (NSString *) shortDescription;
1354 - (NSString *) label;
1355 - (NSString *) origin;
1356 - (NSString *) version;
1358 - (NSString *) defaultIcon;
1359 - (NSURL *) iconURL;
1363 @implementation Source
1367 distribution_.clear();
1372 description_.clear();
1378 defaultIcon_.clear();
1385 + (NSString *) webScriptNameForSelector:(SEL)selector {
1387 else if (selector == @selector(addSection:))
1388 return @"addSection";
1389 else if (selector == @selector(getField:))
1391 else if (selector == @selector(removeSection:))
1392 return @"removeSection";
1393 else if (selector == @selector(remove))
1399 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1400 return [self webScriptNameForSelector:selector] == nil;
1403 + (NSArray *) _attributeKeys {
1404 return [NSArray arrayWithObjects:
1415 @"shortDescription",
1422 - (NSArray *) attributeKeys {
1423 return [[self class] _attributeKeys];
1426 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1427 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1430 - (metaIndex *) metaIndex {
1434 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1437 trusted_ = index->IsTrusted();
1439 uri_.set(pool, index->GetURI());
1440 distribution_.set(pool, index->GetDist());
1441 type_.set(pool, index->GetType());
1443 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1444 if (dindex != NULL) {
1445 base_.set(pool, dindex->MetaIndexURI(""));
1448 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1451 pkgTagFile tags(&fd);
1453 pkgTagSection section;
1460 {"default-icon", &defaultIcon_},
1461 {"depiction", &depiction_},
1462 {"description", &description_},
1464 {"origin", &origin_},
1465 {"support", &support_},
1466 {"version", &version_},
1469 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1470 const char *start, *end;
1472 if (section.Find(names[i].name_, start, end)) {
1473 CYString &value(*names[i].value_);
1474 value.set(pool, start, end - start);
1480 record_ = [Sources_ objectForKey:[self key]];
1482 NSURL *url([NSURL URLWithString:uri_]);
1486 host_ = [host_ lowercaseString];
1491 authority_ = [url path];
1494 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1495 if ((self = [super init]) != nil) {
1496 era_ = [database era];
1497 database_ = database;
1500 [self setMetaIndex:index inPool:pool];
1504 - (NSString *) getField:(NSString *)name {
1505 @synchronized (database_) {
1506 if ([database_ era] != era_ || index_ == NULL)
1509 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1514 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1519 pkgTagFile tags(&fd);
1521 pkgTagSection section;
1524 const char *start, *end;
1525 if (!section.Find([name UTF8String], start, end))
1526 return (NSString *) [NSNull null];
1528 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1531 - (NSComparisonResult) compareByName:(Source *)source {
1532 NSString *lhs = [self name];
1533 NSString *rhs = [source name];
1535 if ([lhs length] != 0 && [rhs length] != 0) {
1536 unichar lhc = [lhs characterAtIndex:0];
1537 unichar rhc = [rhs characterAtIndex:0];
1539 if (isalpha(lhc) && !isalpha(rhc))
1540 return NSOrderedAscending;
1541 else if (!isalpha(lhc) && isalpha(rhc))
1542 return NSOrderedDescending;
1545 return [lhs compare:rhs options:LaxCompareOptions_];
1548 - (NSString *) depictionForPackage:(NSString *)package {
1549 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1552 - (NSString *) supportForPackage:(NSString *)package {
1553 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1556 - (NSArray *) sections {
1557 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1560 - (void) _addSection:(NSString *)section {
1563 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1564 if (![sections containsObject:section]) {
1565 [sections addObject:section];
1569 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1574 - (bool) addSection:(NSString *)section {
1578 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1582 - (void) _removeSection:(NSString *)section {
1586 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1587 if ([sections containsObject:section]) {
1588 [sections removeObject:section];
1593 - (bool) removeSection:(NSString *)section {
1597 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1602 [Sources_ removeObjectForKey:[self key]];
1607 bool value(record_ != nil);
1608 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1612 - (NSDictionary *) record {
1620 - (NSString *) rooturi {
1624 - (NSString *) distribution {
1625 return distribution_;
1628 - (NSString *) type {
1632 - (NSString *) baseuri {
1633 return base_.empty() ? nil : (id) base_;
1636 - (NSString *) iconuri {
1637 if (NSString *base = [self baseuri])
1638 return [base stringByAppendingString:@"CydiaIcon.png"];
1643 - (NSURL *) iconURL {
1644 if (NSString *uri = [self iconuri])
1645 return [NSURL URLWithString:uri];
1649 - (NSString *) key {
1650 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1653 - (NSString *) host {
1657 - (NSString *) name {
1658 return origin_.empty() ? (id) authority_ : origin_;
1661 - (NSString *) shortDescription {
1662 return description_;
1665 - (NSString *) label {
1666 return label_.empty() ? (id) authority_ : label_;
1669 - (NSString *) origin {
1673 - (NSString *) version {
1677 - (NSString *) defaultIcon {
1678 return defaultIcon_;
1683 /* CydiaOperation Class {{{ */
1684 @interface CydiaOperation : NSObject {
1685 _H<NSString> operator_;
1686 _H<NSString> value_;
1689 - (NSString *) operator;
1690 - (NSString *) value;
1694 @implementation CydiaOperation
1696 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1697 if ((self = [super init]) != nil) {
1698 operator_ = [NSString stringWithUTF8String:_operator];
1699 value_ = [NSString stringWithUTF8String:value];
1703 + (NSArray *) _attributeKeys {
1704 return [NSArray arrayWithObjects:
1710 - (NSArray *) attributeKeys {
1711 return [[self class] _attributeKeys];
1714 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1715 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1718 - (NSString *) operator {
1722 - (NSString *) value {
1728 /* CydiaClause Class {{{ */
1729 @interface CydiaClause : NSObject {
1730 _H<NSString> package_;
1731 _H<CydiaOperation> version_;
1734 - (NSString *) package;
1735 - (CydiaOperation *) version;
1739 @implementation CydiaClause
1741 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1742 if ((self = [super init]) != nil) {
1743 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1745 if (const char *version = dep.TargetVer())
1746 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1748 version_ = (id) [NSNull null];
1752 + (NSArray *) _attributeKeys {
1753 return [NSArray arrayWithObjects:
1759 - (NSArray *) attributeKeys {
1760 return [[self class] _attributeKeys];
1763 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1764 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1767 - (NSString *) package {
1771 - (CydiaOperation *) version {
1777 /* CydiaRelation Class {{{ */
1778 @interface CydiaRelation : NSObject {
1779 _H<NSString> relationship_;
1780 _H<NSMutableArray> clauses_;
1783 - (NSString *) relationship;
1784 - (NSArray *) clauses;
1788 @implementation CydiaRelation
1790 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1791 if ((self = [super init]) != nil) {
1792 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1793 clauses_ = [NSMutableArray arrayWithCapacity:8];
1795 pkgCache::DepIterator start;
1796 pkgCache::DepIterator end;
1797 dep.GlobOr(start, end); // ++dep
1800 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1802 // yes, seriously. (wtf?)
1810 + (NSArray *) _attributeKeys {
1811 return [NSArray arrayWithObjects:
1817 - (NSArray *) attributeKeys {
1818 return [[self class] _attributeKeys];
1821 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1822 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1825 - (NSString *) relationship {
1826 return relationship_;
1829 - (NSArray *) clauses {
1833 - (void) addClause:(CydiaClause *)clause {
1834 [clauses_ addObject:clause];
1839 /* Package Class {{{ */
1840 struct ParsedPackage {
1844 CYString architecture_;
1847 CYString depiction_;
1857 @interface Package : NSObject {
1860 uint32_t essential_ : 1;
1861 uint32_t obsolete_ : 1;
1862 uint32_t ignored_ : 1;
1863 uint32_t pooled_ : 1;
1869 _transient Database *database_;
1871 pkgCache::VerIterator version_;
1872 pkgCache::PkgIterator iterator_;
1873 pkgCache::VerFileIterator file_;
1879 CYString installed_;
1881 const char *section_;
1882 _transient NSString *section$_;
1886 PackageValue *metadata_;
1887 ParsedPackage *parsed_;
1889 _H<NSMutableArray> tags_;
1892 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1893 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1895 - (pkgCache::PkgIterator) iterator;
1898 - (NSString *) section;
1899 - (NSString *) simpleSection;
1901 - (NSString *) longSection;
1902 - (NSString *) shortSection;
1906 - (MIMEAddress *) maintainer;
1908 - (NSString *) longDescription;
1909 - (NSString *) shortDescription;
1912 - (PackageValue *) metadata;
1915 - (bool) subscribed;
1916 - (bool) setSubscribed:(bool)subscribed;
1920 - (NSString *) latest;
1921 - (NSString *) installed;
1922 - (BOOL) uninstalled;
1925 - (BOOL) upgradableAndEssential:(BOOL)essential;
1928 - (BOOL) unfiltered;
1932 - (BOOL) halfConfigured;
1933 - (BOOL) halfInstalled;
1935 - (NSString *) mode;
1938 - (NSString *) name;
1940 - (NSString *) homepage;
1941 - (NSString *) depiction;
1942 - (MIMEAddress *) author;
1944 - (NSString *) support;
1946 - (NSArray *) files;
1947 - (NSArray *) warnings;
1948 - (NSArray *) applications;
1950 - (Source *) source;
1953 - (BOOL) matches:(NSArray *)query;
1955 - (bool) hasSupportingRole;
1956 - (BOOL) hasTag:(NSString *)tag;
1957 - (NSString *) primaryPurpose;
1958 - (NSArray *) purposes;
1959 - (bool) isCommercial;
1961 - (void) setIndex:(size_t)index;
1963 - (CYString &) cyname;
1965 - (uint32_t) compareBySection:(NSArray *)sections;
1970 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1971 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1972 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1973 - (bool) isVisibleInSection:(NSString *)section;
1974 - (bool) isVisibleInSource:(Source *)source;
1978 uint32_t PackageChangesRadix(Package *self, void *) {
1983 uint32_t timestamp : 30;
1984 uint32_t ignored : 1;
1985 uint32_t upgradable : 1;
1989 bool upgradable([self upgradableAndEssential:YES]);
1990 value.bits.upgradable = upgradable ? 1 : 0;
1993 value.bits.timestamp = 0;
1994 value.bits.ignored = [self ignored] ? 0 : 1;
1995 value.bits.upgradable = 1;
1997 value.bits.timestamp = [self seen] >> 2;
1998 value.bits.ignored = 0;
1999 value.bits.upgradable = 0;
2002 return _not(uint32_t) - value.key;
2005 uint32_t PackagePrefixRadix(Package *self, void *context) {
2006 size_t offset(reinterpret_cast<size_t>(context));
2007 CYString &name([self cyname]);
2009 size_t size(name.size());
2012 char *text(name.data());
2015 if (!isdigit(text[0]))
2019 while (size != digits && isdigit(text[digits]))
2027 if (offset == 0 && zeros != 0) {
2028 memset(data, '0', zeros);
2029 memcpy(data + zeros, text, 4 - zeros);
2031 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2032 if (size <= offset - zeros)
2035 text += offset - zeros;
2036 size -= offset - zeros;
2039 memcpy(data, text, 4);
2041 memcpy(data, text, size);
2042 memset(data + size, 0, 4 - size);
2045 for (size_t i(0); i != 4; ++i)
2046 if (isalpha(data[i]))
2054 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2056 /* XXX: ntohl may be more honest */
2057 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2060 CYString &(*PackageName)(Package *self, SEL sel);
2062 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2063 _profile(PackageNameCompare)
2064 CYString &lhi(PackageName(lhs, @selector(cyname)));
2065 CYString &rhi(PackageName(rhs, @selector(cyname)));
2066 CFStringRef lhn(lhi), rhn(rhi);
2069 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2070 else if (rhn == NULL)
2071 return NSOrderedDescending;
2073 _profile(PackageNameCompare$NumbersLast)
2074 if (!lhi.empty() && !rhi.empty()) {
2075 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2076 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2077 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2078 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2079 return lha ? NSOrderedAscending : NSOrderedDescending;
2083 CFIndex length = CFStringGetLength(lhn);
2085 _profile(PackageNameCompare$Compare)
2086 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2091 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2092 return PackageNameCompare(*lhs, *rhs, context);
2095 struct PackageNameOrdering :
2096 std::binary_function<Package *, Package *, bool>
2098 _finline bool operator ()(Package *lhs, Package *rhs) const {
2099 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2103 @implementation Package
2105 - (NSString *) description {
2106 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2111 apr_pool_destroy(pool_);
2112 if (parsed_ != NULL)
2117 + (NSString *) webScriptNameForSelector:(SEL)selector {
2119 else if (selector == @selector(clear))
2121 else if (selector == @selector(getField:))
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",
2172 - (NSArray *) attributeKeys {
2173 return [[self class] _attributeKeys];
2176 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2177 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2180 - (NSArray *) relations {
2181 @synchronized (database_) {
2182 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2183 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2184 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2188 - (NSString *) architecture {
2190 @synchronized (database_) {
2191 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2194 - (NSString *) getField:(NSString *)name {
2195 @synchronized (database_) {
2196 if ([database_ era] != era_ || file_.end())
2199 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2201 const char *start, *end;
2202 if (!parser.Find([name UTF8String], start, end))
2203 return (NSString *) [NSNull null];
2205 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2209 if (parsed_ != NULL)
2211 @synchronized (database_) {
2212 if ([database_ era] != era_ || file_.end())
2215 ParsedPackage *parsed(new ParsedPackage);
2218 _profile(Package$parse)
2219 pkgRecords::Parser *parser;
2221 _profile(Package$parse$Lookup)
2222 parser = &[database_ records]->Lookup(file_);
2227 _profile(Package$parse$Find)
2232 {"architecture", &parsed->architecture_},
2233 {"icon", &parsed->icon_},
2234 {"depiction", &parsed->depiction_},
2235 {"homepage", &parsed->homepage_},
2236 {"website", &website},
2237 {"bugs", &parsed->bugs_},
2238 {"support", &parsed->support_},
2239 {"sponsor", &parsed->sponsor_},
2240 {"author", &parsed->author_},
2241 {"md5sum", &parsed->md5sum_},
2244 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2245 const char *start, *end;
2247 if (parser->Find(names[i].name_, start, end)) {
2248 CYString &value(*names[i].value_);
2249 _profile(Package$parse$Value)
2250 value.set(pool_, start, end - start);
2256 _profile(Package$parse$Tagline)
2257 const char *start, *end;
2258 if (parser->ShortDesc(start, end)) {
2259 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2262 while (stop != start && stop[-1] == '\r')
2264 parsed->tagline_.set(pool_, start, stop - start);
2268 _profile(Package$parse$Retain)
2269 if (parsed->homepage_.empty())
2270 parsed->homepage_ = website;
2271 if (parsed->homepage_ == parsed->depiction_)
2272 parsed->homepage_.clear();
2277 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2278 if ((self = [super init]) != nil) {
2279 _profile(Package$initWithVersion)
2281 apr_pool_create(&pool_, NULL);
2287 database_ = database;
2288 era_ = [database era];
2292 pkgCache::PkgIterator iterator(version.ParentPkg());
2293 iterator_ = iterator;
2295 _profile(Package$initWithVersion$Version)
2296 if (!version_.end())
2297 file_ = version_.FileList();
2299 pkgCache &cache([database_ cache]);
2300 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2304 _profile(Package$initWithVersion$Cache)
2305 name_.set(NULL, iterator.Display());
2307 latest_.set(NULL, StripVersion_(version_.VerStr()));
2309 pkgCache::VerIterator current(iterator.CurrentVer());
2311 installed_.set(NULL, StripVersion_(current.VerStr()));
2314 _profile(Package$initWithVersion$Tags)
2315 pkgCache::TagIterator tag(iterator.TagList());
2317 tags_ = [NSMutableArray arrayWithCapacity:8];
2319 goto tag; for (; !tag.end(); ++tag) tag: {
2320 const char *name(tag.Name());
2321 NSString *string((NSString *) CYStringCreate(name));
2325 [tags_ addObject:[string autorelease]];
2327 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2328 if (strcmp(name + 6, "enduser") == 0)
2330 else if (strcmp(name + 6, "hacker") == 0)
2332 else if (strcmp(name + 6, "developer") == 0)
2334 else if (strcmp(name + 6, "cydia") == 0)
2340 if (strncmp(name, "cydia::", 7) == 0) {
2341 if (strcmp(name + 7, "essential") == 0)
2343 else if (strcmp(name + 7, "obsolete") == 0)
2350 _profile(Package$initWithVersion$Metadata)
2351 const char *mixed(iterator.Name());
2352 size_t size(strlen(mixed));
2353 char lower[size + 1];
2355 for (size_t i(0); i != size; ++i)
2356 lower[i] = mixed[i] | 0x20;
2359 PackageValue *metadata(PackageFind(lower, size));
2360 metadata_ = metadata;
2362 id_.set(NULL, metadata->name_, size);
2364 const char *latest(version_.VerStr());
2365 size_t length(strlen(latest));
2367 uint16_t vhash(hashlittle(latest, length));
2369 size_t capped(std::min<size_t>(8, length));
2370 latest = latest + length - capped;
2372 if (metadata->first_ == 0)
2373 metadata->first_ = now_;
2375 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2376 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2377 metadata->vhash_ = vhash;
2378 metadata->last_ = now_;
2379 } else if (metadata->last_ == 0)
2380 metadata->last_ = metadata->first_;
2383 _profile(Package$initWithVersion$Section)
2384 section_ = version_.Section();
2387 _profile(Package$initWithVersion$Flags)
2388 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2389 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2394 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2395 pkgCache::VerIterator version;
2397 _profile(Package$packageWithIterator$GetCandidateVer)
2398 version = [database policy]->GetCandidateVer(iterator);
2406 _profile(Package$packageWithIterator$Allocate)
2407 package = [Package allocWithZone:zone];
2410 _profile(Package$packageWithIterator$Initialize)
2412 initWithVersion:version
2419 _profile(Package$packageWithIterator$Autorelease)
2420 package = [package autorelease];
2426 - (pkgCache::PkgIterator) iterator {
2430 - (NSString *) section {
2431 if (section$_ == nil) {
2432 if (section_ == NULL)
2435 _profile(Package$section$mappedSectionForPointer)
2436 section$_ = [database_ mappedSectionForPointer:section_];
2441 - (NSString *) simpleSection {
2442 if (NSString *section = [self section])
2443 return Simplify(section);
2448 - (NSString *) longSection {
2449 return LocalizeSection([self section]);
2452 - (NSString *) shortSection {
2453 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2456 - (NSString *) uri {
2459 pkgIndexFile *index;
2460 pkgCache::PkgFileIterator file(file_.File());
2461 if (![database_ list].FindIndex(file, index))
2463 return [NSString stringWithUTF8String:iterator_->Path];
2464 //return [NSString stringWithUTF8String:file.Site()];
2465 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2469 - (MIMEAddress *) maintainer {
2470 @synchronized (database_) {
2471 if ([database_ era] != era_ || file_.end())
2474 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2475 const std::string &maintainer(parser->Maintainer());
2476 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2479 - (NSString *) md5sum {
2480 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2484 @synchronized (database_) {
2485 if ([database_ era] != era_ || version_.end())
2488 return version_->InstalledSize;
2491 - (NSString *) longDescription {
2492 @synchronized (database_) {
2493 if ([database_ era] != era_ || file_.end())
2496 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2497 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2499 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2500 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2501 if ([lines count] < 2)
2504 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2505 for (size_t i(1), e([lines count]); i != e; ++i) {
2506 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2507 [trimmed addObject:trim];
2510 return [trimmed componentsJoinedByString:@"\n"];
2513 - (NSString *) shortDescription {
2514 if (parsed_ != NULL)
2515 return static_cast<NSString *>(parsed_->tagline_);
2517 @synchronized (database_) {
2518 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2520 const char *start, *end;
2521 if (!parser.ShortDesc(start, end))
2524 if (end - start > 200)
2528 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2531 while (end != start && end[-1] == '\r')
2535 return [(id) CYStringCreate(start, end - start) autorelease];
2539 _profile(Package$index)
2540 CFStringRef name((CFStringRef) [self name]);
2541 if (CFStringGetLength(name) == 0)
2543 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2544 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2546 return toupper(character);
2550 - (PackageValue *) metadata {
2555 PackageValue *metadata([self metadata]);
2556 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2559 - (bool) subscribed {
2560 return [self metadata]->subscribed_;
2563 - (bool) setSubscribed:(bool)subscribed {
2564 PackageValue *metadata([self metadata]);
2565 if (metadata->subscribed_ == subscribed)
2567 metadata->subscribed_ = subscribed;
2575 - (NSString *) latest {
2579 - (NSString *) installed {
2583 - (BOOL) uninstalled {
2584 return installed_.empty();
2588 return !version_.end();
2591 - (BOOL) upgradableAndEssential:(BOOL)essential {
2592 _profile(Package$upgradableAndEssential)
2593 pkgCache::VerIterator current(iterator_.CurrentVer());
2595 return essential && essential_;
2597 return !version_.end() && version_ != current;
2601 - (BOOL) essential {
2606 return [database_ cache][iterator_].InstBroken();
2609 - (BOOL) unfiltered {
2610 _profile(Package$unfiltered$obsolete)
2611 if (_unlikely(obsolete_))
2615 _profile(Package$unfiltered$hasSupportingRole)
2616 if (_unlikely(![self hasSupportingRole]))
2624 if (![self unfiltered])
2629 _profile(Package$visible$section)
2630 section = [self section];
2633 _profile(Package$visible$isSectionVisible)
2634 if (!isSectionVisible(section))
2642 unsigned char current(iterator_->CurrentState);
2643 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2646 - (BOOL) halfConfigured {
2647 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2650 - (BOOL) halfInstalled {
2651 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2655 @synchronized (database_) {
2656 if ([database_ era] != era_ || iterator_.end())
2659 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2660 return state.Mode != pkgDepCache::ModeKeep;
2663 - (NSString *) mode {
2664 @synchronized (database_) {
2665 if ([database_ era] != era_ || iterator_.end())
2668 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2670 switch (state.Mode) {
2671 case pkgDepCache::ModeDelete:
2672 if ((state.iFlags & pkgDepCache::Purge) != 0)
2676 case pkgDepCache::ModeKeep:
2677 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2678 return @"REINSTALL";
2679 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2683 case pkgDepCache::ModeInstall:
2684 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2685 return @"REINSTALL";
2686 else*/ switch (state.Status) {
2688 return @"DOWNGRADE";
2694 return @"NEW_INSTALL";
2705 - (NSString *) name {
2706 return name_.empty() ? id_ : name_;
2709 - (UIImage *) icon {
2710 NSString *section = [self simpleSection];
2713 if (parsed_ != NULL)
2714 if (NSString *href = parsed_->icon_)
2715 if ([href hasPrefix:@"file:///"])
2716 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2717 if (icon == nil) if (section != nil)
2718 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2719 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2720 if ([dicon hasPrefix:@"file:///"])
2721 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2723 icon = [UIImage applicationImageNamed:@"unknown.png"];
2727 - (NSString *) homepage {
2728 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2731 - (NSString *) depiction {
2732 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2735 - (MIMEAddress *) sponsor {
2736 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2739 - (MIMEAddress *) author {
2740 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2743 - (NSString *) support {
2744 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2747 - (NSArray *) files {
2748 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2749 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2752 fin.open([path UTF8String]);
2757 while (std::getline(fin, line))
2758 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2763 - (NSString *) state {
2764 @synchronized (database_) {
2765 if ([database_ era] != era_ || file_.end())
2768 switch (iterator_->CurrentState) {
2769 case pkgCache::State::NotInstalled:
2770 return @"NotInstalled";
2771 case pkgCache::State::UnPacked:
2773 case pkgCache::State::HalfConfigured:
2774 return @"HalfConfigured";
2775 case pkgCache::State::HalfInstalled:
2776 return @"HalfInstalled";
2777 case pkgCache::State::ConfigFiles:
2778 return @"ConfigFiles";
2779 case pkgCache::State::Installed:
2780 return @"Installed";
2781 case pkgCache::State::TriggersAwaited:
2782 return @"TriggersAwaited";
2783 case pkgCache::State::TriggersPending:
2784 return @"TriggersPending";
2787 return (NSString *) [NSNull null];
2790 - (NSString *) selection {
2791 @synchronized (database_) {
2792 if ([database_ era] != era_ || file_.end())
2795 switch (iterator_->SelectedState) {
2796 case pkgCache::State::Unknown:
2798 case pkgCache::State::Install:
2800 case pkgCache::State::Hold:
2802 case pkgCache::State::DeInstall:
2803 return @"DeInstall";
2804 case pkgCache::State::Purge:
2808 return (NSString *) [NSNull null];
2811 - (NSArray *) warnings {
2812 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2813 const char *name(iterator_.Name());
2815 size_t length(strlen(name));
2816 if (length < 2) invalid:
2817 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2818 else for (size_t i(0); i != length; ++i)
2820 /* XXX: technically this is not allowed */
2821 (name[i] < 'A' || name[i] > 'Z') &&
2822 (name[i] < 'a' || name[i] > 'z') &&
2823 (name[i] < '0' || name[i] > '9') &&
2824 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2827 if (strcmp(name, "cydia") != 0) {
2830 bool _private = false;
2833 bool repository = [[self section] isEqualToString:@"Repositories"];
2835 if (NSArray *files = [self files])
2836 for (NSString *file in files)
2837 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2839 else if (!user && [file isEqualToString:@"/User"])
2841 else if (!_private && [file isEqualToString:@"/private"])
2843 else if (!stash && [file isEqualToString:@"/var/stash"])
2846 /* XXX: this is not sensitive enough. only some folders are valid. */
2847 if (cydia && !repository)
2848 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2850 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2852 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2854 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2857 return [warnings count] == 0 ? nil : warnings;
2860 - (NSArray *) applications {
2861 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2863 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2865 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2866 if (NSArray *files = [self files])
2867 for (NSString *file in files)
2868 if (application_r(file)) {
2869 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2870 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2871 if ([id isEqualToString:me])
2874 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2876 display = application_r[1];
2878 NSString *bundle([file stringByDeletingLastPathComponent]);
2879 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2880 // XXX: maybe this should check if this is really a string, not just for length
2881 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
2883 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2885 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2886 [applications addObject:application];
2888 [application addObject:id];
2889 [application addObject:display];
2890 [application addObject:url];
2893 return [applications count] == 0 ? nil : applications;
2896 - (Source *) source {
2897 if (source_ == nil) {
2898 @synchronized (database_) {
2899 if ([database_ era] != era_ || file_.end())
2900 source_ = (Source *) [NSNull null];
2902 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2906 return source_ == (Source *) [NSNull null] ? nil : source_;
2913 - (BOOL) matches:(NSArray *)query {
2914 if (query == nil || [query count] == 0)
2923 string = [self name];
2924 length = [string length];
2926 for (NSString *term in query) {
2927 range = [string rangeOfString:term options:MatchCompareOptions_];
2928 if (range.location != NSNotFound)
2929 rank_ -= 6 * 1000000 / length;
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;
2943 string = [self shortDescription];
2944 length = [string length];
2945 NSUInteger stop(std::min<NSUInteger>(length, 200));
2947 for (NSString *term in query) {
2948 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2949 if (range.location != NSNotFound)
2950 rank_ -= 2 * 100000;
2956 - (bool) hasSupportingRole {
2961 if ([Role_ isEqualToString:@"User"])
2965 if ([Role_ isEqualToString:@"Hacker"])
2969 if ([Role_ isEqualToString:@"Developer"])
2974 - (NSArray *) tags {
2978 - (BOOL) hasTag:(NSString *)tag {
2979 return tags_ == nil ? NO : [tags_ containsObject:tag];
2982 - (NSString *) primaryPurpose {
2983 for (NSString *tag in (NSArray *) tags_)
2984 if ([tag hasPrefix:@"purpose::"])
2985 return [tag substringFromIndex:9];
2989 - (NSArray *) purposes {
2990 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2991 for (NSString *tag in (NSArray *) tags_)
2992 if ([tag hasPrefix:@"purpose::"])
2993 [purposes addObject:[tag substringFromIndex:9]];
2994 return [purposes count] == 0 ? nil : purposes;
2997 - (bool) isCommercial {
2998 return [self hasTag:@"cydia::commercial"];
3001 - (void) setIndex:(size_t)index {
3002 if (metadata_->index_ != index)
3003 metadata_->index_ = index;
3006 - (CYString &) cyname {
3007 return name_.empty() ? id_ : name_;
3010 - (uint32_t) compareBySection:(NSArray *)sections {
3011 NSString *section([self section]);
3012 for (size_t i(0), e([sections count]); i != e; ++i) {
3013 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3017 return _not(uint32_t);
3021 @synchronized (database_) {
3022 pkgProblemResolver *resolver = [database_ resolver];
3023 resolver->Clear(iterator_);
3025 pkgCacheFile &cache([database_ cache]);
3026 cache->SetReInstall(iterator_, false);
3027 cache->MarkKeep(iterator_, false);
3031 @synchronized (database_) {
3032 pkgProblemResolver *resolver = [database_ resolver];
3033 resolver->Clear(iterator_);
3034 resolver->Protect(iterator_);
3036 pkgCacheFile &cache([database_ cache]);
3037 cache->SetReInstall(iterator_, false);
3038 cache->MarkInstall(iterator_, false);
3040 pkgDepCache::StateCache &state((*cache)[iterator_]);
3041 if (!state.Install())
3042 cache->SetReInstall(iterator_, true);
3046 @synchronized (database_) {
3047 pkgProblemResolver *resolver = [database_ resolver];
3048 resolver->Clear(iterator_);
3049 resolver->Remove(iterator_);
3050 resolver->Protect(iterator_);
3052 pkgCacheFile &cache([database_ cache]);
3053 cache->SetReInstall(iterator_, false);
3054 cache->MarkDelete(iterator_, true);
3057 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3058 _profile(Package$isUnfilteredAndSearchedForBy)
3061 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3062 value &= [self unfiltered];
3065 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3066 value &= [self matches:query];
3073 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3074 if ([search length] == 0)
3077 _profile(Package$isUnfilteredAndSelectedForBy)
3080 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3081 value &= [self unfiltered];
3084 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3085 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3092 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3093 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3096 - (bool) isVisibleInSection:(NSString *)name {
3097 NSString *section([self section]);
3101 section == nil && [name length] == 0 ||
3102 [name isEqualToString:section]
3103 ) && [self visible];
3106 - (bool) isVisibleInSource:(Source *)source {
3107 return [self source] == source && [self visible];
3112 /* Section Class {{{ */
3113 @interface Section : NSObject {
3118 _H<NSString> localized_;
3121 - (NSComparisonResult) compareByLocalized:(Section *)section;
3122 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3123 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3124 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3125 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3126 - (NSString *) name;
3133 - (void) addToCount;
3135 - (void) setCount:(size_t)count;
3136 - (NSString *) localized;
3140 @implementation Section
3142 - (NSComparisonResult) compareByLocalized:(Section *)section {
3143 NSString *lhs(localized_);
3144 NSString *rhs([section localized]);
3146 /*if ([lhs length] != 0 && [rhs length] != 0) {
3147 unichar lhc = [lhs characterAtIndex:0];
3148 unichar rhc = [rhs characterAtIndex:0];
3150 if (isalpha(lhc) && !isalpha(rhc))
3151 return NSOrderedAscending;
3152 else if (!isalpha(lhc) && isalpha(rhc))
3153 return NSOrderedDescending;
3156 return [lhs compare:rhs options:LaxCompareOptions_];
3159 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3160 if ((self = [self initWithName:name localize:NO]) != nil) {
3161 if (localized != nil)
3162 localized_ = localized;
3166 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3167 return [self initWithName:name row:0 localize:localize];
3170 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3171 if ((self = [super init]) != nil) {
3176 localized_ = LocalizeSection(name_);
3180 /* XXX: localize the index thingees */
3181 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3182 if ((self = [super init]) != nil) {
3183 name_ = [NSString stringWithCharacters:&index length:1];
3189 - (NSString *) name {
3209 - (void) addToCount {
3213 - (void) setCount:(size_t)count {
3217 - (NSString *) localized {
3224 class CydiaLogCleaner :
3225 public pkgArchiveCleaner
3228 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3233 /* Database Implementation {{{ */
3234 @implementation Database
3236 + (Database *) sharedInstance {
3237 static _H<Database> instance;
3238 if (instance == nil)
3239 instance = [[[Database alloc] init] autorelease];
3247 - (void) releasePackages {
3248 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3249 CFArrayRemoveAllValues(packages_);
3253 // XXX: actually implement this thing
3255 [self releasePackages];
3256 apr_pool_destroy(pool_);
3257 NSRecycleZone(zone_);
3261 - (void) _readCydia:(NSNumber *)fd {
3262 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3263 std::istream is(&ib);
3266 static Pcre finish_r("^finish:([^:]*)$");
3268 while (std::getline(is, line)) {
3269 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3271 const char *data(line.c_str());
3272 size_t size = line.size();
3273 lprintf("C:%s\n", data);
3275 if (finish_r(data, size)) {
3276 NSString *finish = finish_r[1];
3277 int index = [Finishes_ indexOfObject:finish];
3278 if (index != INT_MAX && index > Finish_)
3288 - (void) _readStatus:(NSNumber *)fd {
3289 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3290 std::istream is(&ib);
3293 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3294 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3296 while (std::getline(is, line)) {
3297 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3299 const char *data(line.c_str());
3300 size_t size(line.size());
3301 lprintf("S:%s\n", data);
3303 if (conffile_r(data, size)) {
3304 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3305 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3306 } else if (strncmp(data, "status: ", 8) == 0) {
3307 // status: <package>: {unpacked,half-configured,installed}
3308 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3309 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3310 } else if (strncmp(data, "processing: ", 12) == 0) {
3311 // processing: configure: config-test
3312 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3313 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3314 } else if (pmstatus_r(data, size)) {
3315 std::string type([pmstatus_r[1] UTF8String]);
3317 NSString *package = pmstatus_r[2];
3318 if ([package isEqualToString:@"dpkg-exec"])
3321 float percent([pmstatus_r[3] floatValue]);
3322 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3324 NSString *string = pmstatus_r[4];
3326 if (type == "pmerror") {
3327 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3328 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3329 } else if (type == "pmstatus") {
3330 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3331 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3332 } else if (type == "pmconffile")
3333 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3335 lprintf("E:unknown pmstatus\n");
3337 lprintf("E:unknown status\n");
3345 - (void) _readOutput:(NSNumber *)fd {
3346 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3347 std::istream is(&ib);
3350 while (std::getline(is, line)) {
3351 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3353 lprintf("O:%s\n", line.c_str());
3355 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3356 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3368 - (Package *) packageWithName:(NSString *)name {
3371 @synchronized (self) {
3372 if (static_cast<pkgDepCache *>(cache_) == NULL)
3374 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3375 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3379 if ((self = [super init]) != nil) {
3386 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3387 apr_pool_create(&pool_, NULL);
3389 size_t capacity(MetaFile_->active_);
3395 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3396 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3400 _assert(pipe(fds) != -1);
3403 _config->Set("APT::Keep-Fds::", cydiafd_);
3404 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3407 detachNewThreadSelector:@selector(_readCydia:)
3409 withObject:[NSNumber numberWithInt:fds[0]]
3412 _assert(pipe(fds) != -1);
3416 detachNewThreadSelector:@selector(_readStatus:)
3418 withObject:[NSNumber numberWithInt:fds[0]]
3421 _assert(pipe(fds) != -1);
3422 _assert(dup2(fds[0], 0) != -1);
3423 _assert(close(fds[0]) != -1);
3425 input_ = fdopen(fds[1], "a");
3427 _assert(pipe(fds) != -1);
3428 _assert(dup2(fds[1], 1) != -1);
3429 _assert(close(fds[1]) != -1);
3432 detachNewThreadSelector:@selector(_readOutput:)
3434 withObject:[NSNumber numberWithInt:fds[0]]
3439 - (pkgCacheFile &) cache {
3443 - (pkgDepCache::Policy *) policy {
3447 - (pkgRecords *) records {
3451 - (pkgProblemResolver *) resolver {
3455 - (pkgAcquire &) fetcher {
3459 - (pkgSourceList &) list {
3463 - (NSArray *) packages {
3464 return (NSArray *) packages_;
3467 - (NSArray *) sources {
3471 - (Source *) sourceWithKey:(NSString *)key {
3472 for (Source *source in [self sources]) {
3473 if ([[source key] isEqualToString:key])
3478 - (bool) popErrorWithTitle:(NSString *)title {
3481 while (!_error->empty()) {
3483 bool warning(!_error->PopMessage(error));
3488 size_t size(error.size());
3489 if (size == 0 || error[size - 1] != '\n')
3491 error.resize(size - 1);
3494 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3496 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3497 if (warning && no_pubkey(error.c_str()))
3500 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3506 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3507 return [self popErrorWithTitle:title] || !success;
3510 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3511 @synchronized (self) {
3514 [self releasePackages];
3517 [sourceList_ removeAllObjects];
3537 apr_pool_clear(pool_);
3539 NSRecycleZone(zone_);
3540 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3542 int chk(creat("/tmp/cydia.chk", 0644));
3546 if (invocation != nil)
3547 [invocation invoke];
3549 NSString *title(UCLocalize("DATABASE"));
3551 list_ = new pkgSourceList();
3552 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3555 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3556 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3557 [sourceList_ addObject:object];
3561 OpProgress progress;
3563 if (!cache_.Open(progress, true)) {
3564 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3565 while (!_error->empty()) {
3567 bool warning(!_error->PopMessage(error));
3569 lprintf("cache_.Open():[%s]\n", error.c_str());
3571 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3575 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3576 repair = @selector(configure);
3577 //else if (error == "The package lists or status file could not be parsed or opened.")
3578 // repair = @selector(update);
3579 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3580 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3581 // else if (error == "Malformed Status line")
3582 // else if (error == "The list of sources could not be read.")
3584 if (repair != NULL) {
3586 [delegate_ repairWithSelector:repair];
3595 unlink("/tmp/cydia.chk");
3597 now_ = [[NSDate date] timeIntervalSince1970];
3599 policy_ = new pkgDepCache::Policy();
3600 records_ = new pkgRecords(cache_);
3601 resolver_ = new pkgProblemResolver(cache_);
3602 fetcher_ = new pkgAcquire(&status_);
3605 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3606 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3610 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3613 if (cache_->BrokenCount() != 0) {
3614 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3617 if (cache_->BrokenCount() != 0) {
3618 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3622 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3626 for (Source *object in (id) sourceList_) {
3627 metaIndex *source([object metaIndex]);
3628 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3629 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3630 // XXX: this could be more intelligent
3631 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3632 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3634 sourceMap_[cached->ID] = object;
3639 /*std::vector<Package *> packages;
3640 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3645 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3646 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3647 //packages.push_back(package);
3648 CFArrayAppendValue(packages_, CFRetain(package));
3652 /*if (packages.empty())
3653 packages_ = [[NSArray alloc] init];
3655 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3658 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3659 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3660 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3668 /*if (!packages.empty())
3669 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3670 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3672 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3674 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3676 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3680 size_t count(CFArrayGetCount(packages_));
3681 MetaFile_->active_ = count;
3683 for (size_t index(0); index != count; ++index)
3684 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3691 @synchronized (self) {
3693 resolver_ = new pkgProblemResolver(cache_);
3695 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3696 if (!cache_[iterator].Keep())
3697 cache_->MarkKeep(iterator, false);
3698 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3699 cache_->SetReInstall(iterator, false);
3702 - (void) configure {
3703 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3705 system([dpkg UTF8String]);
3710 @synchronized (self) {
3711 // XXX: I don't remember this condition
3716 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3718 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3720 if ([self popErrorWithTitle:title])
3724 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3726 CydiaLogCleaner cleaner;
3727 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3734 fetcher_->Shutdown();
3736 pkgRecords records(cache_);
3738 lock_ = new FileFd();
3739 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3741 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3743 if ([self popErrorWithTitle:title])
3747 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3750 manager_ = (_system->CreatePM(cache_));
3751 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3758 bool substrate(RestartSubstrate_);
3759 RestartSubstrate_ = false;
3761 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3763 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3765 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3767 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3768 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3771 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3773 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3775 [self popErrorWithTitle:title];
3779 bool failed = false;
3780 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3781 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3783 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3786 std::string uri = (*item)->DescURI();
3787 std::string error = (*item)->ErrorText;
3789 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3792 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3793 [delegate_ addProgressEventOnMainThread:event forTask:title];
3796 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3804 RestartSubstrate_ = true;
3807 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3808 if ([self popErrorWithTitle:title])
3811 if (result == pkgPackageManager::Failed) {
3816 if (result != pkgPackageManager::Completed) {
3821 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3823 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3825 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3826 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3829 if (![before isEqualToArray:after])
3834 NSString *title(UCLocalize("UPGRADE"));
3835 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3841 [self updateWithStatus:status_];
3844 - (void) updateWithStatus:(Status &)status {
3845 NSString *title(UCLocalize("REFRESHING_DATA"));
3848 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3852 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3853 if ([self popErrorWithTitle:title])
3856 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3858 bool success(ListUpdate(status, list, PulseInterval_));
3859 if (status.WasCancelled())
3862 [self popErrorWithTitle:title forOperation:success];
3863 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3867 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3870 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3871 delegate_ = delegate;
3874 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3875 progress_ = delegate;
3876 status_.setDelegate(delegate);
3879 - (NSObject<ProgressDelegate> *) progressDelegate {
3883 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3884 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3885 return i == sourceMap_.end() ? nil : i->second;
3888 - (NSString *) mappedSectionForPointer:(const char *)section {
3889 _H<NSString> *mapped;
3891 _profile(Database$mappedSectionForPointer$Cache)
3892 mapped = §ions_[section];
3895 if (*mapped == NULL) {
3896 size_t length(strlen(section));
3897 char spaced[length + 1];
3899 _profile(Database$mappedSectionForPointer$Replace)
3900 for (size_t index(0); index != length; ++index)
3901 spaced[index] = section[index] == '_' ? ' ' : section[index];
3902 spaced[length] = '\0';
3907 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3908 string = [NSString stringWithUTF8String:spaced];
3911 _profile(Database$mappedSectionForPointer$Map)
3912 string = [SectionMap_ objectForKey:string] ?: string;
3922 static _H<NSMutableSet> Diversions_;
3924 @interface Diversion : NSObject {
3927 _H<NSString> format_;
3932 @implementation Diversion
3934 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3935 if ((self = [super init]) != nil) {
3936 pattern_ = [from UTF8String];
3942 - (NSString *) divert:(NSString *)url {
3943 return !pattern_(url) ? nil : pattern_->*format_;
3946 + (NSURL *) divertURL:(NSURL *)url {
3948 NSString *href([url absoluteString]);
3950 for (Diversion *diversion in (id) Diversions_)
3951 if (NSString *diverted = [diversion divert:href]) {
3953 NSLog(@"div: %@", diverted);
3955 url = [NSURL URLWithString:diverted];
3962 - (NSString *) key {
3966 - (NSUInteger) hash {
3970 - (BOOL) isEqual:(Diversion *)object {
3971 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3976 @interface CydiaObject : NSObject {
3977 _H<CyteWebViewController> indirect_;
3978 _transient id delegate_;
3981 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3987 @interface CydiaWebViewController : CyteWebViewController {
3988 _H<CydiaObject> cydia_;
3991 + (void) addDiversion:(Diversion *)diversion;
3992 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
3993 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
3994 - (void) setDelegate:(id)delegate;
3998 /* Web Scripting {{{ */
3999 @implementation CydiaObject
4001 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4002 if ((self = [super init]) != nil) {
4003 indirect_ = (CyteWebViewController *) indirect;
4007 - (void) setDelegate:(id)delegate {
4008 delegate_ = delegate;
4011 + (NSArray *) _attributeKeys {
4012 return [NSArray arrayWithObjects:
4015 @"coreFoundationVersionNumber",
4032 - (NSArray *) attributeKeys {
4033 return [[self class] _attributeKeys];
4036 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4037 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4040 - (NSString *) version {
4044 - (NSString *) build {
4048 - (NSString *) coreFoundationVersionNumber {
4049 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4052 - (NSString *) device {
4053 return UniqueIdentifier();
4056 - (NSString *) firmware {
4057 return [[UIDevice currentDevice] systemVersion];
4060 - (NSString *) hostname {
4061 return [[UIDevice currentDevice] name];
4064 - (NSString *) idiom {
4065 return (id) Idiom_ ?: [NSNull null];
4068 - (NSString *) mcc {
4069 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4070 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4074 - (NSString *) mnc {
4075 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4076 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4080 - (NSString *) operator {
4081 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4082 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4086 - (NSString *) bbsnum {
4087 return (id) BBSNum_ ?: [NSNull null];
4090 - (NSString *) ecid {
4091 return (id) ChipID_ ?: [NSNull null];
4094 - (NSString *) serial {
4095 return SerialNumber_;
4098 - (NSString *) role {
4099 return (id) Role_ ?: [NSNull null];
4102 - (NSString *) model {
4103 return [NSString stringWithUTF8String:Machine_];
4106 - (NSString *) token {
4107 return (id) Token_ ?: [NSNull null];
4110 + (NSString *) webScriptNameForSelector:(SEL)selector {
4112 else if (selector == @selector(addBridgedHost:))
4113 return @"addBridgedHost";
4114 else if (selector == @selector(addInsecureHost:))
4115 return @"addInsecureHost";
4116 else if (selector == @selector(addInternalRedirect::))
4117 return @"addInternalRedirect";
4118 else if (selector == @selector(addPipelinedHost:scheme:))
4119 return @"addPipelinedHost";
4120 else if (selector == @selector(addSource:::))
4121 return @"addSource";
4122 else if (selector == @selector(addTokenHost:))
4123 return @"addTokenHost";
4124 else if (selector == @selector(addTrivialSource:))
4125 return @"addTrivialSource";
4126 else if (selector == @selector(close))
4128 else if (selector == @selector(du:))
4130 else if (selector == @selector(stringWithFormat:arguments:))
4132 else if (selector == @selector(getAllSources))
4133 return @"getAllSources";
4134 else if (selector == @selector(getKernelNumber:))
4135 return @"getKernelNumber";
4136 else if (selector == @selector(getKernelString:))
4137 return @"getKernelString";
4138 else if (selector == @selector(getInstalledPackages))
4139 return @"getInstalledPackages";
4140 else if (selector == @selector(getIORegistryEntry::))
4141 return @"getIORegistryEntry";
4142 else if (selector == @selector(getLocaleIdentifier))
4143 return @"getLocaleIdentifier";
4144 else if (selector == @selector(getPreferredLanguages))
4145 return @"getPreferredLanguages";
4146 else if (selector == @selector(getPackageById:))
4147 return @"getPackageById";
4148 else if (selector == @selector(getMetadataKeys))
4149 return @"getMetadataKeys";
4150 else if (selector == @selector(getMetadataValue:))
4151 return @"getMetadataValue";
4152 else if (selector == @selector(getSessionValue:))
4153 return @"getSessionValue";
4154 else if (selector == @selector(installPackages:))
4155 return @"installPackages";
4156 else if (selector == @selector(isReachable:))
4157 return @"isReachable";
4158 else if (selector == @selector(localizedStringForKey:value:table:))
4160 else if (selector == @selector(popViewController:))
4161 return @"popViewController";
4162 else if (selector == @selector(refreshSources))
4163 return @"refreshSources";
4164 else if (selector == @selector(registerFrame:))
4165 return @"registerFrame";
4166 else if (selector == @selector(removeButton))
4167 return @"removeButton";
4168 else if (selector == @selector(saveConfig))
4169 return @"saveConfig";
4170 else if (selector == @selector(setMetadataValue::))
4171 return @"setMetadataValue";
4172 else if (selector == @selector(setSessionValue::))
4173 return @"setSessionValue";
4174 else if (selector == @selector(setShowPromoted:))
4175 return @"setShowPromoted";
4176 else if (selector == @selector(substitutePackageNames:))
4177 return @"substitutePackageNames";
4178 else if (selector == @selector(scrollToBottom:))
4179 return @"scrollToBottom";
4180 else if (selector == @selector(setAllowsNavigationAction:))
4181 return @"setAllowsNavigationAction";
4182 else if (selector == @selector(setBadgeValue:))
4183 return @"setBadgeValue";
4184 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4185 return @"setButtonImage";
4186 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4187 return @"setButtonTitle";
4188 else if (selector == @selector(setHidesBackButton:))
4189 return @"setHidesBackButton";
4190 else if (selector == @selector(setHidesNavigationBar:))
4191 return @"setHidesNavigationBar";
4192 else if (selector == @selector(setNavigationBarStyle:))
4193 return @"setNavigationBarStyle";
4194 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4195 return @"setNavigationBarTintColor";
4196 else if (selector == @selector(setPasteboardString:))
4197 return @"setPasteboardString";
4198 else if (selector == @selector(setPasteboardURL:))
4199 return @"setPasteboardURL";
4200 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4201 return @"setScrollAlwaysBounceVertical";
4202 else if (selector == @selector(setScrollIndicatorStyle:))
4203 return @"setScrollIndicatorStyle";
4204 else if (selector == @selector(setToken:))
4206 else if (selector == @selector(setViewportWidth:))
4207 return @"setViewportWidth";
4208 else if (selector == @selector(statfs:))
4210 else if (selector == @selector(supports:))
4212 else if (selector == @selector(unload))
4218 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4219 return [self webScriptNameForSelector:selector] == nil;
4222 - (BOOL) supports:(NSString *)feature {
4223 return [feature isEqualToString:@"window.open"];
4227 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4230 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4231 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4234 - (void) setScrollIndicatorStyle:(NSString *)style {
4235 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4238 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4239 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4242 - (NSNumber *) getKernelNumber:(NSString *)name {
4243 const char *string([name UTF8String]);
4246 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4247 return (id) [NSNull null];
4249 if (size != sizeof(int))
4250 return (id) [NSNull null];
4253 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4254 return (id) [NSNull null];
4256 return [NSNumber numberWithInt:value];
4259 - (NSString *) getKernelString:(NSString *)name {
4260 const char *string([name UTF8String]);
4263 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4264 return (id) [NSNull null];
4266 char value[size + 1];
4267 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4268 return (id) [NSNull null];
4270 // XXX: just in case you request something ludicrous
4273 return [NSString stringWithCString:value];
4276 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4277 NSObject *value(CYIOGetValue([path UTF8String], entry));
4280 if ([value isKindOfClass:[NSData class]])
4281 value = CYHex((NSData *) value);
4286 - (NSArray *) getMetadataKeys {
4287 @synchronized (Values_) {
4288 return [Values_ allKeys];
4291 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4292 WebFrame *frame([iframe contentFrame]);
4293 [indirect_ registerFrame:frame];
4296 - (void) _setShowPromoted:(NSNumber *)value {
4297 [Metadata_ setObject:value forKey:@"ShowPromoted"];
4301 - (void) setShowPromoted:(NSNumber *)value {
4302 [self performSelectorOnMainThread:@selector(_setShowPromoted:) withObject:value waitUntilDone:NO];
4305 - (id) getMetadataValue:(NSString *)key {
4306 @synchronized (Values_) {
4307 return [Values_ objectForKey:key];
4310 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4311 @synchronized (Values_) {
4312 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4313 [Values_ removeObjectForKey:key];
4315 [Values_ setObject:value forKey:key];
4317 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4320 - (id) getSessionValue:(NSString *)key {
4321 @synchronized (SessionData_) {
4322 return [SessionData_ objectForKey:key];
4325 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4326 @synchronized (SessionData_) {
4327 if (value == (id) [WebUndefined undefined])
4328 [SessionData_ removeObjectForKey:key];
4330 [SessionData_ setObject:value forKey:key];
4333 - (void) addBridgedHost:(NSString *)host {
4334 @synchronized (HostConfig_) {
4335 [BridgedHosts_ addObject:host];
4338 - (void) addInsecureHost:(NSString *)host {
4339 @synchronized (HostConfig_) {
4340 [InsecureHosts_ addObject:host];
4343 - (void) addTokenHost:(NSString *)host {
4344 @synchronized (HostConfig_) {
4345 [TokenHosts_ addObject:host];
4348 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4349 @synchronized (HostConfig_) {
4350 if (scheme != (id) [WebUndefined undefined])
4351 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4353 [PipelinedHosts_ addObject:host];
4356 - (void) popViewController:(NSNumber *)value {
4357 if (value == (id) [WebUndefined undefined])
4358 value = [NSNumber numberWithBool:YES];
4359 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4362 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4363 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4365 for (NSString *section in sections)
4366 [array addObject:section];
4368 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4371 distribution, @"Distribution",
4373 nil] waitUntilDone:NO];
4376 - (void) addTrivialSource:(NSString *)href {
4377 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4380 - (void) refreshSources {
4381 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4384 - (void) saveConfig {
4385 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4388 - (NSArray *) getAllSources {
4389 return [[Database sharedInstance] sources];
4392 - (NSArray *) getInstalledPackages {
4393 Database *database([Database sharedInstance]);
4394 @synchronized (database) {
4395 NSArray *packages([database packages]);
4396 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4397 for (Package *package in packages)
4398 if (![package uninstalled])
4399 [installed addObject:package];
4403 - (Package *) getPackageById:(NSString *)id {
4404 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4408 return (Package *) [NSNull null];
4411 - (NSString *) getLocaleIdentifier {
4412 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4415 - (NSArray *) getPreferredLanguages {
4419 - (NSArray *) statfs:(NSString *)path {
4422 if (path == nil || statfs([path UTF8String], &stat) == -1)
4425 return [NSArray arrayWithObjects:
4426 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4427 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4428 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4432 - (NSNumber *) du:(NSString *)path {
4433 NSNumber *value(nil);
4436 _assert(pipe(fds) != -1);
4438 pid_t pid(ExecFork());
4440 _assert(dup2(fds[1], 1) != -1);
4441 _assert(close(fds[0]) != -1);
4442 _assert(close(fds[1]) != -1);
4443 /* XXX: this should probably not use du */
4444 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4449 _assert(close(fds[1]) != -1);
4451 if (FILE *du = fdopen(fds[0], "r")) {
4453 while (fgets(line, sizeof(line), du) != NULL) {
4454 size_t length(strlen(line));
4455 while (length != 0 && line[length - 1] == '\n')
4456 line[--length] = '\0';
4457 if (char *tab = strchr(line, '\t')) {
4459 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4464 } else _assert(close(fds[0]));
4472 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4475 - (NSNumber *) isReachable:(NSString *)name {
4476 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4479 - (void) installPackages:(NSArray *)packages {
4480 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4483 - (NSString *) substitutePackageNames:(NSString *)message {
4484 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4485 for (size_t i(0), e([words count]); i != e; ++i) {
4486 NSString *word([words objectAtIndex:i]);
4487 if (Package *package = [[Database sharedInstance] packageWithName:word])
4488 [words replaceObjectAtIndex:i withObject:[package name]];
4491 return [words componentsJoinedByString:@" "];
4494 - (void) removeButton {
4495 [indirect_ removeButton];
4498 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4499 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4502 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4503 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4506 - (void) setBadgeValue:(id)value {
4507 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4510 - (void) setAllowsNavigationAction:(NSString *)value {
4511 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4514 - (void) setHidesBackButton:(NSString *)value {
4515 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4518 - (void) setHidesNavigationBar:(NSString *)value {
4519 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4522 - (void) setNavigationBarStyle:(NSString *)value {
4523 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4526 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4527 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4528 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4529 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4532 - (void) setPasteboardString:(NSString *)value {
4533 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4536 - (void) setPasteboardURL:(NSString *)value {
4537 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4540 - (void) _setToken:(NSString *)token {
4544 [Metadata_ removeObjectForKey:@"Token"];
4546 [Metadata_ setObject:Token_ forKey:@"Token"];
4551 - (void) setToken:(NSString *)token {
4552 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4555 - (void) scrollToBottom:(NSNumber *)animated {
4556 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4559 - (void) setViewportWidth:(float)width {
4560 [indirect_ setViewportWidthOnMainThread:width];
4563 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4564 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4565 unsigned count([arguments count]);
4567 for (unsigned i(0); i != count; ++i)
4568 values[i] = [arguments objectAtIndex:i];
4569 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4572 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4573 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4575 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4577 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4583 @interface NSURL (CydiaSecure)
4586 @implementation NSURL (CydiaSecure)
4588 - (bool) isCydiaSecure {
4589 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4592 @synchronized (HostConfig_) {
4593 if ([InsecureHosts_ containsObject:[self host]])
4602 /* Cydia Browser Controller {{{ */
4603 @implementation CydiaWebViewController
4605 - (NSURL *) navigationURL {
4606 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4609 + (void) _initialize {
4610 [super _initialize];
4612 Diversions_ = [NSMutableSet setWithCapacity:0];
4615 + (void) addDiversion:(Diversion *)diversion {
4616 [Diversions_ addObject:diversion];
4619 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4620 [super webView:view didClearWindowObject:window forFrame:frame];
4621 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4624 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4625 WebDataSource *source([frame dataSource]);
4626 NSURLResponse *response([source response]);
4627 NSURL *url([response URL]);
4628 NSString *scheme([[url scheme] lowercaseString]);
4630 bool bridged(false);
4632 @synchronized (HostConfig_) {
4633 if ([scheme isEqualToString:@"file"])
4635 else if ([scheme isEqualToString:@"https"])
4636 if ([BridgedHosts_ containsObject:[url host]])
4641 [window setValue:cydia forKey:@"cydia"];
4644 - (void) _setupMail:(MFMailComposeViewController *)controller {
4645 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4647 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4648 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4651 - (NSURL *) URLWithURL:(NSURL *)url {
4652 return [Diversion divertURL:url];
4655 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4656 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4659 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4660 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4662 NSURL *url([copy URL]);
4663 NSString *href([url absoluteString]);
4664 NSString *host([url host]);
4666 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4667 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4668 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4669 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4672 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4673 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4675 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4679 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4680 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4681 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4682 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4687 @synchronized (HostConfig_) {
4688 bridged = [BridgedHosts_ containsObject:host];
4689 token = [TokenHosts_ containsObject:host];
4692 if ([url isCydiaSecure]) {
4694 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4695 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4697 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4698 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4705 - (void) setDelegate:(id)delegate {
4706 [super setDelegate:delegate];
4707 [cydia_ setDelegate:delegate];
4710 - (NSString *) applicationNameForUserAgent {
4715 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4716 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4722 @interface AppCacheController : CydiaWebViewController {
4727 @implementation AppCacheController
4729 - (void) didReceiveMemoryWarning {
4730 // XXX: this doesn't work
4733 - (bool) retainsNetworkActivityIndicator {
4741 @interface NSObject (CydiaScript)
4742 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4745 @implementation NSObject (CydiaScript)
4747 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4753 @implementation NSArray (CydiaScript)
4755 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4756 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4757 for (size_t i(0), e([self count]); i != e; ++i)
4758 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4764 @implementation NSDictionary (CydiaScript)
4766 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4767 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4769 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4776 /* Confirmation Controller {{{ */
4777 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4778 if (!iterator.end())
4779 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4780 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4782 pkgCache::PkgIterator package(dep.TargetPkg());
4785 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4792 @protocol ConfirmationControllerDelegate
4793 - (void) cancelAndClear:(bool)clear;
4794 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4798 @interface ConfirmationController : CydiaWebViewController {
4799 _transient Database *database_;
4801 _H<UIAlertView> essential_;
4803 _H<NSDictionary> changes_;
4804 _H<NSMutableArray> issues_;
4805 _H<NSDictionary> sizes_;
4810 - (id) initWithDatabase:(Database *)database;
4814 @implementation ConfirmationController
4818 RestartSubstrate_ = true;
4819 [delegate_ confirmWithNavigationController:[self navigationController]];
4822 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4823 NSString *context([alert context]);
4825 if ([context isEqualToString:@"remove"]) {
4826 if (button == [alert cancelButtonIndex])
4827 [self dismissModalViewControllerAnimated:YES];
4828 else if (button == [alert firstOtherButtonIndex]) {
4829 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
4832 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4833 } else if ([context isEqualToString:@"unable"]) {
4834 [self dismissModalViewControllerAnimated:YES];
4835 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4837 [super alertView:alert clickedButtonAtIndex:button];
4841 - (void) _doContinue {
4842 [delegate_ cancelAndClear:NO];
4843 [self dismissModalViewControllerAnimated:YES];
4846 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4847 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4851 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4852 [super webView:view didClearWindowObject:window forFrame:frame];
4854 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4855 (id) changes_, @"changes",
4856 (id) issues_, @"issues",
4857 (id) sizes_, @"sizes",
4859 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4862 - (id) initWithDatabase:(Database *)database {
4863 if ((self = [super init]) != nil) {
4864 database_ = database;
4866 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4867 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4868 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4869 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4870 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4874 pkgCacheFile &cache([database_ cache]);
4875 NSArray *packages([database_ packages]);
4876 pkgDepCache::Policy *policy([database_ policy]);
4878 issues_ = [NSMutableArray arrayWithCapacity:4];
4880 for (Package *package in packages) {
4881 pkgCache::PkgIterator iterator([package iterator]);
4882 NSString *name([package id]);
4884 if ([package broken]) {
4885 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4887 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4889 reasons, @"reasons",
4892 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4896 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4897 pkgCache::DepIterator start;
4898 pkgCache::DepIterator end;
4899 dep.GlobOr(start, end); // ++dep
4901 if (!cache->IsImportantDep(end))
4903 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4906 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4908 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4909 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4910 clauses, @"clauses",
4914 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4916 pkgCache::PkgIterator target(start.TargetPkg());
4917 if (target->ProvidesList != 0)
4918 reason = @"missing";
4920 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4922 reason = @"installed";
4923 installed = [NSString stringWithUTF8String:ver.VerStr()];
4924 } else if (!cache[target].CandidateVerIter(cache).end())
4925 reason = @"uninstalled";
4926 else if (target->ProvidesList == 0)
4927 reason = @"uninstallable";
4929 reason = @"virtual";
4932 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4933 [NSString stringWithUTF8String:start.CompType()], @"operator",
4934 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4937 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4938 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4939 version, @"version",
4941 installed, @"installed",
4944 // yes, seriously. (wtf?)
4952 pkgDepCache::StateCache &state(cache[iterator]);
4954 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4956 if (state.NewInstall())
4957 [installs addObject:name];
4958 // XXX: else if (state.Install())
4959 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4960 [reinstalls addObject:name];
4961 // XXX: move before previous if
4962 else if (state.Upgrade())
4963 [upgrades addObject:name];
4964 else if (state.Downgrade())
4965 [downgrades addObject:name];
4966 else if (!state.Delete())
4967 // XXX: _assert(state.Keep());
4969 else if (special_r(name))
4970 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4971 [NSNull null], @"package",
4972 [NSArray arrayWithObjects:
4973 [NSDictionary dictionaryWithObjectsAndKeys:
4974 @"Conflicts", @"relationship",
4975 [NSArray arrayWithObjects:
4976 [NSDictionary dictionaryWithObjectsAndKeys:
4978 [NSNull null], @"version",
4979 @"installed", @"reason",
4986 if ([package essential])
4988 [removes addObject:name];
4991 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4992 substrate_ |= DepSubstrate(iterator.CurrentVer());
4997 else if (Advanced_) {
4998 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5000 essential_ = [[[UIAlertView alloc]
5001 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5002 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5004 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5006 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5010 [essential_ setContext:@"remove"];
5011 [essential_ setNumberOfRows:2];
5013 essential_ = [[[UIAlertView alloc]
5014 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5015 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5017 cancelButtonTitle:UCLocalize("OKAY")
5018 otherButtonTitles:nil
5021 [essential_ setContext:@"unable"];
5024 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5025 installs, @"installs",
5026 reinstalls, @"reinstalls",
5027 upgrades, @"upgrades",
5028 downgrades, @"downgrades",
5029 removes, @"removes",
5032 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5033 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5034 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5037 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5041 - (UIBarButtonItem *) leftButton {
5042 return [[[UIBarButtonItem alloc]
5043 initWithTitle:UCLocalize("CANCEL")
5044 style:UIBarButtonItemStylePlain
5046 action:@selector(cancelButtonClicked)
5051 - (void) applyRightButton {
5052 if ([issues_ count] == 0 && ![self isLoading])
5053 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5054 initWithTitle:UCLocalize("CONFIRM")
5055 style:UIBarButtonItemStyleDone
5057 action:@selector(confirmButtonClicked)
5060 [[self navigationItem] setRightBarButtonItem:nil];
5064 - (void) cancelButtonClicked {
5065 [delegate_ cancelAndClear:YES];
5066 [self dismissModalViewControllerAnimated:YES];
5070 - (void) confirmButtonClicked {
5071 if (essential_ != nil)
5081 /* Progress Data {{{ */
5082 @interface CydiaProgressData : NSObject {
5083 _transient id delegate_;
5092 _H<NSMutableArray> events_;
5093 _H<NSString> title_;
5095 _H<NSString> status_;
5096 _H<NSString> finish_;
5101 @implementation CydiaProgressData
5103 + (NSArray *) _attributeKeys {
5104 return [NSArray arrayWithObjects:
5116 - (NSArray *) attributeKeys {
5117 return [[self class] _attributeKeys];
5120 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5121 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5125 if ((self = [super init]) != nil) {
5126 events_ = [NSMutableArray arrayWithCapacity:32];
5134 - (void) setDelegate:(id)delegate {
5135 delegate_ = delegate;
5138 - (void) setPercent:(float)value {
5142 - (NSNumber *) percent {
5143 return [NSNumber numberWithFloat:percent_];
5146 - (void) setCurrent:(float)value {
5150 - (NSNumber *) current {
5151 return [NSNumber numberWithFloat:current_];
5154 - (void) setTotal:(float)value {
5158 - (NSNumber *) total {
5159 return [NSNumber numberWithFloat:total_];
5162 - (void) setSpeed:(float)value {
5166 - (NSNumber *) speed {
5167 return [NSNumber numberWithFloat:speed_];
5170 - (NSArray *) events {
5174 - (void) removeAllEvents {
5175 [events_ removeAllObjects];
5178 - (void) addEvent:(CydiaProgressEvent *)event {
5179 [events_ addObject:event];
5182 - (void) setTitle:(NSString *)text {
5186 - (NSString *) title {
5190 - (void) setFinish:(NSString *)text {
5194 - (NSString *) finish {
5195 return (id) finish_ ?: [NSNull null];
5198 - (void) setRunning:(bool)running {
5202 - (NSNumber *) running {
5203 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5208 /* Progress Controller {{{ */
5209 @interface ProgressController : CydiaWebViewController <
5212 _transient Database *database_;
5213 _H<CydiaProgressData, 1> progress_;
5217 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5219 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5221 - (void) setTitle:(NSString *)title;
5222 - (void) setCancellable:(bool)cancellable;
5226 @implementation ProgressController
5229 [database_ setProgressDelegate:nil];
5233 - (UIBarButtonItem *) leftButton {
5234 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5235 initWithTitle:UCLocalize("CANCEL")
5236 style:UIBarButtonItemStylePlain
5238 action:@selector(cancel)
5239 ] autorelease] : nil;
5242 - (void) updateCancel {
5243 [super applyLeftButton];
5246 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5247 if ((self = [super init]) != nil) {
5248 database_ = database;
5249 delegate_ = delegate;
5251 [database_ setProgressDelegate:self];
5253 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5254 [progress_ setDelegate:self];
5256 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5258 [scroller_ setBackgroundColor:[UIColor blackColor]];
5260 [[self navigationItem] setHidesBackButton:YES];
5262 [self updateCancel];
5266 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5267 [super webView:view didClearWindowObject:window forFrame:frame];
5268 [window setValue:progress_ forKey:@"cydiaProgress"];
5271 - (void) updateProgress {
5272 [self dispatchEvent:@"CydiaProgressUpdate"];
5275 - (void) viewWillAppear:(BOOL)animated {
5276 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5277 [super viewWillAppear:animated];
5280 - (void) reloadSpringBoard {
5281 if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
5282 system("/bin/launchctl stop com.apple.backboardd");
5284 system("/usr/bin/killall backboardd SpringBoard sbreload");
5288 pid_t pid(ExecFork());
5290 pid_t pid(ExecFork());
5292 execl("/usr/bin/sbreload", "sbreload", NULL);
5303 system("/usr/bin/killall backboardd SpringBoard sbreload");
5307 UpdateExternalStatus(0);
5310 [delegate_ saveState];
5314 [delegate_ returnToCydia];
5318 [delegate_ terminateWithSuccess];
5319 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5320 [delegate_ suspendWithAnimation:YES];
5322 [delegate_ suspend];*/
5334 UIProgressHUD *hud([delegate_ addProgressHUD]);
5335 [hud setText:UCLocalize("LOADING")];
5336 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5342 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5343 SBReboot(SBSSpringBoardServerPort());
5345 reboot2(RB_AUTOBOOT);
5352 - (void) setTitle:(NSString *)title {
5353 [progress_ setTitle:title];
5354 [self updateProgress];
5357 - (UIBarButtonItem *) rightButton {
5358 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5359 initWithTitle:UCLocalize("CLOSE")
5360 style:UIBarButtonItemStylePlain
5362 action:@selector(close)
5366 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5367 UpdateExternalStatus(1);
5369 [progress_ setRunning:true];
5370 [self setTitle:title];
5371 // implicit updateProgress
5373 SHA1SumValue notifyconf; {
5375 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5378 MMap mmap(file, MMap::ReadOnly);
5380 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5381 notifyconf = sha1.Result();
5385 SHA1SumValue springlist; {
5387 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5390 MMap mmap(file, MMap::ReadOnly);
5392 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5393 springlist = sha1.Result();
5397 if (invocation != nil) {
5398 [invocation yieldToSelector:@selector(invoke)];
5399 [self setTitle:@"COMPLETE"];
5404 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5407 MMap mmap(file, MMap::ReadOnly);
5409 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5410 if (!(notifyconf == sha1.Result()))
5417 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5420 MMap mmap(file, MMap::ReadOnly);
5422 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5423 if (!(springlist == sha1.Result()))
5429 if (RestartSubstrate_)
5433 RestartSubstrate_ = false;
5436 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5437 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5438 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5439 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5440 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5443 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5445 [progress_ setRunning:false];
5446 [self updateProgress];
5448 [self applyRightButton];
5451 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5452 [progress_ addEvent:event];
5453 [self updateProgress];
5456 - (bool) isProgressCancelled {
5457 return cancel_ == 2;
5462 [self updateCancel];
5465 - (void) setCancellable:(bool)cancellable {
5466 unsigned cancel(cancel_);
5470 else if (cancel_ == 0)
5473 if (cancel != cancel_)
5474 [self updateCancel];
5477 - (void) setProgressCancellable:(NSNumber *)cancellable {
5478 [self setCancellable:[cancellable boolValue]];
5481 - (void) setProgressPercent:(NSNumber *)percent {
5482 [progress_ setPercent:[percent floatValue]];
5483 [self updateProgress];
5486 - (void) setProgressStatus:(NSDictionary *)status {
5487 if (status == nil) {
5488 [progress_ setCurrent:0];
5489 [progress_ setTotal:0];
5490 [progress_ setSpeed:0];
5492 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5494 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5495 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5496 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5499 [self updateProgress];
5505 /* Package Cell {{{ */
5506 @interface PackageCell : CyteTableViewCell <
5507 CyteTableViewCellDelegate
5511 _H<NSString> description_;
5513 _H<NSString> source_;
5515 _H<UIImage> placard_;
5519 - (PackageCell *) init;
5520 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5522 - (void) drawContentRect:(CGRect)rect;
5526 @implementation PackageCell
5528 - (PackageCell *) init {
5529 CGRect frame(CGRectMake(0, 0, 320, 74));
5530 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5531 UIView *content([self contentView]);
5532 CGRect bounds([content bounds]);
5534 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5535 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5536 [content addSubview:content_];
5538 [content_ setDelegate:self];
5539 [content_ setOpaque:YES];
5543 - (NSString *) accessibilityLabel {
5547 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5548 summarized_ = summary;
5558 [content_ setBackgroundColor:[UIColor whiteColor]];
5562 Source *source = [package source];
5564 icon_ = [package icon];
5566 if (NSString *name = [package name])
5567 name_ = [NSString stringWithString:name];
5569 NSString *description(nil);
5571 if (description == nil && IsWildcat_)
5572 description = [package longDescription];
5573 if (description == nil)
5574 description = [package shortDescription];
5576 if (description != nil)
5577 description_ = [NSString stringWithString:description];
5579 commercial_ = [package isCommercial];
5581 NSString *label = nil;
5582 bool trusted = false;
5584 if (source != nil) {
5585 label = [source label];
5586 trusted = [source trusted];
5587 } else if ([[package id] isEqualToString:@"firmware"])
5588 label = UCLocalize("APPLE");
5590 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5592 NSString *from(label);
5594 NSString *section = [package simpleSection];
5595 if (section != nil && ![section isEqualToString:label]) {
5596 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5597 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5600 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5602 if (NSString *purpose = [package primaryPurpose])
5603 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5608 if (NSString *mode = [package mode]) {
5609 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5610 color = RemovingColor_;
5611 //placard = @"removing";
5613 color = InstallingColor_;
5614 //placard = @"installing";
5617 // XXX: the removing/installing placards are not @2x
5620 color = [UIColor whiteColor];
5622 if ([package installed] != nil)
5623 placard = @"installed";
5628 [content_ setBackgroundColor:color];
5631 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5634 [self setNeedsDisplay];
5635 [content_ setNeedsDisplay];
5638 - (void) drawSummaryContentRect:(CGRect)rect {
5639 bool highlighted(highlighted_);
5640 float width([self bounds].size.width);
5644 rect.size = [(UIImage *) icon_ size];
5646 while (rect.size.width > 16 || rect.size.height > 16) {
5647 rect.size.width /= 2;
5648 rect.size.height /= 2;
5651 rect.origin.x = 18 - rect.size.width / 2;
5652 rect.origin.y = 18 - rect.size.height / 2;
5654 [icon_ drawInRect:rect];
5657 if (badge_ != nil) {
5659 rect.size = [(UIImage *) badge_ size];
5661 rect.size.width /= 4;
5662 rect.size.height /= 4;
5664 rect.origin.x = 23 - rect.size.width / 2;
5665 rect.origin.y = 23 - rect.size.height / 2;
5667 [badge_ drawInRect:rect];
5674 UISetColor(commercial_ ? Purple_ : Black_);
5675 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5677 if (placard_ != nil)
5678 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5681 - (void) drawNormalContentRect:(CGRect)rect {
5682 bool highlighted(highlighted_);
5683 float width([self bounds].size.width);
5687 rect.size = [(UIImage *) icon_ size];
5689 while (rect.size.width > 32 || rect.size.height > 32) {
5690 rect.size.width /= 2;
5691 rect.size.height /= 2;
5694 rect.origin.x = 25 - rect.size.width / 2;
5695 rect.origin.y = 25 - rect.size.height / 2;
5697 [icon_ drawInRect:rect];
5700 if (badge_ != nil) {
5702 rect.size = [(UIImage *) badge_ size];
5704 rect.size.width /= 2;
5705 rect.size.height /= 2;
5707 rect.origin.x = 36 - rect.size.width / 2;
5708 rect.origin.y = 36 - rect.size.height / 2;
5710 [badge_ drawInRect:rect];
5717 UISetColor(commercial_ ? Purple_ : Black_);
5718 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5719 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5722 UISetColor(commercial_ ? Purplish_ : Gray_);
5723 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5725 if (placard_ != nil)
5726 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5729 - (void) drawContentRect:(CGRect)rect {
5731 [self drawSummaryContentRect:rect];
5733 [self drawNormalContentRect:rect];
5738 /* Section Cell {{{ */
5739 @interface SectionCell : CyteTableViewCell <
5740 CyteTableViewCellDelegate
5742 _H<NSString> basic_;
5743 _H<NSString> section_;
5745 _H<NSString> count_;
5747 _H<UISwitch> switch_;
5751 - (void) setSection:(Section *)section editing:(BOOL)editing;
5755 @implementation SectionCell
5757 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5758 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5759 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5760 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5761 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5763 UIView *content([self contentView]);
5764 CGRect bounds([content bounds]);
5766 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5767 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5768 [content addSubview:content_];
5769 [content_ setBackgroundColor:[UIColor whiteColor]];
5771 [content_ setDelegate:self];
5775 - (void) onSwitch:(id)sender {
5776 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5777 if (metadata == nil) {
5778 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5779 [Sections_ setObject:metadata forKey:basic_];
5782 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5786 - (void) setSection:(Section *)section editing:(BOOL)editing {
5787 if (editing != editing_) {
5789 [switch_ removeFromSuperview];
5791 [self addSubview:switch_];
5800 if (section == nil) {
5801 name_ = UCLocalize("ALL_PACKAGES");
5804 basic_ = [section name];
5805 section_ = [section localized];
5807 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5808 count_ = [NSString stringWithFormat:@"%d", [section count]];
5811 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5814 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5815 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5817 [content_ setNeedsDisplay];
5820 - (void) setFrame:(CGRect)frame {
5821 [super setFrame:frame];
5823 CGRect rect([switch_ frame]);
5824 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5827 - (NSString *) accessibilityLabel {
5831 - (void) drawContentRect:(CGRect)rect {
5832 bool highlighted(highlighted_ && !editing_);
5834 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5839 float width(rect.size.width);
5845 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5847 CGSize size = [count_ sizeWithFont:Font14_];
5851 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5857 /* File Table {{{ */
5858 @interface FileTable : CyteViewController <
5859 UITableViewDataSource,
5862 _transient Database *database_;
5863 _H<Package> package_;
5865 _H<NSMutableArray> files_;
5866 _H<UITableView, 2> list_;
5869 - (id) initWithDatabase:(Database *)database;
5870 - (void) setPackage:(Package *)package;
5874 @implementation FileTable
5876 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5877 return files_ == nil ? 0 : [files_ count];
5880 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5884 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5885 static NSString *reuseIdentifier = @"Cell";
5887 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5889 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5890 [cell setFont:[UIFont systemFontOfSize:16]];
5892 [cell setText:[files_ objectAtIndex:indexPath.row]];
5893 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5898 - (NSURL *) navigationURL {
5899 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5903 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5904 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5905 [list_ setRowHeight:24.0f];
5906 [(UITableView *) list_ setDataSource:self];
5907 [list_ setDelegate:self];
5908 [self setView:list_];
5911 - (void) viewDidLoad {
5912 [super viewDidLoad];
5914 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5917 - (void) releaseSubviews {
5923 [super releaseSubviews];
5926 - (id) initWithDatabase:(Database *)database {
5927 if ((self = [super init]) != nil) {
5928 database_ = database;
5932 - (void) setPackage:(Package *)package {
5936 files_ = [NSMutableArray arrayWithCapacity:32];
5938 if (package != nil) {
5940 name_ = [package id];
5942 if (NSArray *files = [package files])
5943 [files_ addObjectsFromArray:files];
5945 if ([files_ count] != 0) {
5946 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5947 [files_ removeObjectAtIndex:0];
5948 [files_ sortUsingSelector:@selector(compareByPath:)];
5950 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5951 [stack addObject:@"/"];
5953 for (int i(0), e([files_ count]); i != e; ++i) {
5954 NSString *file = [files_ objectAtIndex:i];
5955 while (![file hasPrefix:[stack lastObject]])
5956 [stack removeLastObject];
5957 NSString *directory = [stack lastObject];
5958 [stack addObject:[file stringByAppendingString:@"/"]];
5959 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5960 ([stack count] - 2) * 3, "",
5961 [file substringFromIndex:[directory length]]
5970 - (void) reloadData {
5973 [self setPackage:[database_ packageWithName:name_]];
5978 /* Package Controller {{{ */
5979 @interface CYPackageController : CydiaWebViewController <
5980 UIActionSheetDelegate
5982 _transient Database *database_;
5983 _H<Package> package_;
5986 _H<NSMutableArray> buttons_;
5987 _H<UIBarButtonItem> button_;
5990 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
5994 @implementation CYPackageController
5996 - (NSURL *) navigationURL {
5997 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6000 /* XXX: this is not safe at all... localization of /fail/ */
6001 - (void) _clickButtonWithName:(NSString *)name {
6002 if ([name isEqualToString:UCLocalize("CLEAR")])
6003 [delegate_ clearPackage:package_];
6004 else if ([name isEqualToString:UCLocalize("INSTALL")])
6005 [delegate_ installPackage:package_];
6006 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6007 [delegate_ installPackage:package_];
6008 else if ([name isEqualToString:UCLocalize("REMOVE")])
6009 [delegate_ removePackage:package_];
6010 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6011 [delegate_ installPackage:package_];
6012 else _assert(false);
6015 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6016 NSString *context([sheet context]);
6018 if ([context isEqualToString:@"modify"]) {
6019 if (button != [sheet cancelButtonIndex]) {
6020 NSString *buttonName = [buttons_ objectAtIndex:button];
6021 [self _clickButtonWithName:buttonName];
6024 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6028 - (bool) _allowJavaScriptPanel {
6033 - (void) _customButtonClicked {
6034 int count([buttons_ count]);
6039 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6041 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6042 [buttons addObjectsFromArray:buttons_];
6044 UIActionSheet *sheet = [[[UIActionSheet alloc]
6047 cancelButtonTitle:nil
6048 destructiveButtonTitle:nil
6049 otherButtonTitles:nil
6052 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6054 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6055 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6057 [sheet setContext:@"modify"];
6059 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6063 - (void) reloadButtonClicked {
6064 if (commercial_ && function_ == nil && [package_ uninstalled])
6066 [self customButtonClicked];
6069 - (void) applyLoadingTitle {
6070 // Don't show "Loading" as the title. Ever.
6073 - (UIBarButtonItem *) rightButton {
6078 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6079 if ((self = [super init]) != nil) {
6080 database_ = database;
6081 buttons_ = [NSMutableArray arrayWithCapacity:4];
6082 name_ = name == nil ? @"" : [NSString stringWithString:name];
6083 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6087 - (void) reloadData {
6090 package_ = [database_ packageWithName:name_];
6092 [buttons_ removeAllObjects];
6094 if (package_ != nil) {
6095 [(Package *) package_ parse];
6097 commercial_ = [package_ isCommercial];
6099 if ([package_ mode] != nil)
6100 [buttons_ addObject:UCLocalize("CLEAR")];
6101 if ([package_ source] == nil);
6102 else if ([package_ upgradableAndEssential:NO])
6103 [buttons_ addObject:UCLocalize("UPGRADE")];
6104 else if ([package_ uninstalled])
6105 [buttons_ addObject:UCLocalize("INSTALL")];
6107 [buttons_ addObject:UCLocalize("REINSTALL")];
6108 if (![package_ uninstalled])
6109 [buttons_ addObject:UCLocalize("REMOVE")];
6113 switch ([buttons_ count]) {
6114 case 0: title = nil; break;
6115 case 1: title = [buttons_ objectAtIndex:0]; break;
6116 default: title = UCLocalize("MODIFY"); break;
6119 button_ = [[[UIBarButtonItem alloc]
6121 style:UIBarButtonItemStylePlain
6123 action:@selector(customButtonClicked)
6127 - (bool) isLoading {
6128 return commercial_ ? [super isLoading] : false;
6134 /* Package List Controller {{{ */
6135 @interface PackageListController : CyteViewController <
6136 UITableViewDataSource,
6139 _transient Database *database_;
6141 _H<NSArray> packages_;
6142 _H<NSMutableArray> sections_;
6143 _H<UITableView, 2> list_;
6144 _H<NSMutableArray> index_;
6145 _H<NSMutableDictionary> indices_;
6146 _H<NSString> title_;
6147 unsigned reloading_;
6150 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6151 - (void) setDelegate:(id)delegate;
6152 - (void) resetCursor;
6157 @implementation PackageListController
6159 - (NSURL *) referrerURL {
6160 return [self navigationURL];
6163 - (bool) isSummarized {
6167 - (bool) showsSections {
6171 - (void) deselectWithAnimation:(BOOL)animated {
6172 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6175 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6176 CGRect base = [[self view] bounds];
6177 base.size.height -= bounds.size.height;
6178 base.origin = [list_ frame].origin;
6180 [UIView beginAnimations:nil context:NULL];
6181 [UIView setAnimationBeginsFromCurrentState:YES];
6182 [UIView setAnimationCurve:curve];
6183 [UIView setAnimationDuration:duration];
6184 [list_ setFrame:base];
6185 [UIView commitAnimations];
6188 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6189 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6192 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6193 [self resizeForKeyboardBounds:bounds duration:0];
6196 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6197 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6198 *curve = UIViewAnimationCurveEaseInOut;
6200 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6202 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6205 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6208 - (void) keyboardWillShow:(NSNotification *)notification {
6211 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6212 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6214 NSTimeInterval duration;
6215 UIViewAnimationCurve curve;
6216 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6218 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);
6219 UIViewController *base = self;
6220 while ([base parentOrPresentingViewController] != nil)
6221 base = [base parentOrPresentingViewController];
6222 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6223 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6225 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6226 intersection.size.height += CYStatusBarHeight();
6228 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6231 - (void) keyboardWillHide:(NSNotification *)notification {
6232 NSTimeInterval duration;
6233 UIViewAnimationCurve curve;
6234 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6236 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6239 - (void) viewWillAppear:(BOOL)animated {
6240 [super viewWillAppear:animated];
6242 [self resizeForKeyboardBounds:CGRectZero];
6243 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6244 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6247 - (void) viewWillDisappear:(BOOL)animated {
6248 [super viewWillDisappear:animated];
6250 [self resizeForKeyboardBounds:CGRectZero];
6251 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6252 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6255 - (void) viewDidAppear:(BOOL)animated {
6256 [super viewDidAppear:animated];
6257 [self deselectWithAnimation:animated];
6260 - (void) didSelectPackage:(Package *)package {
6261 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6262 [view setDelegate:delegate_];
6263 [[self navigationController] pushViewController:view animated:YES];
6266 #if TryIndexedCollation
6267 + (BOOL) hasIndexedCollation {
6268 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6272 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6273 NSInteger count([sections_ count]);
6274 return count == 0 ? 1 : count;
6277 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6278 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6280 return [[sections_ objectAtIndex:section] name];
6283 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6284 if ([sections_ count] == 0)
6286 return [[sections_ objectAtIndex:section] count];
6289 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6290 @synchronized (database_) {
6291 if ([database_ era] != era_)
6294 Section *section([sections_ objectAtIndex:[path section]]);
6295 NSInteger row([path row]);
6296 Package *package([packages_ objectAtIndex:([section row] + row)]);
6297 return [[package retain] autorelease];
6300 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6301 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6303 cell = [[[PackageCell alloc] init] autorelease];
6305 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6306 [cell setPackage:package asSummary:[self isSummarized]];
6310 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6311 Package *package([self packageAtIndexPath:path]);
6312 package = [database_ packageWithName:[package id]];
6313 [self didSelectPackage:package];
6316 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6317 if (![self showsSections])
6323 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6324 #if TryIndexedCollation
6325 if ([[self class] hasIndexedCollation]) {
6326 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6333 - (void) updateHeight {
6334 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6337 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6338 if ((self = [super init]) != nil) {
6339 database_ = database;
6340 title_ = [title copy];
6341 [[self navigationItem] setTitle:title_];
6346 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6347 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6348 [self setView:view];
6350 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6351 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6352 [view addSubview:list_];
6354 // XXX: is 20 the most optimal number here?
6355 [list_ setSectionIndexMinimumDisplayRowCount:20];
6357 [(UITableView *) list_ setDataSource:self];
6358 [list_ setDelegate:self];
6360 [self updateHeight];
6363 - (void) releaseSubviews {
6371 [super releaseSubviews];
6374 - (void) setDelegate:(id)delegate {
6375 delegate_ = delegate;
6378 - (bool) shouldYield {
6382 - (bool) shouldBlock {
6386 - (NSMutableArray *) _reloadPackages {
6387 @synchronized (database_) {
6388 era_ = [database_ era];
6389 NSArray *packages([database_ packages]);
6391 return [NSMutableArray arrayWithArray:packages];
6394 - (void) _reloadData {
6395 if (reloading_ != 0) {
6403 if ([self shouldYield]) {
6407 if (![self shouldBlock])
6410 hud = [delegate_ addProgressHUD];
6411 [hud setText:UCLocalize("LOADING")];
6415 packages = [self yieldToSelector:@selector(_reloadPackages)];
6418 [delegate_ removeProgressHUD:hud];
6419 } while (reloading_ == 2);
6421 packages = [self _reloadPackages];
6424 @synchronized (database_) {
6425 if (era_ != [database_ era])
6429 packages_ = packages;
6431 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6432 sections_ = [NSMutableArray arrayWithCapacity:16];
6434 Section *section = nil;
6436 #if TryIndexedCollation
6437 if ([[self class] hasIndexedCollation]) {
6438 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6440 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6441 NSArray *titles = [collation sectionIndexTitles];
6444 _profile(PackageTable$reloadData$Section)
6445 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6449 _profile(PackageTable$reloadData$Section$Package)
6450 package = [packages_ objectAtIndex:offset];
6451 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6454 while (secidx < index) {
6457 _profile(PackageTable$reloadData$Section$Allocate)
6458 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6461 _profile(PackageTable$reloadData$Section$Add)
6462 [sections_ addObject:section];
6466 [section addToCount];
6472 index_ = [NSMutableArray arrayWithCapacity:32];
6474 bool sectioned([self showsSections]);
6476 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6477 [sections_ addObject:section];
6480 _profile(PackageTable$reloadData$Section)
6481 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6485 _profile(PackageTable$reloadData$Section$Package)
6486 package = [packages_ objectAtIndex:offset];
6487 index = [package index];
6490 if (sectioned && (section == nil || [section index] != index)) {
6491 _profile(PackageTable$reloadData$Section$Allocate)
6492 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6495 [index_ addObject:[section name]];
6496 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6498 _profile(PackageTable$reloadData$Section$Add)
6499 [sections_ addObject:section];
6503 [section addToCount];
6508 [self updateHeight];
6510 _profile(PackageTable$reloadData$List)
6511 [(UITableView *) list_ setDataSource:self];
6516 - (void) reloadData {
6519 if ([self shouldYield])
6520 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6525 - (void) resetCursor {
6526 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6529 - (void) clearData {
6530 [self updateHeight];
6532 [list_ setDataSource:nil];
6540 /* Filtered Package List Controller {{{ */
6541 @interface FilteredPackageListController : PackageListController {
6544 _H<NSObject> object_;
6547 - (void) setObject:(id)object;
6548 - (void) setObject:(id)object forFilter:(SEL)filter;
6551 - (void) setFilter:(SEL)filter;
6553 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6557 @implementation FilteredPackageListController
6563 - (void) setFilter:(SEL)filter {
6564 @synchronized (self) {
6567 /* XXX: this is an unsafe optimization of doomy hell */
6568 Method method(class_getInstanceMethod([Package class], filter));
6569 _assert(method != NULL);
6570 imp_ = method_getImplementation(method);
6571 _assert(imp_ != NULL);
6574 - (void) setObject:(id)object {
6575 @synchronized (self) {
6579 - (void) setObject:(id)object forFilter:(SEL)filter {
6580 @synchronized (self) {
6581 [self setFilter:filter];
6582 [self setObject:object];
6585 - (NSMutableArray *) _reloadPackages {
6586 @synchronized (database_) {
6587 era_ = [database_ era];
6588 NSArray *packages([database_ packages]);
6590 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6594 _H<NSObject> object;
6596 @synchronized (self) {
6602 _profile(PackageTable$reloadData$Filter)
6603 for (Package *package in packages)
6604 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6605 [filtered addObject:package];
6611 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6612 if ((self = [super initWithDatabase:database title:title]) != nil) {
6613 [self setFilter:filter];
6614 [self setObject:object];
6621 /* Home Controller {{{ */
6622 @interface HomeController : CydiaWebViewController {
6623 CFRunLoopRef runloop_;
6624 SCNetworkReachabilityRef reachability_;
6629 @implementation HomeController
6631 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6632 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6636 if ((self = [super init]) != nil) {
6637 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6640 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6641 if (reachability_ != NULL) {
6642 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6643 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6645 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6646 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6653 if (reachability_ != NULL && runloop_ != NULL)
6654 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6658 - (NSURL *) navigationURL {
6659 return [NSURL URLWithString:@"cydia://home"];
6662 - (void) aboutButtonClicked {
6663 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6665 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6666 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6667 [alert setCancelButtonIndex:0];
6670 @"Copyright \u00a9 2008-2012\n"
6673 "Jay Freeman (saurik)\n"
6674 "saurik@saurik.com\n"
6675 "http://www.saurik.com/"
6681 - (UIBarButtonItem *) leftButton {
6682 return [[[UIBarButtonItem alloc]
6683 initWithTitle:UCLocalize("ABOUT")
6684 style:UIBarButtonItemStylePlain
6686 action:@selector(aboutButtonClicked)
6692 /* Manage Controller {{{ */
6693 @interface ManageController : CydiaWebViewController {
6696 - (void) queueStatusDidChange;
6700 @implementation ManageController
6703 if ((self = [super init]) != nil) {
6704 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6708 - (NSURL *) navigationURL {
6709 return [NSURL URLWithString:@"cydia://manage"];
6712 - (UIBarButtonItem *) leftButton {
6713 return [[[UIBarButtonItem alloc]
6714 initWithTitle:UCLocalize("SETTINGS")
6715 style:UIBarButtonItemStylePlain
6717 action:@selector(settingsButtonClicked)
6721 - (void) settingsButtonClicked {
6722 [delegate_ showSettings];
6725 - (void) queueButtonClicked {
6729 - (UIBarButtonItem *) rightButton {
6730 return Queuing_ ? [[[UIBarButtonItem alloc]
6731 initWithTitle:UCLocalize("QUEUE")
6732 style:UIBarButtonItemStyleDone
6734 action:@selector(queueButtonClicked)
6735 ] autorelease] : nil;
6738 - (void) queueStatusDidChange {
6739 [self applyRightButton];
6742 - (bool) isLoading {
6743 return !Queuing_ && [super isLoading];
6749 /* Refresh Bar {{{ */
6750 @interface RefreshBar : UINavigationBar {
6751 _H<UIProgressIndicator> indicator_;
6752 _H<UITextLabel> prompt_;
6753 _H<UINavigationButton> cancel_;
6758 @implementation RefreshBar
6760 - (void) positionViews {
6761 CGRect frame = [cancel_ frame];
6762 frame.size = [cancel_ sizeThatFits:frame.size];
6763 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6764 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6765 [cancel_ setFrame:frame];
6767 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6768 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6769 CGRect indrect = {{indoffset, indoffset}, indsize};
6770 [indicator_ setFrame:indrect];
6772 CGSize prmsize = {215, indsize.height + 4};
6774 indoffset * 2 + indsize.width,
6775 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6777 [prompt_ setFrame:prmrect];
6780 - (void) setFrame:(CGRect)frame {
6781 [super setFrame:frame];
6782 [self positionViews];
6785 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6786 if ((self = [super initWithFrame:frame]) != nil) {
6787 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6789 [self setBarStyle:UIBarStyleBlack];
6791 UIBarStyle barstyle([self _barStyle:NO]);
6792 bool ugly(barstyle == UIBarStyleDefault);
6794 UIProgressIndicatorStyle style = ugly ?
6795 UIProgressIndicatorStyleMediumBrown :
6796 UIProgressIndicatorStyleMediumWhite;
6798 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6799 [(UIProgressIndicator *) indicator_ setStyle:style];
6800 [indicator_ startAnimation];
6801 [self addSubview:indicator_];
6803 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6804 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6805 [prompt_ setBackgroundColor:[UIColor clearColor]];
6806 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6807 [self addSubview:prompt_];
6809 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6810 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6811 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6812 [cancel_ setBarStyle:barstyle];
6814 [self positionViews];
6818 - (void) setCancellable:(bool)cancellable {
6820 [self addSubview:cancel_];
6822 [cancel_ removeFromSuperview];
6826 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6830 [self setCancellable:NO];
6833 - (void) setPrompt:(NSString *)prompt {
6834 [prompt_ setText:prompt];
6837 - (void) setProgress:(float)progress {
6843 /* Cydia Navigation Controller Interface {{{ */
6844 @interface UINavigationController (Cydia)
6846 - (NSArray *) navigationURLCollection;
6847 - (void) unloadData;
6852 /* Cydia Tab Bar Controller {{{ */
6853 @interface CYTabBarController : UITabBarController <
6854 UITabBarControllerDelegate,
6857 _transient Database *database_;
6858 _H<RefreshBar, 1> refreshbar_;
6862 // XXX: ok, "updatedelegate_"?...
6863 _transient NSObject<CydiaDelegate> *updatedelegate_;
6865 _H<UIViewController> remembered_;
6866 _transient UIViewController *transient_;
6869 - (NSArray *) navigationURLCollection;
6870 - (void) dropBar:(BOOL)animated;
6871 - (void) beginUpdate;
6872 - (void) raiseBar:(BOOL)animated;
6874 - (void) unloadData;
6878 @implementation CYTabBarController
6880 - (void) didReceiveMemoryWarning {
6881 [super didReceiveMemoryWarning];
6883 // presenting a UINavigationController on 2.x does not update its transitionView
6884 // it thereby will not allow its topViewController to be unloaded by memory pressure
6885 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6886 UIViewController *selected([self selectedViewController]);
6887 for (UINavigationController *controller in [self viewControllers])
6888 if (controller != selected)
6889 if (UIViewController *top = [controller topViewController])
6894 - (void) setUnselectedViewController:(UIViewController *)transient {
6895 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6896 if (transient != nil) {
6897 [[[self viewControllers] objectAtIndex:0] pushViewController:transient animated:YES];
6898 [self setSelectedIndex:0];
6902 NSMutableArray *controllers = [[[self viewControllers] mutableCopy] autorelease];
6903 if (transient != nil) {
6904 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
6905 [navigation setViewControllers:[NSArray arrayWithObject:transient]];
6906 transient = navigation;
6908 if (transient_ == nil)
6909 remembered_ = [controllers objectAtIndex:0];
6910 transient_ = transient;
6911 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6912 [controllers replaceObjectAtIndex:0 withObject:transient_];
6913 [self setSelectedIndex:0];
6914 [self setViewControllers:controllers];
6915 [self concealTabBarSelection];
6916 } else if (remembered_ != nil) {
6917 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6918 transient_ = transient;
6919 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6921 [self setViewControllers:controllers];
6922 [self revealTabBarSelection];
6926 - (UIViewController *) unselectedViewController {
6930 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6931 if ([self unselectedViewController])
6932 [self setUnselectedViewController:nil];
6934 // presenting a UINavigationController on 2.x does not update its transitionView
6935 // if this view was unloaded, the tranitionView may currently be presenting nothing
6936 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6937 UINavigationController *navigation((UINavigationController *) viewController);
6938 [navigation pushViewController:[[[UIViewController alloc] init] autorelease] animated:NO];
6939 [navigation popViewControllerAnimated:NO];
6943 - (NSArray *) navigationURLCollection {
6944 NSMutableArray *items([NSMutableArray array]);
6946 // XXX: Should this deal with transient view controllers?
6947 for (id navigation in [self viewControllers]) {
6948 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6950 [items addObject:stack];
6956 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6957 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6958 [self setUnselectedViewController:nil];
6960 [super dismissModalViewControllerAnimated:YES];
6963 - (void) unloadData {
6966 for (UINavigationController *controller in [self viewControllers])
6967 [controller unloadData];
6969 if (UIViewController *selected = [self selectedViewController])
6970 [selected reloadData];
6972 if (UIViewController *unselected = [self unselectedViewController]) {
6973 [unselected unloadData];
6974 [unselected reloadData];
6979 [[NSNotificationCenter defaultCenter] removeObserver:self];
6984 - (id) initWithDatabase:(Database *)database {
6985 if ((self = [super init]) != nil) {
6986 database_ = database;
6987 [self setDelegate:self];
6989 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6990 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6992 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6996 - (void) setUpdate:(NSDate *)date {
7000 - (void) beginUpdate {
7001 [(RefreshBar *) refreshbar_ start];
7004 [updatedelegate_ retainNetworkActivityIndicator];
7008 detachNewThreadSelector:@selector(performUpdate)
7014 - (void) performUpdate {
7015 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7018 status.setDelegate(self);
7019 [database_ updateWithStatus:status];
7022 performSelectorOnMainThread:@selector(completeUpdate)
7030 - (void) stopUpdateWithSelector:(SEL)selector {
7032 [updatedelegate_ releaseNetworkActivityIndicator];
7034 [self raiseBar:YES];
7037 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7040 - (void) completeUpdate {
7043 [self stopUpdateWithSelector:@selector(reloadData)];
7046 - (void) cancelUpdate {
7047 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7050 - (void) cancelPressed {
7051 [self cancelUpdate];
7058 - (void) addProgressEvent:(CydiaProgressEvent *)event {
7059 [refreshbar_ setPrompt:[event compoundMessage]];
7062 - (bool) isProgressCancelled {
7066 - (void) setProgressCancellable:(NSNumber *)cancellable {
7067 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
7070 - (void) setProgressPercent:(NSNumber *)percent {
7071 [refreshbar_ setProgress:[percent floatValue]];
7074 - (void) setProgressStatus:(NSDictionary *)status {
7076 [self setProgressPercent:[status objectForKey:@"Percent"]];
7079 - (void) setUpdateDelegate:(id)delegate {
7080 updatedelegate_ = delegate;
7083 - (UIView *) transitionView {
7084 if ([self respondsToSelector:@selector(_transitionView)])
7085 return [self _transitionView];
7087 return MSHookIvar<id>(self, "_viewControllerTransitionView");
7090 - (void) dropBar:(BOOL)animated {
7095 UIView *transition([self transitionView]);
7096 [[self view] addSubview:refreshbar_];
7098 CGRect barframe([refreshbar_ frame]);
7100 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
7101 barframe.origin.y = CYStatusBarHeight();
7103 barframe.origin.y = 0;
7105 [refreshbar_ setFrame:barframe];
7108 [UIView beginAnimations:nil context:NULL];
7110 CGRect viewframe = [transition frame];
7111 viewframe.origin.y += barframe.size.height;
7112 viewframe.size.height -= barframe.size.height;
7113 [transition setFrame:viewframe];
7116 [UIView commitAnimations];
7118 // Ensure bar has the proper width for our view, it might have changed
7119 barframe.size.width = viewframe.size.width;
7120 [refreshbar_ setFrame:barframe];
7123 - (void) raiseBar:(BOOL)animated {
7128 UIView *transition([self transitionView]);
7129 [refreshbar_ removeFromSuperview];
7131 CGRect barframe([refreshbar_ frame]);
7134 [UIView beginAnimations:nil context:NULL];
7136 CGRect viewframe = [transition frame];
7137 viewframe.origin.y -= barframe.size.height;
7138 viewframe.size.height += barframe.size.height;
7139 [transition setFrame:viewframe];
7142 [UIView commitAnimations];
7145 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7146 bool dropped(dropped_);
7151 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7157 - (void) statusBarFrameChanged:(NSNotification *)notification {
7167 /* Cydia Navigation Controller Implementation {{{ */
7168 @implementation UINavigationController (Cydia)
7170 - (NSArray *) navigationURLCollection {
7171 NSMutableArray *stack([NSMutableArray array]);
7173 for (CyteViewController *controller in [self viewControllers]) {
7174 NSString *url = [[controller navigationURL] absoluteString];
7176 [stack addObject:url];
7182 - (void) reloadData {
7185 UIViewController *visible([self visibleViewController]);
7187 [visible reloadData];
7189 // on the iPad, this view controller is ALSO visible. :(
7191 if (UIViewController *top = [self topViewController])
7196 - (void) unloadData {
7197 for (CyteViewController *page in [self viewControllers])
7206 /* Cydia:// Protocol {{{ */
7207 @interface CydiaURLProtocol : NSURLProtocol {
7212 @implementation CydiaURLProtocol
7214 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7215 NSURL *url([request URL]);
7219 NSString *scheme([[url scheme] lowercaseString]);
7220 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7222 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7228 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7232 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7233 id<NSURLProtocolClient> client([self client]);
7235 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7237 NSData *data(UIImagePNGRepresentation(icon));
7239 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7240 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7241 [client URLProtocol:self didLoadData:data];
7242 [client URLProtocolDidFinishLoading:self];
7246 - (void) startLoading {
7247 id<NSURLProtocolClient> client([self client]);
7248 NSURLRequest *request([self request]);
7250 NSURL *url([request URL]);
7251 NSString *href([url absoluteString]);
7252 NSString *scheme([[url scheme] lowercaseString]);
7256 if ([scheme isEqualToString:@"cydia"])
7257 path = [href substringFromIndex:8];
7258 else if ([scheme isEqualToString:@"about"])
7259 path = [href substringFromIndex:12];
7260 else _assert(false);
7262 NSRange slash([path rangeOfString:@"/"]);
7265 if (slash.location == NSNotFound) {
7269 command = [path substringToIndex:slash.location];
7270 path = [path substringFromIndex:(slash.location + 1)];
7273 Database *database([Database sharedInstance]);
7275 if ([command isEqualToString:@"package-icon"]) {
7278 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7279 Package *package([database packageWithName:path]);
7283 UIImage *icon([package icon]);
7284 [self _returnPNGWithImage:icon forRequest:request];
7285 } else if ([command isEqualToString:@"uikit-image"]) {
7288 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7289 UIImage *icon(_UIImageWithName(path));
7290 [self _returnPNGWithImage:icon forRequest:request];
7291 } else if ([command isEqualToString:@"section-icon"]) {
7294 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7295 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7297 icon = [UIImage applicationImageNamed:@"unknown.png"];
7298 [self _returnPNGWithImage:icon forRequest:request];
7300 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7304 - (void) stopLoading {
7310 /* Section Controller {{{ */
7311 @interface SectionController : FilteredPackageListController {
7312 _H<IndirectDelegate, 1> indirect_;
7313 _H<CydiaObject> cydia_;
7314 _H<NSString> section_;
7315 std::vector< _H<CyteWebViewTableViewCell, 1> > promoted_;
7318 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7322 @implementation SectionController
7324 - (NSURL *) referrerURL {
7325 NSString *name = section_;
7329 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@", UI_, [name stringByAddingPercentEscapesIncludingReserved]]];
7332 - (NSURL *) navigationURL {
7333 NSString *name = section_;
7337 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", [name stringByAddingPercentEscapesIncludingReserved]]];
7340 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7343 title = UCLocalize("ALL_PACKAGES");
7344 else if (![name isEqual:@""])
7345 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7347 title = UCLocalize("NO_SECTION");
7349 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7350 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7351 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7356 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7357 return [super numberOfSectionsInTableView:list] + 1;
7360 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7361 return section == 0 ? nil : [super tableView:list titleForHeaderInSection:(section - 1)];
7364 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7365 return section == 0 ? promoted_.size() : [super tableView:list numberOfRowsInSection:(section - 1)];
7368 + (NSIndexPath *) adjustedIndexPath:(NSIndexPath *)path {
7369 return [NSIndexPath indexPathForRow:[path row] inSection:([path section] - 1)];
7372 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7373 if ([path section] != 0)
7374 return [super tableView:table cellForRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7376 return promoted_[[path row]];
7379 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
7380 if ([path section] != 0)
7381 return [super tableView:table didSelectRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7384 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
7385 NSInteger section([super tableView:tableView sectionForSectionIndexTitle:title atIndex:index]);
7386 return section == 0 ? 0 : section + 1;
7389 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7390 NSURL *url([request URL]);
7394 if ([frame isEqualToString:@"_open"])
7395 [delegate_ openURL:url];
7397 WebFrame *frame(nil);
7398 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7399 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7401 frame = [view mainFrame];
7403 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7405 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7406 [controller setDelegate:delegate_];
7407 [[self navigationController] pushViewController:controller animated:YES];
7413 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7414 return [CydiaWebViewController requestWithHeaders:request];
7417 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7418 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7424 // XXX: this code is horrible. I mean, wtf Jay?
7425 if (ShowPromoted_ && [[Metadata_ objectForKey:@"ShowPromoted"] boolValue]) {
7426 promoted_.resize(1);
7428 for (unsigned i(0); i != promoted_.size(); ++i) {
7429 CyteWebViewTableViewCell *promoted([CyteWebViewTableViewCell cellWithRequest:[NSURLRequest
7430 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sectionhead/%u/%@",
7431 UI_, i, section_ == nil ? @"" : [section_ stringByAddingPercentEscapesIncludingReserved]]
7434 cachePolicy:NSURLRequestUseProtocolCachePolicy
7438 [promoted setDelegate:self];
7439 promoted_[i] = promoted;
7444 - (void) setDelegate:(id)delegate {
7445 [super setDelegate:delegate];
7446 [cydia_ setDelegate:delegate];
7449 - (void) releaseSubviews {
7451 [super releaseSubviews];
7456 /* Sections Controller {{{ */
7457 @interface SectionsController : CyteViewController <
7458 UITableViewDataSource,
7461 _transient Database *database_;
7462 _H<NSMutableArray> sections_;
7463 _H<NSMutableArray> filtered_;
7464 _H<UITableView, 2> list_;
7467 - (id) initWithDatabase:(Database *)database;
7468 - (void) editButtonClicked;
7472 @implementation SectionsController
7474 - (NSURL *) navigationURL {
7475 return [NSURL URLWithString:@"cydia://sections"];
7478 - (void) updateNavigationItem {
7479 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7480 if ([sections_ count] == 0) {
7481 [[self navigationItem] setRightBarButtonItem:nil];
7483 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7484 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7486 action:@selector(editButtonClicked)
7487 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7491 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7492 [super setEditing:editing animated:animated];
7497 [delegate_ updateData];
7499 [self updateNavigationItem];
7502 - (void) viewDidAppear:(BOOL)animated {
7503 [super viewDidAppear:animated];
7504 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7507 - (void) viewWillDisappear:(BOOL)animated {
7508 [super viewWillDisappear:animated];
7509 [self setEditing:NO];
7512 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7513 Section *section = nil;
7514 int index = [indexPath row];
7515 if (![self isEditing]) {
7518 section = [filtered_ objectAtIndex:index];
7520 section = [sections_ objectAtIndex:index];
7525 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7526 if ([self isEditing])
7527 return [sections_ count];
7529 return [filtered_ count] + 1;
7532 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7536 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7537 static NSString *reuseIdentifier = @"SectionCell";
7539 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7541 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7543 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7548 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7549 if ([self isEditing])
7552 Section *section = [self sectionAtIndexPath:indexPath];
7554 SectionController *controller = [[[SectionController alloc]
7555 initWithDatabase:database_
7556 section:[section name]
7558 [controller setDelegate:delegate_];
7560 [[self navigationController] pushViewController:controller animated:YES];
7564 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7565 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7566 [list_ setRowHeight:45.0f];
7567 [(UITableView *) list_ setDataSource:self];
7568 [list_ setDelegate:self];
7569 [self setView:list_];
7572 - (void) viewDidLoad {
7573 [super viewDidLoad];
7575 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7578 - (void) releaseSubviews {
7584 [super releaseSubviews];
7587 - (id) initWithDatabase:(Database *)database {
7588 if ((self = [super init]) != nil) {
7589 database_ = database;
7593 - (void) reloadData {
7596 NSArray *packages = [database_ packages];
7598 sections_ = [NSMutableArray arrayWithCapacity:16];
7599 filtered_ = [NSMutableArray arrayWithCapacity:16];
7601 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7604 for (Package *package in packages) {
7605 NSString *name([package section]);
7606 NSString *key(name == nil ? @"" : name);
7610 _profile(SectionsView$reloadData$Section)
7611 section = [sections objectForKey:key];
7612 if (section == nil) {
7613 _profile(SectionsView$reloadData$Section$Allocate)
7614 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7615 [sections setObject:section forKey:key];
7620 [section addToCount];
7622 _profile(SectionsView$reloadData$Filter)
7623 if (![package valid] || ![package visible])
7631 [sections_ addObjectsFromArray:[sections allValues]];
7633 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7635 for (Section *section in (id) sections_) {
7636 size_t count([section row]);
7640 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7641 [section setCount:count];
7642 [filtered_ addObject:section];
7645 [self updateNavigationItem];
7650 - (void) editButtonClicked {
7651 [self setEditing:![self isEditing] animated:YES];
7657 /* Changes Controller {{{ */
7658 @interface ChangesController : CyteViewController <
7659 CyteWebViewDelegate,
7660 UITableViewDataSource,
7663 _transient Database *database_;
7665 _H<NSMutableArray> packages_;
7666 _H<NSMutableArray> sections_;
7667 _H<UITableView, 2> list_;
7668 _H<CyteWebView, 1> dickbar_;
7670 _H<IndirectDelegate, 1> indirect_;
7671 _H<CydiaObject> cydia_;
7674 - (id) initWithDatabase:(Database *)database;
7678 @implementation ChangesController
7680 - (NSURL *) navigationURL {
7681 return [NSURL URLWithString:@"cydia://changes"];
7684 - (void) viewDidAppear:(BOOL)animated {
7685 [super viewDidAppear:animated];
7686 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7689 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7690 NSInteger count([sections_ count]);
7691 return count == 0 ? 1 : count;
7694 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7695 if ([sections_ count] == 0)
7697 return [[sections_ objectAtIndex:section] name];
7700 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7701 if ([sections_ count] == 0)
7703 return [[sections_ objectAtIndex:section] count];
7706 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7707 @synchronized (database_) {
7708 if ([database_ era] != era_)
7711 NSUInteger sectionIndex([path section]);
7712 if (sectionIndex >= [sections_ count])
7714 Section *section([sections_ objectAtIndex:sectionIndex]);
7715 NSInteger row([path row]);
7716 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7719 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7720 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7722 cell = [[[PackageCell alloc] init] autorelease];
7724 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7725 [cell setPackage:package asSummary:false];
7729 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7730 Package *package([self packageAtIndexPath:path]);
7731 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[NSString stringWithFormat:@"%@/#!/changes/", UI_]] autorelease]);
7732 [view setDelegate:delegate_];
7733 [[self navigationController] pushViewController:view animated:YES];
7737 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7738 NSString *context([alert context]);
7740 if ([context isEqualToString:@"norefresh"])
7741 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7744 - (void) refreshButtonClicked {
7745 if (IsReachable("cydia.saurik.com")) {
7746 [delegate_ beginUpdate];
7747 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7749 UIAlertView *alert = [[[UIAlertView alloc]
7750 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
7751 message:@"Host Unreachable" // XXX: Localize
7753 cancelButtonTitle:UCLocalize("OK")
7754 otherButtonTitles:nil
7757 [alert setContext:@"norefresh"];
7762 - (void) upgradeButtonClicked {
7763 [delegate_ distUpgrade];
7764 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7768 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7769 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7770 [self setView:view];
7772 list_ = [[[UITableView alloc] initWithFrame:[view bounds] style:UITableViewStylePlain] autorelease];
7773 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7774 [list_ setRowHeight:73];
7775 [(UITableView *) list_ setDataSource:self];
7776 [list_ setDelegate:self];
7777 [view addSubview:list_];
7779 if (AprilFools_ && kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
7780 CGRect dickframe([view bounds]);
7781 dickframe.size.height = 44;
7783 dickbar_ = [[[CyteWebView alloc] initWithFrame:dickframe] autorelease];
7784 [dickbar_ setDelegate:self];
7785 [view addSubview:dickbar_];
7787 [dickbar_ setBackgroundColor:[UIColor clearColor]];
7788 [dickbar_ setScalesPageToFit:YES];
7790 UIWebDocumentView *document([dickbar_ _documentView]);
7791 [document setBackgroundColor:[UIColor clearColor]];
7792 [document setDrawsBackground:NO];
7794 WebView *webview([document webView]);
7795 [webview setShouldUpdateWhileOffscreen:NO];
7797 UIScrollView *scroller([dickbar_ scrollView]);
7798 [scroller setScrollingEnabled:NO];
7799 [scroller setFixedBackgroundPattern:YES];
7800 [scroller setBackgroundColor:[UIColor clearColor]];
7802 WebPreferences *preferences([webview preferences]);
7803 [preferences setCacheModel:WebCacheModelDocumentBrowser];
7804 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
7805 [preferences setOfflineWebApplicationCacheEnabled:YES];
7807 [dickbar_ loadRequest:[NSURLRequest
7808 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/dickbar/", UI_]]]
7809 cachePolicy:NSURLRequestUseProtocolCachePolicy
7813 UIEdgeInsets inset = {44, 0, 0, 0};
7814 [list_ setContentInset:inset];
7816 [dickbar_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7820 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7821 NSURL *url([request URL]);
7825 if ([frame isEqualToString:@"_open"])
7826 [delegate_ openURL:url];
7828 WebFrame *frame(nil);
7829 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7830 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7832 frame = [view mainFrame];
7834 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7836 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7837 [controller setDelegate:delegate_];
7838 [[self navigationController] pushViewController:controller animated:YES];
7844 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7845 return [CydiaWebViewController requestWithHeaders:request];
7848 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7849 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7852 - (void) setDelegate:(id)delegate {
7853 [super setDelegate:delegate];
7854 [cydia_ setDelegate:delegate];
7857 - (void) viewDidLoad {
7858 [super viewDidLoad];
7860 [[self navigationItem] setTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES"))];
7863 - (void) releaseSubviews {
7870 [super releaseSubviews];
7873 - (id) initWithDatabase:(Database *)database {
7874 if ((self = [super init]) != nil) {
7875 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7876 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7877 database_ = database;
7881 - (NSMutableArray *) _reloadPackages {
7882 @synchronized (database_) {
7883 era_ = [database_ era];
7884 NSArray *packages([database_ packages]);
7886 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7889 _profile(ChangesController$_reloadPackages$Filter)
7890 for (Package *package in packages)
7891 if ([package upgradableAndEssential:YES] || [package visible])
7892 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7895 _profile(ChangesController$_reloadPackages$radixSort)
7896 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7903 - (void) _reloadData {
7904 NSMutableArray *packages;
7908 UIProgressHUD *hud([delegate_ addProgressHUD]);
7909 [hud setText:UCLocalize("LOADING")];
7910 //NSLog(@"HUD:%@::%@", delegate_, hud);
7911 packages = [self yieldToSelector:@selector(_reloadPackages)];
7912 [delegate_ removeProgressHUD:hud];
7914 packages = [self _reloadPackages];
7917 @synchronized (database_) {
7918 if (era_ != [database_ era])
7921 packages_ = packages;
7922 sections_ = [NSMutableArray arrayWithCapacity:16];
7924 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7925 Section *ignored = nil;
7926 Section *section = nil;
7930 bool unseens = false;
7932 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7934 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7935 Package *package = [packages_ objectAtIndex:offset];
7937 BOOL uae = [package upgradableAndEssential:YES];
7941 time_t seen([package seen]);
7943 if (section == nil || last != seen) {
7947 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7950 _profile(ChangesController$reloadData$Allocate)
7951 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7952 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7953 [sections_ addObject:section];
7957 [section addToCount];
7958 } else if ([package ignored]) {
7959 if (ignored == nil) {
7960 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7962 [ignored addToCount];
7965 [upgradable addToCount];
7970 CFRelease(formatter);
7973 Section *last = [sections_ lastObject];
7974 size_t count = [last count];
7975 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7976 [sections_ removeLastObject];
7979 if ([ignored count] != 0)
7980 [sections_ insertObject:ignored atIndex:0];
7982 [sections_ insertObject:upgradable atIndex:0];
7986 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7987 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7988 style:UIBarButtonItemStylePlain
7990 action:@selector(upgradeButtonClicked)
7991 ] autorelease]) animated:YES];
7993 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7994 initWithTitle:UCLocalize("REFRESH")
7995 style:UIBarButtonItemStylePlain
7997 action:@selector(refreshButtonClicked)
7998 ] autorelease]) animated:YES];
8003 - (void) reloadData {
8005 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
8010 /* Search Controller {{{ */
8011 @interface SearchController : FilteredPackageListController <
8014 _H<UISearchBar, 1> search_;
8018 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
8019 - (void) reloadData;
8023 @implementation SearchController
8025 - (NSURL *) referrerURL {
8026 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
8029 - (NSURL *) navigationURL {
8030 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
8031 return [NSURL URLWithString:@"cydia://search"];
8033 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
8036 - (NSArray *) termsForQuery:(NSString *)query {
8037 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
8038 for (NSString *component in [query componentsSeparatedByString:@" "])
8039 if ([component length] != 0)
8040 [terms addObject:component];
8045 - (void) useSearch {
8046 [self setObject:[self termsForQuery:[search_ text]] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
8051 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
8052 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8057 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
8058 [search_ resignFirstResponder];
8062 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
8063 [search_ setText:@""];
8064 [self searchBarButtonClicked:searchBar];
8067 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
8068 [self searchBarButtonClicked:searchBar];
8071 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
8072 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8076 - (bool) shouldYield {
8080 - (bool) shouldBlock {
8081 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
8084 - (bool) isSummarized {
8085 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
8088 - (bool) showsSections {
8092 - (NSMutableArray *) _reloadPackages {
8093 NSMutableArray *packages([super _reloadPackages]);
8094 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8095 [packages radixSortUsingSelector:@selector(rank)];
8099 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
8100 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[self termsForQuery:query]])) {
8101 search_ = [[[UISearchBar alloc] init] autorelease];
8102 [search_ setDelegate:self];
8105 [search_ setText:query];
8109 - (void) viewDidAppear:(BOOL)animated {
8110 [super viewDidAppear:animated];
8112 if (!searchloaded_) {
8113 searchloaded_ = YES;
8114 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
8115 [search_ layoutSubviews];
8116 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
8118 UITextField *textField;
8119 if ([search_ respondsToSelector:@selector(searchField)])
8120 textField = [search_ searchField];
8122 textField = MSHookIvar<UITextField *>(search_, "_searchField");
8124 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8125 [textField setEnablesReturnKeyAutomatically:NO];
8126 [[self navigationItem] setTitleView:textField];
8129 if ([self isSummarized])
8130 [search_ becomeFirstResponder];
8133 - (void) reloadData {
8134 id object([search_ text]);
8135 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8136 object = [self termsForQuery:object];
8138 [self setObject:object];
8144 - (void) didSelectPackage:(Package *)package {
8145 [search_ resignFirstResponder];
8146 [super didSelectPackage:package];
8151 /* Package Settings Controller {{{ */
8152 @interface PackageSettingsController : CyteViewController <
8153 UITableViewDataSource,
8156 _transient Database *database_;
8158 _H<Package> package_;
8159 _H<UITableView, 2> table_;
8160 _H<UISwitch> subscribedSwitch_;
8161 _H<UISwitch> ignoredSwitch_;
8162 _H<UITableViewCell> subscribedCell_;
8163 _H<UITableViewCell> ignoredCell_;
8166 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
8170 @implementation PackageSettingsController
8172 - (NSURL *) navigationURL {
8173 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
8176 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8177 if (package_ == nil)
8180 if ([package_ installed] == nil)
8186 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8187 if (package_ == nil)
8190 // both sections contain just one item right now.
8194 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8198 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8200 return UCLocalize("SHOW_ALL_CHANGES_EX");
8202 return UCLocalize("IGNORE_UPGRADES_EX");
8205 - (void) onSubscribed:(id)control {
8206 bool value([control isOn]);
8207 if (package_ == nil)
8209 if ([package_ setSubscribed:value])
8210 [delegate_ updateData];
8213 - (void) _updateIgnored {
8214 const char *package([name_ UTF8String]);
8215 bool on([ignoredSwitch_ isOn]);
8217 pid_t pid(ExecFork());
8219 FILE *dpkg(popen("dpkg --set-selections", "w"));
8220 fwrite(package, strlen(package), 1, dpkg);
8223 fwrite(" hold\n", 6, 1, dpkg);
8225 fwrite(" install\n", 9, 1, dpkg);
8236 - (void) onIgnored:(id)control {
8237 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8238 [invocation setTarget:self];
8239 [invocation setSelector:@selector(_updateIgnored)];
8241 [delegate_ reloadDataWithInvocation:invocation];
8244 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8245 if (package_ == nil)
8248 switch ([indexPath section]) {
8249 case 0: return subscribedCell_;
8250 case 1: return ignoredCell_;
8259 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8260 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8261 [self setView:view];
8263 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8264 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8265 [(UITableView *) table_ setDataSource:self];
8266 [table_ setDelegate:self];
8267 [view addSubview:table_];
8269 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8270 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8271 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8273 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8274 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8275 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8277 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8278 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8279 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8280 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8282 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8283 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8284 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8285 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8288 - (void) viewDidLoad {
8289 [super viewDidLoad];
8291 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8294 - (void) releaseSubviews {
8296 subscribedCell_ = nil;
8298 ignoredSwitch_ = nil;
8299 subscribedSwitch_ = nil;
8301 [super releaseSubviews];
8304 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8305 if ((self = [super init]) != nil) {
8306 database_ = database;
8311 - (void) reloadData {
8314 package_ = [database_ packageWithName:name_];
8316 if (package_ != nil) {
8317 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8318 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8319 } // XXX: what now, G?
8321 [table_ reloadData];
8327 /* Installed Controller {{{ */
8328 @interface InstalledController : FilteredPackageListController {
8332 - (id) initWithDatabase:(Database *)database;
8334 - (void) updateRoleButton;
8335 - (void) queueStatusDidChange;
8339 @implementation InstalledController
8341 - (NSURL *) referrerURL {
8342 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8345 - (NSURL *) navigationURL {
8346 return [NSURL URLWithString:@"cydia://installed"];
8349 - (id) initWithDatabase:(Database *)database {
8350 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8351 [self updateRoleButton];
8352 [self queueStatusDidChange];
8357 - (void) queueButtonClicked {
8362 - (void) queueStatusDidChange {
8366 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8367 initWithTitle:UCLocalize("QUEUE")
8368 style:UIBarButtonItemStyleDone
8370 action:@selector(queueButtonClicked)
8373 [[self navigationItem] setLeftBarButtonItem:nil];
8379 - (void) updateRoleButton {
8380 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8381 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8382 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8383 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8385 action:@selector(roleButtonClicked)
8389 - (void) roleButtonClicked {
8390 [self setObject:[NSNumber numberWithBool:expert_]];
8394 [self updateRoleButton];
8400 /* Source Cell {{{ */
8401 @interface SourceCell : CyteTableViewCell <
8402 CyteTableViewCellDelegate
8406 _H<NSString> origin_;
8407 _H<NSString> label_;
8410 - (void) setSource:(Source *)source;
8414 @implementation SourceCell
8416 - (void) _setImage:(NSArray *)data {
8417 if ([url_ isEqual:[data objectAtIndex:0]]) {
8418 icon_ = [data objectAtIndex:1];
8419 [content_ setNeedsDisplay];
8423 - (void) _setSource:(NSURL *) url {
8424 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8426 if (NSData *data = [NSURLConnection
8427 sendSynchronousRequest:[NSURLRequest
8429 cachePolicy:NSURLRequestUseProtocolCachePolicy
8433 returningResponse:NULL
8436 if (UIImage *image = [UIImage imageWithData:data])
8437 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8442 - (void) setSource:(Source *)source {
8443 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8445 origin_ = [source name];
8446 label_ = [source rooturi];
8448 [content_ setNeedsDisplay];
8450 url_ = [source iconURL];
8451 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8454 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8455 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8456 UIView *content([self contentView]);
8457 CGRect bounds([content bounds]);
8459 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8460 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8461 [content_ setBackgroundColor:[UIColor whiteColor]];
8462 [content addSubview:content_];
8464 [content_ setDelegate:self];
8465 [content_ setOpaque:YES];
8467 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8471 - (NSString *) accessibilityLabel {
8475 - (void) drawContentRect:(CGRect)rect {
8476 bool highlighted(highlighted_);
8477 float width(rect.size.width);
8481 rect.size = [(UIImage *) icon_ size];
8483 while (rect.size.width > 32 || rect.size.height > 32) {
8484 rect.size.width /= 2;
8485 rect.size.height /= 2;
8488 rect.origin.x = 25 - rect.size.width / 2;
8489 rect.origin.y = 25 - rect.size.height / 2;
8491 [icon_ drawInRect:rect];
8499 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 65) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8503 [label_ drawAtPoint:CGPointMake(48, 29) forWidth:(width - 65) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8508 /* Source Controller {{{ */
8509 @interface SourceController : FilteredPackageListController {
8510 _transient Source *source_;
8514 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8518 @implementation SourceController
8520 - (NSURL *) referrerURL {
8521 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sources/%@", UI_, [key_ stringByAddingPercentEscapesIncludingReserved]]];
8524 - (NSURL *) navigationURL {
8525 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8528 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8529 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8531 key_ = [source key];
8535 - (void) reloadData {
8536 source_ = [database_ sourceWithKey:key_];
8537 key_ = [source_ key];
8538 [self setObject:source_];
8540 [[self navigationItem] setTitle:[source_ label]];
8547 /* Sources Controller {{{ */
8548 @interface SourcesController : CyteViewController <
8549 UITableViewDataSource,
8552 _transient Database *database_;
8555 _H<UITableView, 2> list_;
8556 _H<NSMutableArray> sources_;
8560 _H<UIProgressHUD> hud_;
8563 //NSURLConnection *installer_;
8564 NSURLConnection *trivial_bz2_;
8565 NSURLConnection *trivial_gz_;
8566 //NSURLConnection *automatic_;
8571 - (id) initWithDatabase:(Database *)database;
8572 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8576 @implementation SourcesController
8578 - (void) _releaseConnection:(NSURLConnection *)connection {
8579 if (connection != nil) {
8580 [connection cancel];
8581 //[connection setDelegate:nil];
8582 [connection release];
8587 //[self _releaseConnection:installer_];
8588 [self _releaseConnection:trivial_gz_];
8589 [self _releaseConnection:trivial_bz2_];
8590 //[self _releaseConnection:automatic_];
8595 - (NSURL *) navigationURL {
8596 return [NSURL URLWithString:@"cydia://sources"];
8599 - (void) viewDidAppear:(BOOL)animated {
8600 [super viewDidAppear:animated];
8601 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8604 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8608 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8612 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8613 return [sources_ count];
8616 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8617 @synchronized (database_) {
8618 if ([database_ era] != era_)
8621 NSUInteger index([indexPath row]);
8622 return index < [sources_ count] ? [sources_ objectAtIndex:index] : nil;
8625 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8626 static NSString *cellIdentifier = @"SourceCell";
8628 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8629 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8630 [cell setSource:[self sourceAtIndexPath:indexPath]];
8631 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8636 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8637 Source *source = [self sourceAtIndexPath:indexPath];
8638 if (source == nil) return;
8640 SourceController *controller = [[[SourceController alloc]
8641 initWithDatabase:database_
8645 [controller setDelegate:delegate_];
8647 [[self navigationController] pushViewController:controller animated:YES];
8650 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8651 Source *source = [self sourceAtIndexPath:indexPath];
8652 return [source record] != nil;
8655 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8656 if (editingStyle == UITableViewCellEditingStyleDelete) {
8657 Source *source = [self sourceAtIndexPath:indexPath];
8658 if (source == nil) return;
8660 [Sources_ removeObjectForKey:[source key]];
8663 [delegate_ _saveConfig];
8664 [delegate_ reloadDataWithInvocation:nil];
8669 [delegate_ addTrivialSource:href_];
8672 [delegate_ syncData];
8675 - (NSString *) getWarning {
8676 NSString *href(href_);
8677 NSRange colon([href rangeOfString:@"://"]);
8678 if (colon.location != NSNotFound)
8679 href = [href substringFromIndex:(colon.location + 3)];
8680 href = [href stringByAddingPercentEscapes];
8681 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8683 NSURL *url([NSURL URLWithString:href]);
8685 NSStringEncoding encoding;
8686 NSError *error(nil);
8688 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8689 return [warning length] == 0 ? nil : warning;
8693 - (void) _endConnection:(NSURLConnection *)connection {
8694 // XXX: the memory management in this method is horribly awkward
8696 NSURLConnection **field = NULL;
8697 if (connection == trivial_bz2_)
8698 field = &trivial_bz2_;
8699 else if (connection == trivial_gz_)
8700 field = &trivial_gz_;
8701 _assert(field != NULL);
8702 [connection release];
8706 trivial_bz2_ == nil &&
8709 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8711 [delegate_ releaseNetworkActivityIndicator];
8713 [delegate_ removeProgressHUD:hud_];
8717 if (warning != nil) {
8718 UIAlertView *alert = [[[UIAlertView alloc]
8719 initWithTitle:UCLocalize("SOURCE_WARNING")
8722 cancelButtonTitle:UCLocalize("CANCEL")
8724 UCLocalize("ADD_ANYWAY"),
8728 [alert setContext:@"warning"];
8729 [alert setNumberOfRows:1];
8732 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8738 } else if (error_ != nil) {
8739 UIAlertView *alert = [[[UIAlertView alloc]
8740 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8741 message:[error_ localizedDescription]
8743 cancelButtonTitle:UCLocalize("OK")
8744 otherButtonTitles:nil
8747 [alert setContext:@"urlerror"];
8752 UIAlertView *alert = [[[UIAlertView alloc]
8753 initWithTitle:UCLocalize("NOT_REPOSITORY")
8754 message:UCLocalize("NOT_REPOSITORY_EX")
8756 cancelButtonTitle:UCLocalize("OK")
8757 otherButtonTitles:nil
8760 [alert setContext:@"trivial"];
8770 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8771 switch ([response statusCode]) {
8777 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8778 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8780 [self _endConnection:connection];
8783 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8784 [self _endConnection:connection];
8787 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8788 NSURL *url([NSURL URLWithString:href]);
8790 NSMutableURLRequest *request = [NSMutableURLRequest
8792 cachePolicy:NSURLRequestUseProtocolCachePolicy
8796 [request setHTTPMethod:method];
8798 if (Machine_ != NULL)
8799 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8801 if (UniqueID_ != nil)
8802 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8804 if ([url isCydiaSecure]) {
8805 if (UniqueID_ != nil)
8806 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8809 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8812 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8813 NSString *context([alert context]);
8815 if ([context isEqualToString:@"source"]) {
8818 NSString *href = [[alert textField] text];
8820 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8822 if (![href hasSuffix:@"/"])
8823 href_ = [href stringByAppendingString:@"/"];
8827 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8828 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8829 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8833 // XXX: this is stupid
8834 hud_ = [delegate_ addProgressHUD];
8835 [hud_ setText:UCLocalize("VERIFYING_URL")];
8836 [delegate_ retainNetworkActivityIndicator];
8845 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8846 } else if ([context isEqualToString:@"trivial"])
8847 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8848 else if ([context isEqualToString:@"urlerror"])
8849 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8850 else if ([context isEqualToString:@"warning"]) {
8853 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8862 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8867 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8868 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8869 [list_ setRowHeight:53];
8870 [(UITableView *) list_ setDataSource:self];
8871 [list_ setDelegate:self];
8872 [self setView:list_];
8875 - (void) viewDidLoad {
8876 [super viewDidLoad];
8878 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8879 [self updateButtonsForEditingStatusAnimated:NO];
8882 - (void) viewWillAppear:(BOOL)animated {
8883 [super viewWillAppear:animated];
8885 [list_ setEditing:NO];
8886 [self updateButtonsForEditingStatusAnimated:NO];
8889 - (void) releaseSubviews {
8894 [super releaseSubviews];
8897 - (id) initWithDatabase:(Database *)database {
8898 if ((self = [super init]) != nil) {
8899 database_ = database;
8903 - (void) reloadData {
8906 @synchronized (database_) {
8907 era_ = [database_ era];
8909 sources_ = [NSMutableArray arrayWithCapacity:16];
8910 [sources_ addObjectsFromArray:[database_ sources]];
8912 [sources_ sortUsingSelector:@selector(compareByName:)];
8915 int count([sources_ count]);
8917 for (int i = 0; i != count; i++) {
8918 if ([[sources_ objectAtIndex:i] record] == nil)
8926 - (void) showAddSourcePrompt {
8927 UIAlertView *alert = [[[UIAlertView alloc]
8928 initWithTitle:UCLocalize("ENTER_APT_URL")
8931 cancelButtonTitle:UCLocalize("CANCEL")
8933 UCLocalize("ADD_SOURCE"),
8937 [alert setContext:@"source"];
8939 [alert setNumberOfRows:1];
8940 [alert addTextFieldWithValue:@"http://" label:@""];
8942 UITextInputTraits *traits = [[alert textField] textInputTraits];
8943 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8944 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8945 [traits setKeyboardType:UIKeyboardTypeURL];
8946 // XXX: UIReturnKeyDone
8947 [traits setReturnKeyType:UIReturnKeyNext];
8952 - (void) addButtonClicked {
8953 [self showAddSourcePrompt];
8956 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8957 BOOL editing([list_ isEditing]);
8959 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8960 initWithTitle:UCLocalize("ADD")
8961 style:UIBarButtonItemStylePlain
8963 action:@selector(addButtonClicked)
8964 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8966 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8967 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8968 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8970 action:@selector(editButtonClicked)
8971 ] autorelease] animated:animated];
8973 if (IsWildcat_ && !editing)
8974 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8975 initWithTitle:UCLocalize("SETTINGS")
8976 style:UIBarButtonItemStylePlain
8978 action:@selector(settingsButtonClicked)
8982 - (void) settingsButtonClicked {
8983 [delegate_ showSettings];
8986 - (void) editButtonClicked {
8987 [list_ setEditing:![list_ isEditing] animated:YES];
8988 [self updateButtonsForEditingStatusAnimated:YES];
8994 /* Settings Controller {{{ */
8995 @interface SettingsController : CyteViewController <
8996 UITableViewDataSource,
8999 _transient Database *database_;
9000 // XXX: ok, "roledelegate_"?...
9001 _transient id roledelegate_;
9002 _H<UITableView, 2> table_;
9003 _H<UISegmentedControl> segment_;
9004 _H<UIView> container_;
9007 - (void) showDoneButton;
9008 - (void) resizeSegmentedControl;
9012 @implementation SettingsController
9015 table_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
9016 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9017 [table_ setDelegate:self];
9018 [(UITableView *) table_ setDataSource:self];
9019 [self setView:table_];
9021 NSArray *items = [NSArray arrayWithObjects:
9023 UCLocalize("HACKER"),
9024 UCLocalize("DEVELOPER"),
9026 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
9027 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
9028 [container_ addSubview:segment_];
9031 - (void) viewDidLoad {
9032 [super viewDidLoad];
9034 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
9037 if ([Role_ isEqualToString:@"User"]) index = 0;
9038 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
9039 if ([Role_ isEqualToString:@"Developer"]) index = 2;
9041 [segment_ setSelectedSegmentIndex:index];
9042 [self showDoneButton];
9045 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
9046 [self resizeSegmentedControl];
9049 - (void) releaseSubviews {
9054 [super releaseSubviews];
9057 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
9058 if ((self = [super init]) != nil) {
9059 database_ = database;
9060 roledelegate_ = delegate;
9064 - (void) resizeSegmentedControl {
9065 CGFloat width = [[self view] frame].size.width;
9066 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
9069 - (void) viewWillAppear:(BOOL)animated {
9070 [super viewWillAppear:animated];
9071 [self resizeSegmentedControl];
9074 - (void) viewDidAppear:(BOOL)animated {
9075 [super viewDidAppear:animated];
9076 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
9077 [self resizeSegmentedControl];
9080 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
9081 [self resizeSegmentedControl];
9084 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
9085 [self resizeSegmentedControl];
9089 NSString *role(nil);
9091 switch ([segment_ selectedSegmentIndex]) {
9092 case 0: role = @"User"; break;
9093 case 1: role = @"Hacker"; break;
9094 case 2: role = @"Developer"; break;
9099 if (![role isEqualToString:Role_]) {
9100 bool rolling(Role_ == nil);
9103 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
9107 [Metadata_ setObject:Settings_ forKey:@"Settings"];
9111 [roledelegate_ loadData];
9113 [roledelegate_ updateData];
9117 - (void) segmentChanged:(UISegmentedControl *)control {
9118 [self showDoneButton];
9121 - (void) saveAndClose {
9124 [[self navigationItem] setRightBarButtonItem:nil];
9125 [[self navigationController] dismissModalViewControllerAnimated:YES];
9128 - (void) doneButtonClicked {
9129 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
9130 [spinner startAnimating];
9131 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
9132 [[self navigationItem] setRightBarButtonItem:spinItem];
9134 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
9137 - (void) showDoneButton {
9138 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
9139 initWithTitle:UCLocalize("DONE")
9140 style:UIBarButtonItemStyleDone
9142 action:@selector(doneButtonClicked)
9143 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
9146 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
9147 // XXX: For not having a single cell in the table, this sure is a lot of sections.
9151 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
9155 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
9156 return nil; // This method is required by the protocol.
9159 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
9161 return UCLocalize("ROLE_EX");
9163 return [NSString stringWithFormat:
9164 @"%@: %@\n%@: %@\n%@: %@",
9165 UCLocalize("USER"), UCLocalize("USER_EX"),
9166 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
9167 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
9172 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
9173 return section == 3 ? 44.0f : 0;
9176 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
9177 return section == 3 ? container_ : nil;
9180 - (void) reloadData {
9183 [table_ reloadData];
9188 /* Stash Controller {{{ */
9189 @interface StashController : CyteViewController {
9190 _H<UIActivityIndicatorView> spinner_;
9191 _H<UILabel> status_;
9192 _H<UILabel> caption_;
9197 @implementation StashController
9200 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
9201 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
9202 [self setView:view];
9204 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
9206 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
9207 CGRect spinrect = [spinner_ frame];
9208 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
9209 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
9210 [spinner_ setFrame:spinrect];
9211 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
9212 [view addSubview:spinner_];
9213 [spinner_ startAnimating];
9216 captrect.size.width = [[self view] frame].size.width;
9217 captrect.size.height = 40.0f;
9218 captrect.origin.x = 0;
9219 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
9220 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
9221 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
9222 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9223 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
9224 [caption_ setTextColor:[UIColor whiteColor]];
9225 [caption_ setBackgroundColor:[UIColor clearColor]];
9226 [caption_ setShadowColor:[UIColor blackColor]];
9227 [caption_ setTextAlignment:UITextAlignmentCenter];
9228 [view addSubview:caption_];
9231 statusrect.size.width = [[self view] frame].size.width;
9232 statusrect.size.height = 30.0f;
9233 statusrect.origin.x = 0;
9234 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
9235 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
9236 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9237 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
9238 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
9239 [status_ setTextColor:[UIColor whiteColor]];
9240 [status_ setBackgroundColor:[UIColor clearColor]];
9241 [status_ setShadowColor:[UIColor blackColor]];
9242 [status_ setTextAlignment:UITextAlignmentCenter];
9243 [view addSubview:status_];
9246 - (void) releaseSubviews {
9251 [super releaseSubviews];
9257 @interface CYURLCache : SDURLCache {
9262 @implementation CYURLCache
9264 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
9267 else if ([event isEqualToString:@"no-cache"])
9269 else if ([event isEqualToString:@"store"])
9271 else if ([event isEqualToString:@"invalid"])
9273 else if ([event isEqualToString:@"memory"])
9275 else if ([event isEqualToString:@"disk"])
9277 else if ([event isEqualToString:@"miss"])
9280 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
9284 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
9285 if (NSURLResponse *response = [cached response])
9286 if (NSString *mime = [response MIMEType])
9287 if ([mime isEqualToString:@"text/cache-manifest"]) {
9288 NSURL *url([response URL]);
9291 NSLog(@"###: %@", [url absoluteString]);
9294 @synchronized (HostConfig_) {
9295 [CachedURLs_ addObject:url];
9299 [super storeCachedResponse:cached forRequest:request];
9304 @interface Cydia : UIApplication <
9305 ConfirmationControllerDelegate,
9308 UINavigationControllerDelegate,
9309 UITabBarControllerDelegate
9311 _H<UIWindow> window_;
9312 _H<CYTabBarController> tabbar_;
9313 _H<CydiaLoadingViewController> emulated_;
9315 _H<NSMutableArray> essential_;
9316 _H<NSMutableArray> broken_;
9318 Database *database_;
9320 _H<NSURL> starturl_;
9325 _H<StashController> stash_;
9334 @implementation Cydia
9336 - (void) lockSuspend {
9337 if (locked_++ == 0) {
9338 if ($SBSSetInterceptsMenuButtonForever != NULL)
9339 (*$SBSSetInterceptsMenuButtonForever)(true);
9341 [self setIdleTimerDisabled:YES];
9345 - (void) unlockSuspend {
9346 if (--locked_ == 0) {
9347 [self setIdleTimerDisabled:NO];
9349 if ($SBSSetInterceptsMenuButtonForever != NULL)
9350 (*$SBSSetInterceptsMenuButtonForever)(false);
9354 - (void) beginUpdate {
9355 [tabbar_ beginUpdate];
9359 return [tabbar_ updating];
9363 if ([broken_ count] != 0) {
9364 int count = [broken_ count];
9366 UIAlertView *alert = [[[UIAlertView alloc]
9367 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9368 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9370 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9372 UCLocalize("TEMPORARY_IGNORE"),
9376 [alert setContext:@"fixhalf"];
9377 [alert setNumberOfRows:2];
9379 } else if (!Ignored_ && [essential_ count] != 0) {
9380 int count = [essential_ count];
9382 UIAlertView *alert = [[[UIAlertView alloc]
9383 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9384 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9386 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9388 UCLocalize("UPGRADE_ESSENTIAL"),
9389 UCLocalize("COMPLETE_UPGRADE"),
9393 [alert setContext:@"upgrade"];
9398 - (void) returnToCydia {
9402 - (void) _saveConfig {
9403 @synchronized (database_) {
9410 NSString *error(nil);
9412 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9414 NSError *error(nil);
9415 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9416 NSLog(@"failure to save metadata data: %@", error);
9421 NSLog(@"failure to serialize metadata: %@", error);
9425 CydiaWriteSources();
9428 // Navigation controller for the queuing badge.
9429 - (UINavigationController *) queueNavigationController {
9430 NSArray *controllers = [tabbar_ viewControllers];
9431 return [controllers objectAtIndex:3];
9434 - (void) unloadData {
9435 [tabbar_ unloadData];
9438 - (void) _updateData {
9442 UINavigationController *navigation = [self queueNavigationController];
9444 id queuedelegate = nil;
9445 if ([[navigation viewControllers] count] > 0)
9446 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9448 [queuedelegate queueStatusDidChange];
9449 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9452 - (void) _refreshIfPossible:(NSDate *)update {
9453 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9455 bool recently = false;
9456 if (update != nil) {
9457 NSTimeInterval interval([update timeIntervalSinceNow]);
9458 if (interval <= 0 && interval > -(15*60))
9462 // Don't automatic refresh if:
9463 // - We already refreshed recently.
9464 // - We already auto-refreshed this launch.
9465 // - Auto-refresh is disabled.
9466 // - Cydia's server is not reachable
9467 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9468 // If we are cancelling, we need to make sure it knows it's already loaded.
9471 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9473 // We are going to load, so remember that.
9476 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9482 - (void) refreshIfPossible {
9483 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9486 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9487 @synchronized (self) {
9488 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9490 [hud setText:UCLocalize("RELOADING_DATA")];
9492 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9496 [essential_ removeAllObjects];
9497 [broken_ removeAllObjects];
9499 NSArray *packages([database_ packages]);
9500 for (Package *package in packages) {
9502 [broken_ addObject:package];
9503 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9504 if ([package essential] && [package installed] != nil)
9505 [essential_ addObject:package];
9510 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9513 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9514 [changesItem setBadgeValue:badge];
9515 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9516 [self setApplicationIconBadgeNumber:changes];
9519 [changesItem setBadgeValue:nil];
9520 [changesItem setAnimatedBadge:NO];
9521 [self setApplicationIconBadgeNumber:0];
9527 [self removeProgressHUD:hud];
9530 - (void) updateData {
9534 - (void) updateDataAndLoad {
9536 if ([database_ progressDelegate] == nil)
9542 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9545 - (void) disemulate {
9546 if (emulated_ == nil)
9549 [window_ addSubview:[tabbar_ view]];
9550 [[emulated_ view] removeFromSuperview];
9552 [window_ setUserInteractionEnabled:YES];
9555 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9556 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9558 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9560 UIViewController *parent;
9561 if (emulated_ == nil)
9570 [parent presentModalViewController:navigation animated:YES];
9573 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9574 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9576 if (navigation != nil)
9577 [navigation pushViewController:progress animated:YES];
9579 [self presentModalViewController:progress force:YES];
9581 [progress invoke:invocation withTitle:title];
9585 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9586 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9589 - (void) repairWithInvocation:(NSInvocation *)invocation {
9591 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9595 - (void) repairWithSelector:(SEL)selector {
9596 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9599 - (void) reloadData {
9600 [self reloadDataWithInvocation:nil];
9601 if ([database_ progressDelegate] == nil)
9607 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9610 - (void) addSource:(NSDictionary *) source {
9611 CydiaAddSource(source);
9614 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9615 CydiaAddSource(href, distribution, sections);
9618 - (void) addTrivialSource:(NSString *)href {
9619 CydiaAddSource(href, @"./");
9622 - (void) updateValues {
9627 pkgProblemResolver *resolver = [database_ resolver];
9629 resolver->InstallProtect();
9630 if (!resolver->Resolve(true))
9635 // XXX: this is a really crappy way of doing this.
9636 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9637 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9638 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9639 if ([tabbar_ updating])
9640 [tabbar_ cancelUpdate];
9642 if (![database_ prepare])
9645 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9646 [page setDelegate:self];
9647 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9650 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9651 [tabbar_ presentModalViewController:confirm_ animated:YES];
9657 @synchronized (self) {
9662 - (void) clearPackage:(Package *)package {
9663 @synchronized (self) {
9670 - (void) installPackages:(NSArray *)packages {
9671 @synchronized (self) {
9672 for (Package *package in packages)
9679 - (void) installPackage:(Package *)package {
9680 @synchronized (self) {
9687 - (void) removePackage:(Package *)package {
9688 @synchronized (self) {
9695 - (void) distUpgrade {
9696 @synchronized (self) {
9697 if (![database_ upgrade])
9705 system("su -c /usr/bin/uicache mobile");
9710 UIProgressHUD *hud([self addProgressHUD]);
9711 [hud setText:UCLocalize("LOADING")];
9712 [self yieldToSelector:@selector(_uicache)];
9713 [self removeProgressHUD:hud];
9717 [database_ perform];
9718 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9719 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9722 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9725 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9726 [self unlockSuspend];
9729 - (void) showSettings {
9730 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9733 - (void) retainNetworkActivityIndicator {
9734 if (activity_++ == 0)
9735 [self setNetworkActivityIndicatorVisible:YES];
9738 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9742 - (void) releaseNetworkActivityIndicator {
9743 if (--activity_ == 0)
9744 [self setNetworkActivityIndicatorVisible:NO];
9747 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9752 - (void) cancelAndClear:(bool)clear {
9753 @synchronized (self) {
9765 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9766 NSString *context([alert context]);
9768 if ([context isEqualToString:@"conffile"]) {
9769 FILE *input = [database_ input];
9770 if (button == [alert cancelButtonIndex])
9771 fprintf(input, "N\n");
9772 else if (button == [alert firstOtherButtonIndex])
9773 fprintf(input, "Y\n");
9776 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9777 } else if ([context isEqualToString:@"fixhalf"]) {
9778 if (button == [alert cancelButtonIndex]) {
9779 @synchronized (self) {
9780 for (Package *broken in (id) broken_) {
9783 NSString *id = [broken id];
9784 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9785 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9786 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9787 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9793 } else if (button == [alert firstOtherButtonIndex]) {
9794 [broken_ removeAllObjects];
9798 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9799 } else if ([context isEqualToString:@"upgrade"]) {
9800 if (button == [alert firstOtherButtonIndex]) {
9801 @synchronized (self) {
9802 for (Package *essential in (id) essential_)
9803 [essential install];
9808 } else if (button == [alert firstOtherButtonIndex] + 1) {
9810 } else if (button == [alert cancelButtonIndex]) {
9814 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9818 - (void) system:(NSString *)command {
9819 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9822 system([command UTF8String]);
9828 - (void) applicationWillSuspend {
9830 [super applicationWillSuspend];
9833 - (BOOL) isSafeToSuspend {
9836 NSLog(@"isSafeToSuspend: locked_ != 0");
9841 // Use external process status API internally.
9842 // This is probably a really bad idea.
9843 // XXX: what is the point of this? does this solve anything at all?
9844 uint64_t status = 0;
9846 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9847 notify_get_state(notify_token, &status);
9848 notify_cancel(notify_token);
9853 NSLog(@"isSafeToSuspend: status != 0");
9859 NSLog(@"isSafeToSuspend: -> true");
9864 - (void) applicationSuspend:(__GSEvent *)event {
9865 if ([self isSafeToSuspend])
9866 [super applicationSuspend:event];
9869 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9870 if ([self isSafeToSuspend])
9871 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9874 - (void) _setSuspended:(BOOL)value {
9875 if ([self isSafeToSuspend])
9876 [super _setSuspended:value];
9879 - (UIProgressHUD *) addProgressHUD {
9880 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9881 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9883 [window_ setUserInteractionEnabled:NO];
9885 UIViewController *target(tabbar_);
9886 if (UIViewController *modal = [target modalViewController])
9889 [hud showInView:[target view]];
9895 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9896 [self unlockSuspend];
9898 [hud removeFromSuperview];
9899 [window_ setUserInteractionEnabled:YES];
9902 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9903 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9906 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9907 NSString *scheme([[url scheme] lowercaseString]);
9908 if ([[url absoluteString] length] <= [scheme length] + 3)
9910 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9911 NSArray *components([path componentsSeparatedByString:@"/"]);
9913 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9914 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9915 if (controller != nil)
9916 [controller setDelegate:self];
9920 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9923 NSString *base([components objectAtIndex:0]);
9925 CyteViewController *controller = nil;
9927 if ([base isEqualToString:@"url"]) {
9928 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9929 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9930 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9931 } else if (!external && [components count] == 1) {
9932 if ([base isEqualToString:@"manage"]) {
9933 controller = [[[ManageController alloc] init] autorelease];
9936 if ([base isEqualToString:@"storage"]) {
9937 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9940 if ([base isEqualToString:@"sources"]) {
9941 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9944 if ([base isEqualToString:@"home"]) {
9945 controller = [[[HomeController alloc] init] autorelease];
9948 if ([base isEqualToString:@"sections"]) {
9949 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9952 if ([base isEqualToString:@"search"]) {
9953 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9956 if ([base isEqualToString:@"changes"]) {
9957 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9960 if ([base isEqualToString:@"installed"]) {
9961 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9963 } else if ([components count] == 2) {
9964 NSString *argument = [components objectAtIndex:1];
9966 if ([base isEqualToString:@"package"]) {
9967 controller = [self pageForPackage:argument withReferrer:referrer];
9970 if (!external && [base isEqualToString:@"search"]) {
9971 controller = [[[SearchController alloc] initWithDatabase:database_ query:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9974 if (!external && [base isEqualToString:@"sections"]) {
9975 if ([argument isEqualToString:@"all"])
9977 controller = [[[SectionController alloc] initWithDatabase:database_ section:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9980 if (!external && [base isEqualToString:@"sources"]) {
9981 if ([argument isEqualToString:@"add"]) {
9982 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9983 [(SourcesController *)controller showAddSourcePrompt];
9985 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9986 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9990 if (!external && [base isEqualToString:@"launch"]) {
9991 [self launchApplicationWithIdentifier:argument suspended:NO];
9994 } else if (!external && [components count] == 3) {
9995 NSString *arg1 = [components objectAtIndex:1];
9996 NSString *arg2 = [components objectAtIndex:2];
9998 if ([base isEqualToString:@"package"]) {
9999 if ([arg2 isEqualToString:@"settings"]) {
10000 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
10001 } else if ([arg2 isEqualToString:@"files"]) {
10002 if (Package *package = [database_ packageWithName:arg1]) {
10003 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
10004 [(FileTable *)controller setPackage:package];
10010 [controller setDelegate:self];
10014 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
10015 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
10018 [tabbar_ setUnselectedViewController:page];
10020 return page != nil;
10023 - (void) applicationOpenURL:(NSURL *)url {
10024 [super applicationOpenURL:url];
10029 [self openCydiaURL:url forExternal:YES];
10032 - (void) applicationWillResignActive:(UIApplication *)application {
10033 // Stop refreshing if you get a phone call or lock the device.
10034 if ([tabbar_ updating])
10035 [tabbar_ cancelUpdate];
10037 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
10038 [super applicationWillResignActive:application];
10041 - (void) saveState {
10042 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
10043 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
10044 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
10047 [self _saveConfig];
10050 - (void) applicationWillTerminate:(UIApplication *)application {
10054 - (void) setConfigurationData:(NSString *)data {
10055 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
10057 if (!conffile_r(data)) {
10058 lprintf("E:invalid conffile\n");
10062 NSString *ofile = conffile_r[1];
10063 //NSString *nfile = conffile_r[2];
10065 UIAlertView *alert = [[[UIAlertView alloc]
10066 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
10067 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
10069 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
10071 UCLocalize("ACCEPT_NEW_COPY"),
10072 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
10076 [alert setContext:@"conffile"];
10077 [alert setNumberOfRows:2];
10081 - (void) addStashController {
10082 [self lockSuspend];
10083 stash_ = [[[StashController alloc] init] autorelease];
10084 [window_ addSubview:[stash_ view]];
10087 - (void) removeStashController {
10088 [[stash_ view] removeFromSuperview];
10090 [self unlockSuspend];
10094 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
10095 UpdateExternalStatus(1);
10096 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
10097 UpdateExternalStatus(0);
10099 [self removeStashController];
10101 pid_t pid(ExecFork());
10103 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
10104 perror("launchctl stop");
10111 - (void) setupViewControllers {
10112 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
10114 NSMutableArray *items([NSMutableArray arrayWithObjects:
10115 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
10116 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
10117 [[[UITabBarItem alloc] initWithTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES")) image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
10118 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
10122 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
10123 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10125 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10128 NSMutableArray *controllers([NSMutableArray array]);
10129 for (UITabBarItem *item in items) {
10130 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
10131 [controller setTabBarItem:item];
10132 [controllers addObject:controller];
10134 [tabbar_ setViewControllers:controllers];
10136 [tabbar_ setUpdateDelegate:self];
10139 - (void) _sendMemoryWarningNotification {
10140 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
10141 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
10143 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
10146 - (void) _sendMemoryWarningNotifications {
10148 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
10154 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
10156 [[NSURLCache sharedURLCache] removeAllCachedResponses];
10159 - (void) applicationDidFinishLaunching:(id)unused {
10160 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
10163 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
10164 [self setApplicationSupportsShakeToEdit:NO];
10166 @synchronized (HostConfig_) {
10167 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
10170 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
10171 initWithMemoryCapacity:524288
10172 diskCapacity:10485760
10173 diskPath:[NSString stringWithFormat:@"%@/SDURLCache", Cache_]
10176 [CydiaWebViewController _initialize];
10178 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
10180 // this would disallow http{,s} URLs from accessing this data
10181 //[WebView registerURLSchemeAsLocal:@"cydia"];
10183 Font12_ = [UIFont systemFontOfSize:12];
10184 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
10185 Font14_ = [UIFont systemFontOfSize:14];
10186 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
10187 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
10189 essential_ = [NSMutableArray arrayWithCapacity:4];
10190 broken_ = [NSMutableArray arrayWithCapacity:4];
10192 // XXX: I really need this thing... like, seriously... I'm sorry
10193 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
10195 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
10196 [window_ orderFront:self];
10197 [window_ makeKey:self];
10198 [window_ setHidden:NO];
10200 if (false) stash: {
10201 [self addStashController];
10202 // XXX: this would be much cleaner as a yieldToSelector:
10203 // that way the removeStashController could happen right here inline
10204 // we also could no longer require the useless stash_ field anymore
10205 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
10210 int error(stat("/", &root));
10211 _assert(error != -1);
10213 #define Stash_(path) do { \
10214 struct stat folder; \
10215 int error(lstat((path), &folder)); \
10216 if (error != -1 && ( \
10217 folder.st_dev == root.st_dev && \
10218 S_ISDIR(folder.st_mode) \
10219 ) || error == -1 && ( \
10220 errno == ENOENT || \
10225 Stash_("/Applications");
10226 Stash_("/Library/Ringtones");
10227 Stash_("/Library/Wallpaper");
10228 //Stash_("/usr/bin");
10229 Stash_("/usr/include");
10230 Stash_("/usr/lib/pam");
10231 Stash_("/usr/libexec");
10232 Stash_("/usr/share");
10233 //Stash_("/var/lib");
10235 database_ = [Database sharedInstance];
10236 [database_ setDelegate:self];
10238 [window_ setUserInteractionEnabled:NO];
10239 [self setupViewControllers];
10241 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
10242 [window_ addSubview:[emulated_ view]];
10244 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
10248 - (NSArray *) defaultStartPages {
10249 NSMutableArray *standard = [NSMutableArray array];
10250 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
10251 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
10252 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
10254 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
10256 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
10257 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
10259 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10263 - (void) loadData {
10265 if (Role_ == nil) {
10266 [window_ setUserInteractionEnabled:YES];
10267 [self showSettings];
10270 if ([emulated_ modalViewController] != nil)
10271 [emulated_ dismissModalViewControllerAnimated:YES];
10272 [window_ setUserInteractionEnabled:NO];
10275 [self reloadDataWithInvocation:nil];
10276 [self refreshIfPossible];
10281 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
10282 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
10283 int standardIndex = 0;
10284 NSArray *standard = [self defaultStartPages];
10291 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
10292 if (valid && closed != nil) {
10293 NSTimeInterval interval([closed timeIntervalSinceNow]);
10294 // XXX: Is 30 minutes the optimal time here?
10295 if (interval <= -(30*60))
10299 if (valid && [saved count] != [standard count])
10303 for (unsigned int i = 0; i < [standard count]; i++) {
10304 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10305 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10306 // but it's good enough for now.
10307 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10314 NSArray *items = nil;
10316 [tabbar_ setSelectedIndex:savedIndex];
10319 [tabbar_ setSelectedIndex:standardIndex];
10323 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10324 NSArray *stack = [items objectAtIndex:tab];
10325 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10326 NSMutableArray *current = [NSMutableArray array];
10328 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10329 NSString *addr = [stack objectAtIndex:nav];
10330 NSURL *url = [NSURL URLWithString:addr];
10331 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10333 [current addObject:page];
10336 [navigation setViewControllers:current];
10339 // (Try to) show the startup URL.
10340 if (starturl_ != nil) {
10341 [self openCydiaURL:starturl_ forExternal:NO];
10346 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10347 if (item != nil && IsWildcat_) {
10348 [sheet showFromBarButtonItem:item animated:YES];
10350 [sheet showInView:window_];
10354 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10355 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10356 [progress setTitle:task];
10357 [progress addProgressEvent:event];
10360 - (void) addProgressEventForTask:(NSArray *)data {
10361 CydiaProgressEvent *event([data objectAtIndex:0]);
10362 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10363 [self addProgressEvent:event forTask:task];
10366 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10367 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10373 id Alloc_(id self, SEL selector) {
10374 id object = alloc_(self, selector);
10375 lprintf("[%s]A-%p\n", self->isa->name, object);
10380 id Dealloc_(id self, SEL selector) {
10381 id object = dealloc_(self, selector);
10382 lprintf("[%s]D-%p\n", self->isa->name, object);
10386 static NSSet *MobilizedFiles_;
10388 static NSURL *MobilizeURL(NSURL *url) {
10389 NSString *path([url path]);
10390 if ([path hasPrefix:@"/var/root/"]) {
10391 NSString *file([path substringFromIndex:10]);
10392 if ([MobilizedFiles_ containsObject:file])
10393 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10399 Class $CFXPreferencesPropertyListSource;
10400 @class CFXPreferencesPropertyListSource;
10402 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10403 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10404 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10405 url = MobilizeURL(url);
10406 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10407 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10413 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10414 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10415 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10416 url = MobilizeURL(url);
10417 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10418 //NSLog(@"%@ %@", [url absoluteString], value);
10424 Class $NSURLConnection;
10426 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10427 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10429 NSURL *url([copy URL]);
10431 NSString *host([url host]);
10432 NSString *scheme([[url scheme] lowercaseString]);
10434 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10436 @synchronized (HostConfig_) {
10437 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10438 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10439 [copy setHTTPShouldUsePipelining:YES];
10441 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10442 if ([control isEqualToString:@"max-age=0"])
10443 if ([CachedURLs_ containsObject:url]) {
10445 NSLog(@"~~~: %@", url);
10448 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10450 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10451 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10452 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10456 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10462 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10463 CGSize size([[UIScreen mainScreen] bounds].size);
10464 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10465 if ([$WAKWindow hasLandscapeOrientation])
10466 std::swap(size.width, size.height);*/
10470 Class $NSUserDefaults;
10472 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10473 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10474 return [NSString stringWithFormat:@"%@/LocalStorage", Cache_];
10475 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10478 int main(int argc, char *argv[]) {
10479 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10483 UpdateExternalStatus(0);
10485 if (Class $UIDevice = objc_getClass("UIDevice")) {
10486 UIDevice *device([$UIDevice currentDevice]);
10487 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10489 IsWildcat_ = false;
10491 UIScreen *screen([UIScreen mainScreen]);
10492 if ([screen respondsToSelector:@selector(scale)])
10493 ScreenScale_ = [screen scale];
10497 UIDevice *device([UIDevice currentDevice]);
10498 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10499 Idiom_ = @"iphone";
10501 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10502 if (idiom == UIUserInterfaceIdiomPhone)
10503 Idiom_ = @"iphone";
10504 else if (idiom == UIUserInterfaceIdiomPad)
10507 NSLog(@"unknown UIUserInterfaceIdiom!");
10510 Pcre pattern("^([0-9]+\\.[0-9]+)");
10512 if (pattern([device systemVersion]))
10513 Firmware_ = pattern[1];
10514 if (pattern(Cydia_))
10515 Major_ = pattern[1];
10517 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10519 HostConfig_ = [[[NSObject alloc] init] autorelease];
10520 @synchronized (HostConfig_) {
10521 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10522 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10523 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10524 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10525 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10528 NSString *ui(@"ui/ios");
10530 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10531 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10532 UI_ = CydiaURL(ui);
10534 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10536 MobilizedFiles_ = [NSMutableSet setWithObjects:
10537 @"Library/Preferences/com.apple.Accessibility.plist",
10538 @"Library/Preferences/com.apple.preferences.sounds.plist",
10541 /* Library Hacks {{{ */
10542 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10544 $WAKWindow = objc_getClass("WAKWindow");
10545 if ($WAKWindow != NULL)
10546 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10547 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10549 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10551 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10552 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10553 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10554 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10557 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10558 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10559 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10560 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10563 $NSURLConnection = objc_getClass("NSURLConnection");
10564 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10565 if (NSURLConnection$init$ != NULL) {
10566 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10567 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10570 $NSUserDefaults = objc_getClass("NSUserDefaults");
10571 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10572 if (NSUserDefaults$objectForKey$ != NULL) {
10573 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10574 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10577 /* Set Locale {{{ */
10578 Locale_ = CFLocaleCopyCurrent();
10579 Languages_ = [NSLocale preferredLanguages];
10581 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10582 //NSLog(@"%@", [Languages_ description]);
10585 if (Locale_ != NULL)
10586 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10587 else if (Languages_ != nil && [Languages_ count] != 0)
10588 lang = [[Languages_ objectAtIndex:0] UTF8String];
10590 // XXX: consider just setting to C and then falling through?
10593 if (lang != NULL) {
10594 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10595 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10598 NSLog(@"Setting Language: %s", lang);
10600 if (lang != NULL) {
10601 setenv("LANG", lang, true);
10602 std::setlocale(LC_ALL, lang);
10606 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10608 /* Parse Arguments {{{ */
10609 bool substrate(false);
10615 for (int argi(1); argi != argc; ++argi)
10616 if (strcmp(argv[argi], "--") == 0) {
10618 argv[argi] = argv[0];
10624 for (int argi(1); argi != arge; ++argi)
10625 if (strcmp(args[argi], "--substrate") == 0)
10628 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10632 App_ = [[NSBundle mainBundle] bundlePath];
10638 if (access("/var/mobile/Library/Keyboard/UserDictionary.sqlite", F_OK) == 0)
10639 system("mkdir -p /var/root/Library/Keyboard; cp -af /var/mobile/Library/Keyboard/UserDictionary.sqlite /var/root/Library/Keyboard/");
10641 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/root"] retain];
10643 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10644 alloc_ = alloc->method_imp;
10645 alloc->method_imp = (IMP) &Alloc_;*/
10647 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10648 dealloc_ = dealloc->method_imp;
10649 dealloc->method_imp = (IMP) &Dealloc_;*/
10651 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10652 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10654 /* System Information {{{ */
10658 size = sizeof(maxproc);
10659 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10660 perror("sysctlbyname(\"kern.maxproc\", ?)");
10661 else if (maxproc < 64) {
10663 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10664 perror("sysctlbyname(\"kern.maxproc\", #)");
10667 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10668 char *osversion = new char[size];
10669 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10670 perror("sysctlbyname(\"kern.osversion\", ?)");
10672 System_ = [NSString stringWithUTF8String:osversion];
10674 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10675 char *machine = new char[size];
10676 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10677 perror("sysctlbyname(\"hw.machine\", ?)");
10679 Machine_ = machine;
10681 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10682 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10683 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10685 UniqueID_ = UniqueIdentifier(device);
10687 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10688 Product_ = [info objectForKey:@"SafariProductVersion"];
10689 Safari_ = [info objectForKey:@"CFBundleVersion"];
10692 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10694 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10695 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10696 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10697 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10698 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10699 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10701 UserAgent_ = agent;
10703 /* Load Database {{{ */
10705 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10707 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10709 if (Metadata_ == NULL)
10710 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10712 Settings_ = [Metadata_ objectForKey:@"Settings"];
10714 Packages_ = [Metadata_ objectForKey:@"Packages"];
10716 Values_ = [Metadata_ objectForKey:@"Values"];
10717 Sections_ = [Metadata_ objectForKey:@"Sections"];
10718 Sources_ = [Metadata_ objectForKey:@"Sources"];
10720 Token_ = [Metadata_ objectForKey:@"Token"];
10722 Version_ = [Metadata_ objectForKey:@"Version"];
10725 if (Settings_ != nil)
10726 Role_ = [Settings_ objectForKey:@"Role"];
10728 if (Values_ == nil) {
10729 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10730 [Metadata_ setObject:Values_ forKey:@"Values"];
10733 if (Sections_ == nil) {
10734 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10735 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10738 if (Sources_ == nil) {
10739 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10740 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10743 if (Version_ == nil) {
10744 Version_ = [NSNumber numberWithUnsignedInt:0];
10745 [Metadata_ setObject:Version_ forKey:@"Version"];
10748 if ([Version_ unsignedIntValue] == 0) {
10749 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10750 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10751 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10752 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10754 Version_ = [NSNumber numberWithUnsignedInt:1];
10755 [Metadata_ setObject:Version_ forKey:@"Version"];
10757 [Metadata_ removeObjectForKey:@"LastUpdate"];
10763 CydiaWriteSources();
10766 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10769 if (Packages_ != nil) {
10771 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10775 [Metadata_ removeObjectForKey:@"Packages"];
10781 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10783 #define MobileSubstrate_(name) \
10784 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10785 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10786 if (handle == NULL) \
10787 NSLog(@"%s", dlerror()); \
10790 MobileSubstrate_(Activator)
10791 MobileSubstrate_(libstatusbar)
10792 MobileSubstrate_(SimulatedKeyEvents)
10793 MobileSubstrate_(WinterBoard)
10795 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10796 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10798 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10800 if (access("/User", F_OK) != 0 || version != 6) {
10802 system("/usr/libexec/cydia/firmware.sh");
10806 _assert([[NSFileManager defaultManager]
10807 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10808 withIntermediateDirectories:YES
10813 if (access("/tmp/cydia.chk", F_OK) == 0) {
10814 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10815 _assert(errno == ENOENT);
10816 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10817 _assert(errno == ENOENT);
10820 /* APT Initialization {{{ */
10821 _assert(pkgInitConfig(*_config));
10822 _assert(pkgInitSystem(*_config, _system));
10825 _config->Set("APT::Acquire::Translation", lang);
10827 // XXX: this timeout might be important :(
10828 //_config->Set("Acquire::http::Timeout", 15);
10830 _config->Set("Acquire::http::MaxParallel", 3);
10832 /* Color Choices {{{ */
10833 space_ = CGColorSpaceCreateDeviceRGB();
10835 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10836 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10837 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10838 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10839 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10840 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10841 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10842 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10843 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10845 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10846 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10848 /* UIKit Configuration {{{ */
10849 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10850 if ($GSFontSetUseLegacyFontMetrics != NULL)
10851 $GSFontSetUseLegacyFontMetrics(YES);
10853 // XXX: I have a feeling this was important
10854 //UIKeyboardDisableAutomaticAppearance();
10857 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10859 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemHasCapability"));
10860 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10862 ShowPromoted_ = fast;
10863 PulseInterval_ = fast ? 50000 : 500000;
10865 Colon_ = UCLocalize("COLON_DELIMITED");
10866 Elision_ = UCLocalize("ELISION");
10867 Error_ = UCLocalize("ERROR");
10868 Warning_ = UCLocalize("WARNING");
10870 AprilFools_ = false;
10873 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10875 CGColorSpaceRelease(space_);
10876 CFRelease(Locale_);