1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "CyteKit/UCPlatform.h"
45 #include "CyteKit/Localize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <QuartzCore/CALayer.h>
71 #include <WebCore/WebCoreThread.h>
78 #include <ext/stdio_filebuf.h>
82 #include <apt-pkg/acquire.h>
83 #include <apt-pkg/acquire-item.h>
84 #include <apt-pkg/algorithms.h>
85 #include <apt-pkg/cachefile.h>
86 #include <apt-pkg/clean.h>
87 #include <apt-pkg/configuration.h>
88 #include <apt-pkg/debindexfile.h>
89 #include <apt-pkg/debmetaindex.h>
90 #include <apt-pkg/error.h>
91 #include <apt-pkg/init.h>
92 #include <apt-pkg/mmap.h>
93 #include <apt-pkg/pkgrecords.h>
94 #include <apt-pkg/sha1.h>
95 #include <apt-pkg/sourcelist.h>
96 #include <apt-pkg/sptr.h>
97 #include <apt-pkg/strutl.h>
98 #include <apt-pkg/tagfile.h>
100 #include <apr-1/apr_pools.h>
102 #include <sys/types.h>
103 #include <sys/stat.h>
104 #include <sys/sysctl.h>
105 #include <sys/param.h>
106 #include <sys/mount.h>
107 #include <sys/reboot.h>
114 #include <mach-o/nlist.h>
123 #include <Cytore.hpp>
126 #include <CydiaSubstrate/CydiaSubstrate.h>
127 #include "Menes/Menes.h"
129 #include "CyteKit/IndirectDelegate.h"
130 #include "CyteKit/PerlCompatibleRegEx.hpp"
131 #include "CyteKit/TableViewCell.h"
132 #include "CyteKit/WebScriptObject-Cyte.h"
133 #include "CyteKit/WebViewController.h"
134 #include "CyteKit/WebViewTableViewCell.h"
135 #include "CyteKit/stringWithUTF8Bytes.h"
137 #include "Cydia/MIMEAddress.h"
138 #include "Cydia/LoadingViewController.h"
139 #include "Cydia/ProgressEvent.h"
141 #include "SDURLCache/SDURLCache.h"
148 #define _timestamp ({ \
150 gettimeofday(&tv, NULL); \
151 tv.tv_sec * 1000000 + tv.tv_usec; \
154 typedef std::vector<class ProfileTime *> TimeList;
164 ProfileTime(const char *name) :
168 times_.push_back(this);
171 void AddTime(uint64_t time) {
178 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
190 ProfileTimer(ProfileTime &time) :
197 time_.AddTime(_timestamp - start_);
202 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
204 std::cerr << "========" << std::endl;
207 #define _profile(name) { \
208 static ProfileTime name(#name); \
209 ProfileTimer _ ## name(name);
214 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
215 #define synchronized(lock) \
216 synchronized(static_cast<NSObject *>(lock))
218 extern NSString *Cydia_;
220 #define lprintf(args...) fprintf(stderr, args)
223 #define TraceLogging (1 && !ForRelease)
224 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
225 #define ProfileTimes (0 && !ForRelease)
226 #define ForSaurik (0 && !ForRelease)
227 #define LogBrowser (0 && !ForRelease)
228 #define TrackResize (0 && !ForRelease)
229 #define ManualRefresh (1 && !ForRelease)
230 #define ShowInternals (0 && !ForRelease)
231 #define AlwaysReload (0 && !ForRelease)
232 #define TryIndexedCollation (0 && !ForRelease)
236 #define _trace(args...)
241 #define _profile(name) {
244 #define PrintTimes() do {} while (false)
247 // Hash Functions/Structures {{{
248 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
256 static bool ShowPromoted_;
258 static NSString *Colon_;
260 static NSString *Error_;
261 static NSString *Warning_;
263 static bool AprilFools_;
265 static bool IsReachable(const char *name) {
266 SCNetworkReachabilityFlags flags; {
267 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
268 SCNetworkReachabilityGetFlags(reachability, &flags);
269 CFRelease(reachability);
272 // XXX: this elaborate mess is what Apple is using to determine this? :(
273 // XXX: do we care if the user has to intervene? maybe that's ok?
275 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
276 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
277 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
278 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
279 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
280 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
285 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
287 static _finline NSString *CydiaURL(NSString *path) {
289 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
290 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
291 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
292 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
293 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
295 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
298 static void ReapZombie(pid_t pid) {
301 if (waitpid(pid, &status, 0) == -1)
307 static _finline void UpdateExternalStatus(uint64_t newStatus) {
309 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
310 notify_set_state(notify_token, newStatus);
311 notify_cancel(notify_token);
313 notify_post("com.saurik.Cydia.status");
316 static CGFloat CYStatusBarHeight() {
317 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
318 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
321 /* NSForcedOrderingSearch doesn't work on the iPhone */
322 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
323 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
324 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
326 /* Insertion Sort {{{ */
328 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
329 const char *ptr = (const char *)list;
331 CFIndex half = count / 2;
332 const char *probe = ptr + elementSize * half;
333 CFComparisonResult cr = comparator(element, probe, context);
334 if (0 == cr) return (probe - (const char *)list) / elementSize;
335 ptr = (cr < 0) ? ptr : probe + elementSize;
336 count = (cr < 0) ? half : (half + (count & 1) - 1);
338 return (ptr - (const char *)list) / elementSize;
341 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
342 const char *ptr = (const char *)list;
344 CFIndex half = count / 2;
345 const char *probe = ptr + elementSize * half;
346 CFComparisonResult cr = comparator(element, probe, context);
347 if (0 == cr) return (probe - (const char *)list) / elementSize;
348 ptr = (cr < 0) ? ptr : probe + elementSize;
349 count = (cr < 0) ? half : (half + (count & 1) - 1);
351 return (ptr - (const char *)list) / elementSize;
354 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
355 if (range.length == 0)
357 const void **values(new const void *[range.length]);
358 CFArrayGetValues(array, range, values);
360 #if HistogramInsertionSort > 0
361 uint32_t total(0), *offsets(new uint32_t[range.length]);
364 for (CFIndex index(1); index != range.length; ++index) {
365 const void *value(values[index]);
366 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
367 CFIndex correct(index);
368 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
369 #if HistogramInsertionSort > 1
370 NSLog(@"%@ < %@", value, values[correct - 1]);
375 if (correct != index) {
376 size_t offset(index - correct);
377 #if HistogramInsertionSort
381 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
383 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
384 values[correct] = value;
388 CFArrayReplaceValues(array, range, values, range.length);
391 #if HistogramInsertionSort > 0
392 for (CFIndex index(0); index != range.length; ++index)
393 if (offsets[index] != 0)
394 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
395 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
402 /* Apple Bug Fixes {{{ */
403 @implementation UIWebDocumentView (Cydia)
405 - (void) _setScrollerOffset:(CGPoint)offset {
406 UIScroller *scroller([self _scroller]);
408 CGSize size([scroller contentSize]);
409 CGSize bounds([scroller bounds].size);
412 max.x = size.width - bounds.width;
413 max.y = size.height - bounds.height;
421 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
422 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
424 [scroller setOffset:offset];
430 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
431 size_t length([self length] - state->state);
434 else if (length > count)
436 for (size_t i(0); i != length; ++i)
437 objects[i] = [self item:state->state++];
438 state->itemsPtr = objects;
439 state->mutationsPtr = (unsigned long *) self;
443 /* Cydia NSString Additions {{{ */
444 @interface NSString (Cydia)
445 - (NSComparisonResult) compareByPath:(NSString *)other;
446 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
449 @implementation NSString (Cydia)
451 - (NSComparisonResult) compareByPath:(NSString *)other {
452 NSString *prefix = [self commonPrefixWithString:other options:0];
453 size_t length = [prefix length];
455 NSRange lrange = NSMakeRange(length, [self length] - length);
456 NSRange rrange = NSMakeRange(length, [other length] - length);
458 lrange = [self rangeOfString:@"/" options:0 range:lrange];
459 rrange = [other rangeOfString:@"/" options:0 range:rrange];
461 NSComparisonResult value;
463 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
464 value = NSOrderedSame;
465 else if (lrange.location == NSNotFound)
466 value = NSOrderedAscending;
467 else if (rrange.location == NSNotFound)
468 value = NSOrderedDescending;
470 value = NSOrderedSame;
472 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
473 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
474 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
475 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
477 NSComparisonResult result = [lpath compare:rpath];
478 return result == NSOrderedSame ? value : result;
481 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
482 return [(id)CFURLCreateStringByAddingPercentEscapes(
487 kCFStringEncodingUTF8
494 /* C++ NSString Wrapper Cache {{{ */
495 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
496 return size == 0 ? NULL :
497 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
498 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
501 static _finline CFStringRef CYStringCreate(const char *data) {
502 return CYStringCreate(data, strlen(data));
511 _finline void clear_() {
512 if (cache_ != NULL) {
519 _finline bool empty() const {
523 _finline size_t size() const {
527 _finline char *data() const {
531 _finline void clear() {
536 _finline CYString() :
543 _finline ~CYString() {
547 void operator =(const CYString &rhs) {
551 if (rhs.cache_ == nil)
554 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
557 void copy(apr_pool_t *pool) {
558 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
559 memcpy(temp, data_, size_);
564 void set(apr_pool_t *pool, const char *data, size_t size) {
570 data_ = const_cast<char *>(data);
578 _finline void set(apr_pool_t *pool, const char *data) {
579 set(pool, data, data == NULL ? 0 : strlen(data));
582 _finline void set(apr_pool_t *pool, const std::string &rhs) {
583 set(pool, rhs.data(), rhs.size());
586 bool operator ==(const CYString &rhs) const {
587 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
590 _finline operator CFStringRef() {
592 cache_ = CYStringCreate(data_, size_);
596 _finline operator id() {
597 return (NSString *) static_cast<CFStringRef>(*this);
600 _finline operator const char *() {
601 return reinterpret_cast<const char *>(data_);
605 /* C++ NSString Algorithm Adapters {{{ */
607 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
610 struct NSStringMapHash :
611 std::unary_function<NSString *, size_t>
613 _finline size_t operator ()(NSString *value) const {
614 return CFStringHashNSString((CFStringRef) value);
618 struct NSStringMapLess :
619 std::binary_function<NSString *, NSString *, bool>
621 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
622 return [lhs compare:rhs] == NSOrderedAscending;
626 struct NSStringMapEqual :
627 std::binary_function<NSString *, NSString *, bool>
629 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
630 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
631 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
632 //[lhs isEqualToString:rhs];
637 /* CoreGraphics Primitives {{{ */
642 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
643 CGFloat color[] = {red, green, blue, alpha};
644 return CGColorCreate(space, color);
653 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
654 color_(Create_(space, red, green, blue, alpha))
656 Set(space, red, green, blue, alpha);
661 CGColorRelease(color_);
668 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
670 color_ = Create_(space, red, green, blue, alpha);
673 operator CGColorRef() {
679 /* Random Global Variables {{{ */
680 static int PulseInterval_ = 500000;
682 static const NSString *UI_;
685 static bool RestartSubstrate_;
686 static NSArray *Finishes_;
688 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
689 #define NotifyConfig_ "/etc/notify.conf"
691 static bool Queuing_;
693 static CYColor Blue_;
694 static CYColor Blueish_;
695 static CYColor Black_;
697 static CYColor White_;
698 static CYColor Gray_;
699 static CYColor Green_;
700 static CYColor Purple_;
701 static CYColor Purplish_;
703 static UIColor *InstallingColor_;
704 static UIColor *RemovingColor_;
706 static NSString *App_;
708 static BOOL Advanced_;
709 static BOOL Ignored_;
711 static _H<UIFont> Font12_;
712 static _H<UIFont> Font12Bold_;
713 static _H<UIFont> Font14_;
714 static _H<UIFont> Font18Bold_;
715 static _H<UIFont> Font22Bold_;
717 static const char *Machine_ = NULL;
718 static _H<NSString> System_;
719 static NSString *SerialNumber_ = nil;
720 static NSString *ChipID_ = nil;
721 static NSString *BBSNum_ = nil;
722 static _H<NSString> Token_;
723 static NSString *UniqueID_ = nil;
724 static _H<NSString> UserAgent_;
725 static _H<NSString> Product_;
726 static _H<NSString> Safari_;
728 static CFLocaleRef Locale_;
729 static NSArray *Languages_;
730 static CGColorSpaceRef space_;
732 static NSDictionary *SectionMap_;
733 static NSMutableDictionary *Metadata_;
734 static _transient NSMutableDictionary *Settings_;
735 static _transient NSString *Role_;
736 static _transient NSMutableDictionary *Packages_;
737 static _transient NSMutableDictionary *Values_;
738 static _transient NSMutableDictionary *Sections_;
739 _H<NSMutableDictionary> Sources_;
740 static _transient NSNumber *Version_;
745 static CGFloat ScreenScale_;
746 static NSString *Idiom_;
747 static _H<NSString> Firmware_;
748 static NSString *Major_;
750 static _H<NSMutableDictionary> SessionData_;
751 static _H<NSObject> HostConfig_;
752 static _H<NSMutableSet> BridgedHosts_;
753 static _H<NSMutableSet> TokenHosts_;
754 static _H<NSMutableSet> InsecureHosts_;
755 static _H<NSMutableSet> PipelinedHosts_;
756 static _H<NSMutableSet> CachedURLs_;
758 static NSString *kCydiaProgressEventTypeError = @"Error";
759 static NSString *kCydiaProgressEventTypeInformation = @"Information";
760 static NSString *kCydiaProgressEventTypeStatus = @"Status";
761 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
764 /* Display Helpers {{{ */
765 inline float Interpolate(float begin, float end, float fraction) {
766 return (end - begin) * fraction + begin;
769 static _finline const char *StripVersion_(const char *version) {
770 const char *colon(strchr(version, ':'));
771 return colon == NULL ? version : colon + 1;
774 NSString *LocalizeSection(NSString *section) {
775 static Pcre title_r("^(.*?) \\((.*)\\)$");
776 if (title_r(section)) {
777 NSString *parent(title_r[1]);
778 NSString *child(title_r[2]);
780 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
781 LocalizeSection(parent),
782 LocalizeSection(child)
786 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
789 NSString *Simplify(NSString *title) {
790 const char *data = [title UTF8String];
791 size_t size = [title length];
793 static Pcre square_r("^\\[(.*)\\]$");
794 if (square_r(data, size))
795 return Simplify(square_r[1]);
797 static Pcre paren_r("^\\((.*)\\)$");
798 if (paren_r(data, size))
799 return Simplify(paren_r[1]);
801 static Pcre title_r("^(.*?) \\((.*)\\)$");
802 if (title_r(data, size))
803 return Simplify(title_r[1]);
809 NSString *GetLastUpdate() {
810 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
813 return UCLocalize("NEVER_OR_UNKNOWN");
815 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
816 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
818 CFRelease(formatter);
820 return [(NSString *) formatted autorelease];
823 bool isSectionVisible(NSString *section) {
824 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
825 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
826 return hidden == nil || ![hidden boolValue];
829 static NSObject *CYIOGetValue(const char *path, NSString *property) {
830 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
831 if (entry == MACH_PORT_NULL)
834 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
835 IOObjectRelease(entry);
839 return [(id) value autorelease];
842 static NSString *CYHex(NSData *data, bool reverse = false) {
846 size_t length([data length]);
847 uint8_t bytes[length];
848 [data getBytes:bytes];
850 char string[length * 2 + 1];
851 for (size_t i(0); i != length; ++i)
852 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
854 return [NSString stringWithUTF8String:string];
859 /* Delegate Prototypes {{{ */
862 @class CydiaProgressEvent;
864 @protocol DatabaseDelegate
865 - (void) repairWithSelector:(SEL)selector;
866 - (void) setConfigurationData:(NSString *)data;
867 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
870 @class CYPackageController;
872 @protocol CydiaDelegate
873 - (void) returnToCydia;
875 - (void) retainNetworkActivityIndicator;
876 - (void) releaseNetworkActivityIndicator;
877 - (void) clearPackage:(Package *)package;
878 - (void) installPackage:(Package *)package;
879 - (void) installPackages:(NSArray *)packages;
880 - (void) removePackage:(Package *)package;
881 - (void) beginUpdate;
883 - (void) distUpgrade;
886 - (void) _saveConfig;
888 - (void) addSource:(NSDictionary *)source;
889 - (void) addTrivialSource:(NSString *)href;
890 - (void) showSettings;
891 - (UIProgressHUD *) addProgressHUD;
892 - (void) removeProgressHUD:(UIProgressHUD *)hud;
893 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
894 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
898 /* Status Delegation {{{ */
900 public pkgAcquireStatus
903 _transient NSObject<ProgressDelegate> *delegate_;
913 void setDelegate(NSObject<ProgressDelegate> *delegate) {
914 delegate_ = delegate;
917 NSObject<ProgressDelegate> *getDelegate() const {
921 virtual bool MediaChange(std::string media, std::string drive) {
925 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
929 virtual void Fetch(pkgAcquire::ItemDesc &item) {
930 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
931 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
932 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
935 virtual void Done(pkgAcquire::ItemDesc &item) {
936 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
937 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
938 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
941 virtual void Fail(pkgAcquire::ItemDesc &item) {
943 item.Owner->Status == pkgAcquire::Item::StatIdle ||
944 item.Owner->Status == pkgAcquire::Item::StatDone
948 std::string &error(item.Owner->ErrorText);
952 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
953 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
956 virtual bool Pulse(pkgAcquire *Owner) {
957 bool value = pkgAcquireStatus::Pulse(Owner);
960 double(CurrentBytes + CurrentItems) /
961 double(TotalBytes + TotalItems)
964 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
965 [NSNumber numberWithDouble:percent], @"Percent",
967 [NSNumber numberWithDouble:CurrentBytes], @"Current",
968 [NSNumber numberWithDouble:TotalBytes], @"Total",
969 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
970 nil] waitUntilDone:YES];
972 if (value && ![delegate_ isProgressCancelled])
980 _finline bool WasCancelled() const {
984 virtual void Start() {
985 pkgAcquireStatus::Start();
986 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
989 virtual void Stop() {
990 pkgAcquireStatus::Stop();
991 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
992 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
996 /* Database Interface {{{ */
997 typedef std::map< unsigned long, _H<Source> > SourceMap;
999 @interface Database : NSObject {
1005 pkgCacheFile cache_;
1006 pkgDepCache::Policy *policy_;
1007 pkgRecords *records_;
1008 pkgProblemResolver *resolver_;
1009 pkgAcquire *fetcher_;
1011 SPtr<pkgPackageManager> manager_;
1012 pkgSourceList *list_;
1014 SourceMap sourceMap_;
1015 _H<NSMutableArray> sourceList_;
1017 CFMutableArrayRef packages_;
1019 _transient NSObject<DatabaseDelegate> *delegate_;
1020 _transient NSObject<ProgressDelegate> *progress_;
1028 std::map<const char *, _H<NSString> > sections_;
1031 + (Database *) sharedInstance;
1034 - (void) _readCydia:(NSNumber *)fd;
1035 - (void) _readStatus:(NSNumber *)fd;
1036 - (void) _readOutput:(NSNumber *)fd;
1040 - (Package *) packageWithName:(NSString *)name;
1042 - (pkgCacheFile &) cache;
1043 - (pkgDepCache::Policy *) policy;
1044 - (pkgRecords *) records;
1045 - (pkgProblemResolver *) resolver;
1046 - (pkgAcquire &) fetcher;
1047 - (pkgSourceList &) list;
1048 - (NSArray *) packages;
1049 - (NSArray *) sources;
1050 - (Source *) sourceWithKey:(NSString *)key;
1051 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1059 - (void) updateWithStatus:(Status &)status;
1061 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1063 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1064 - (NSObject<ProgressDelegate> *) progressDelegate;
1066 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1068 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1072 /* ProgressEvent Implementation {{{ */
1073 @implementation CydiaProgressEvent
1075 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1076 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1079 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1080 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1081 [event setPackage:package];
1085 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1086 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1088 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1089 NSArray *fields([description componentsSeparatedByString:@" "]);
1090 [event setItem:fields];
1092 if ([fields count] > 3) {
1093 [event setPackage:[fields objectAtIndex:2]];
1094 [event setVersion:[fields objectAtIndex:3]];
1097 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1102 + (NSArray *) _attributeKeys {
1103 return [NSArray arrayWithObjects:
1113 - (NSArray *) attributeKeys {
1114 return [[self class] _attributeKeys];
1117 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1118 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1121 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1122 if ((self = [super init]) != nil) {
1128 - (NSString *) message {
1132 - (NSString *) type {
1136 - (NSArray *) item {
1137 return (id) item_ ?: [NSNull null];
1140 - (void) setItem:(NSArray *)item {
1144 - (NSString *) package {
1145 return (id) package_ ?: [NSNull null];
1148 - (void) setPackage:(NSString *)package {
1152 - (NSString *) url {
1153 return (id) url_ ?: [NSNull null];
1156 - (void) setURL:(NSString *)url {
1160 - (void) setVersion:(NSString *)version {
1164 - (NSString *) version {
1165 return (id) version_ ?: [NSNull null];
1168 - (NSString *) compound:(NSString *)value {
1170 NSString *mode(nil); {
1171 NSString *type([self type]);
1172 if ([type isEqualToString:kCydiaProgressEventTypeError])
1173 mode = UCLocalize("ERROR");
1174 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1175 mode = UCLocalize("WARNING");
1179 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1185 - (NSString *) compoundMessage {
1186 return [self compound:[self message]];
1189 - (NSString *) compoundTitle {
1192 if (package_ == nil)
1194 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1195 title = [package name];
1199 return [self compound:title];
1205 // Cytore Definitions {{{
1206 struct PackageValue :
1209 Cytore::Offset<PackageValue> next_;
1211 uint32_t index_ : 23;
1212 uint32_t subscribed_ : 1;
1229 Cytore::Offset<PackageValue> packages_[1 << 16];
1232 static Cytore::File<MetaValue> MetaFile_;
1234 // Cytore Helper Functions {{{
1235 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1236 SplitHash nhash = { hashlittle(name, length) };
1238 PackageValue *metadata;
1240 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1241 offset: if (offset->IsNull()) {
1242 *offset = MetaFile_.New<PackageValue>(length + 1);
1243 metadata = &MetaFile_.Get(*offset);
1245 if (metadata == NULL) {
1249 metadata = new PackageValue();
1250 memset(metadata, 0, sizeof(*metadata));
1253 memcpy(metadata->name_, name, length + 1);
1254 metadata->nhash_ = nhash.u16[1];
1256 metadata = &MetaFile_.Get(*offset);
1258 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1259 offset = &metadata->next_;
1267 static void PackageImport(const void *key, const void *value, void *context) {
1268 bool &fail(*reinterpret_cast<bool *>(context));
1271 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1272 NSLog(@"failed to import package %@", key);
1276 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1277 NSDictionary *package((NSDictionary *) value);
1279 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1280 if ([subscribed boolValue] && !metadata->subscribed_)
1281 metadata->subscribed_ = true;
1283 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1284 time_t time([date timeIntervalSince1970]);
1285 if (metadata->first_ > time || metadata->first_ == 0)
1286 metadata->first_ = time;
1289 NSDate *date([package objectForKey:@"LastSeen"]);
1290 NSString *version([package objectForKey:@"LastVersion"]);
1292 if (date != nil && version != nil) {
1293 time_t time([date timeIntervalSince1970]);
1294 if (metadata->last_ < time || metadata->last_ == 0)
1295 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1296 size_t length(strlen(buffer));
1297 uint16_t vhash(hashlittle(buffer, length));
1299 size_t capped(std::min<size_t>(8, length));
1300 char *latest(buffer + length - capped);
1302 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1303 metadata->vhash_ = vhash;
1305 metadata->last_ = time;
1311 /* Source Class {{{ */
1312 @interface Source : NSObject {
1314 Database *database_;
1317 CYString depiction_;
1318 CYString description_;
1324 CYString distribution_;
1330 _H<NSString> authority_;
1332 CYString defaultIcon_;
1334 _H<NSMutableDictionary> record_;
1338 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1340 - (NSComparisonResult) compareByName:(Source *)source;
1342 - (NSString *) depictionForPackage:(NSString *)package;
1343 - (NSString *) supportForPackage:(NSString *)package;
1345 - (metaIndex *) metaIndex;
1346 - (NSDictionary *) record;
1349 - (NSString *) rooturi;
1350 - (NSString *) distribution;
1351 - (NSString *) type;
1354 - (NSString *) host;
1356 - (NSString *) name;
1357 - (NSString *) shortDescription;
1358 - (NSString *) label;
1359 - (NSString *) origin;
1360 - (NSString *) version;
1362 - (NSString *) defaultIcon;
1363 - (NSURL *) iconURL;
1367 @implementation Source
1371 distribution_.clear();
1376 description_.clear();
1382 defaultIcon_.clear();
1389 + (NSString *) webScriptNameForSelector:(SEL)selector {
1391 else if (selector == @selector(addSection:))
1392 return @"addSection";
1393 else if (selector == @selector(getField:))
1395 else if (selector == @selector(removeSection:))
1396 return @"removeSection";
1397 else if (selector == @selector(remove))
1403 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1404 return [self webScriptNameForSelector:selector] == nil;
1407 + (NSArray *) _attributeKeys {
1408 return [NSArray arrayWithObjects:
1419 @"shortDescription",
1426 - (NSArray *) attributeKeys {
1427 return [[self class] _attributeKeys];
1430 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1431 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1434 - (metaIndex *) metaIndex {
1438 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1441 trusted_ = index->IsTrusted();
1443 uri_.set(pool, index->GetURI());
1444 distribution_.set(pool, index->GetDist());
1445 type_.set(pool, index->GetType());
1447 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1448 if (dindex != NULL) {
1449 base_.set(pool, dindex->MetaIndexURI(""));
1452 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1455 pkgTagFile tags(&fd);
1457 pkgTagSection section;
1464 {"default-icon", &defaultIcon_},
1465 {"depiction", &depiction_},
1466 {"description", &description_},
1468 {"origin", &origin_},
1469 {"support", &support_},
1470 {"version", &version_},
1473 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1474 const char *start, *end;
1476 if (section.Find(names[i].name_, start, end)) {
1477 CYString &value(*names[i].value_);
1478 value.set(pool, start, end - start);
1484 record_ = [Sources_ objectForKey:[self key]];
1486 NSURL *url([NSURL URLWithString:uri_]);
1490 host_ = [host_ lowercaseString];
1495 authority_ = [url path];
1498 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1499 if ((self = [super init]) != nil) {
1500 era_ = [database era];
1501 database_ = database;
1504 [self setMetaIndex:index inPool:pool];
1508 - (NSString *) getField:(NSString *)name {
1509 @synchronized (database_) {
1510 if ([database_ era] != era_ || index_ == NULL)
1513 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1518 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1523 pkgTagFile tags(&fd);
1525 pkgTagSection section;
1528 const char *start, *end;
1529 if (!section.Find([name UTF8String], start, end))
1530 return (NSString *) [NSNull null];
1532 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1535 - (NSComparisonResult) compareByName:(Source *)source {
1536 NSString *lhs = [self name];
1537 NSString *rhs = [source name];
1539 if ([lhs length] != 0 && [rhs length] != 0) {
1540 unichar lhc = [lhs characterAtIndex:0];
1541 unichar rhc = [rhs characterAtIndex:0];
1543 if (isalpha(lhc) && !isalpha(rhc))
1544 return NSOrderedAscending;
1545 else if (!isalpha(lhc) && isalpha(rhc))
1546 return NSOrderedDescending;
1549 return [lhs compare:rhs options:LaxCompareOptions_];
1552 - (NSString *) depictionForPackage:(NSString *)package {
1553 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1556 - (NSString *) supportForPackage:(NSString *)package {
1557 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1560 - (NSArray *) sections {
1561 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1564 - (void) _addSection:(NSString *)section {
1567 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1568 if (![sections containsObject:section]) {
1569 [sections addObject:section];
1573 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1578 - (bool) addSection:(NSString *)section {
1582 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1586 - (void) _removeSection:(NSString *)section {
1590 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1591 if ([sections containsObject:section]) {
1592 [sections removeObject:section];
1597 - (bool) removeSection:(NSString *)section {
1601 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1606 [Sources_ removeObjectForKey:[self key]];
1611 bool value(record_ != nil);
1612 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1616 - (NSDictionary *) record {
1624 - (NSString *) rooturi {
1628 - (NSString *) distribution {
1629 return distribution_;
1632 - (NSString *) type {
1636 - (NSString *) baseuri {
1637 return base_.empty() ? nil : (id) base_;
1640 - (NSString *) iconuri {
1641 if (NSString *base = [self baseuri])
1642 return [base stringByAppendingString:@"CydiaIcon.png"];
1647 - (NSURL *) iconURL {
1648 if (NSString *uri = [self iconuri])
1649 return [NSURL URLWithString:uri];
1653 - (NSString *) key {
1654 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1657 - (NSString *) host {
1661 - (NSString *) name {
1662 return origin_.empty() ? (id) authority_ : origin_;
1665 - (NSString *) shortDescription {
1666 return description_;
1669 - (NSString *) label {
1670 return label_.empty() ? (id) authority_ : label_;
1673 - (NSString *) origin {
1677 - (NSString *) version {
1681 - (NSString *) defaultIcon {
1682 return defaultIcon_;
1687 /* CydiaOperation Class {{{ */
1688 @interface CydiaOperation : NSObject {
1689 _H<NSString> operator_;
1690 _H<NSString> value_;
1693 - (NSString *) operator;
1694 - (NSString *) value;
1698 @implementation CydiaOperation
1700 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1701 if ((self = [super init]) != nil) {
1702 operator_ = [NSString stringWithUTF8String:_operator];
1703 value_ = [NSString stringWithUTF8String:value];
1707 + (NSArray *) _attributeKeys {
1708 return [NSArray arrayWithObjects:
1714 - (NSArray *) attributeKeys {
1715 return [[self class] _attributeKeys];
1718 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1719 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1722 - (NSString *) operator {
1726 - (NSString *) value {
1732 /* CydiaClause Class {{{ */
1733 @interface CydiaClause : NSObject {
1734 _H<NSString> package_;
1735 _H<CydiaOperation> version_;
1738 - (NSString *) package;
1739 - (CydiaOperation *) version;
1743 @implementation CydiaClause
1745 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1746 if ((self = [super init]) != nil) {
1747 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1749 if (const char *version = dep.TargetVer())
1750 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1752 version_ = (id) [NSNull null];
1756 + (NSArray *) _attributeKeys {
1757 return [NSArray arrayWithObjects:
1763 - (NSArray *) attributeKeys {
1764 return [[self class] _attributeKeys];
1767 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1768 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1771 - (NSString *) package {
1775 - (CydiaOperation *) version {
1781 /* CydiaRelation Class {{{ */
1782 @interface CydiaRelation : NSObject {
1783 _H<NSString> relationship_;
1784 _H<NSMutableArray> clauses_;
1787 - (NSString *) relationship;
1788 - (NSArray *) clauses;
1792 @implementation CydiaRelation
1794 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1795 if ((self = [super init]) != nil) {
1796 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1797 clauses_ = [NSMutableArray arrayWithCapacity:8];
1799 pkgCache::DepIterator start;
1800 pkgCache::DepIterator end;
1801 dep.GlobOr(start, end); // ++dep
1804 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1806 // yes, seriously. (wtf?)
1814 + (NSArray *) _attributeKeys {
1815 return [NSArray arrayWithObjects:
1821 - (NSArray *) attributeKeys {
1822 return [[self class] _attributeKeys];
1825 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1826 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1829 - (NSString *) relationship {
1830 return relationship_;
1833 - (NSArray *) clauses {
1837 - (void) addClause:(CydiaClause *)clause {
1838 [clauses_ addObject:clause];
1843 /* Package Class {{{ */
1844 struct ParsedPackage {
1848 CYString architecture_;
1851 CYString depiction_;
1861 @interface Package : NSObject {
1864 uint32_t essential_ : 1;
1865 uint32_t obsolete_ : 1;
1866 uint32_t ignored_ : 1;
1867 uint32_t pooled_ : 1;
1873 _transient Database *database_;
1875 pkgCache::VerIterator version_;
1876 pkgCache::PkgIterator iterator_;
1877 pkgCache::VerFileIterator file_;
1883 CYString installed_;
1885 const char *section_;
1886 _transient NSString *section$_;
1890 PackageValue *metadata_;
1891 ParsedPackage *parsed_;
1893 _H<NSMutableArray> tags_;
1896 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1897 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1899 - (pkgCache::PkgIterator) iterator;
1902 - (NSString *) section;
1903 - (NSString *) simpleSection;
1905 - (NSString *) longSection;
1906 - (NSString *) shortSection;
1910 - (MIMEAddress *) maintainer;
1912 - (NSString *) longDescription;
1913 - (NSString *) shortDescription;
1916 - (PackageValue *) metadata;
1919 - (bool) subscribed;
1920 - (bool) setSubscribed:(bool)subscribed;
1924 - (NSString *) latest;
1925 - (NSString *) installed;
1926 - (BOOL) uninstalled;
1929 - (BOOL) upgradableAndEssential:(BOOL)essential;
1932 - (BOOL) unfiltered;
1936 - (BOOL) halfConfigured;
1937 - (BOOL) halfInstalled;
1939 - (NSString *) mode;
1942 - (NSString *) name;
1944 - (NSString *) homepage;
1945 - (NSString *) depiction;
1946 - (MIMEAddress *) author;
1948 - (NSString *) support;
1950 - (NSArray *) files;
1951 - (NSArray *) warnings;
1952 - (NSArray *) applications;
1954 - (Source *) source;
1957 - (BOOL) matches:(NSArray *)query;
1959 - (bool) hasSupportingRole;
1960 - (BOOL) hasTag:(NSString *)tag;
1961 - (NSString *) primaryPurpose;
1962 - (NSArray *) purposes;
1963 - (bool) isCommercial;
1965 - (void) setIndex:(size_t)index;
1967 - (CYString &) cyname;
1969 - (uint32_t) compareBySection:(NSArray *)sections;
1974 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1975 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1976 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1977 - (bool) isVisibleInSection:(NSString *)section;
1978 - (bool) isVisibleInSource:(Source *)source;
1982 uint32_t PackageChangesRadix(Package *self, void *) {
1987 uint32_t timestamp : 30;
1988 uint32_t ignored : 1;
1989 uint32_t upgradable : 1;
1993 bool upgradable([self upgradableAndEssential:YES]);
1994 value.bits.upgradable = upgradable ? 1 : 0;
1997 value.bits.timestamp = 0;
1998 value.bits.ignored = [self ignored] ? 0 : 1;
1999 value.bits.upgradable = 1;
2001 value.bits.timestamp = [self seen] >> 2;
2002 value.bits.ignored = 0;
2003 value.bits.upgradable = 0;
2006 return _not(uint32_t) - value.key;
2009 uint32_t PackagePrefixRadix(Package *self, void *context) {
2010 size_t offset(reinterpret_cast<size_t>(context));
2011 CYString &name([self cyname]);
2013 size_t size(name.size());
2016 char *text(name.data());
2019 if (!isdigit(text[0]))
2023 while (size != digits && isdigit(text[digits]))
2031 if (offset == 0 && zeros != 0) {
2032 memset(data, '0', zeros);
2033 memcpy(data + zeros, text, 4 - zeros);
2035 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2036 if (size <= offset - zeros)
2039 text += offset - zeros;
2040 size -= offset - zeros;
2043 memcpy(data, text, 4);
2045 memcpy(data, text, size);
2046 memset(data + size, 0, 4 - size);
2049 for (size_t i(0); i != 4; ++i)
2050 if (isalpha(data[i]))
2058 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2060 /* XXX: ntohl may be more honest */
2061 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2064 CYString &(*PackageName)(Package *self, SEL sel);
2066 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2067 _profile(PackageNameCompare)
2068 CYString &lhi(PackageName(lhs, @selector(cyname)));
2069 CYString &rhi(PackageName(rhs, @selector(cyname)));
2070 CFStringRef lhn(lhi), rhn(rhi);
2073 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2074 else if (rhn == NULL)
2075 return NSOrderedDescending;
2077 _profile(PackageNameCompare$NumbersLast)
2078 if (!lhi.empty() && !rhi.empty()) {
2079 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2080 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2081 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2082 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2083 return lha ? NSOrderedAscending : NSOrderedDescending;
2087 CFIndex length = CFStringGetLength(lhn);
2089 _profile(PackageNameCompare$Compare)
2090 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2095 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2096 return PackageNameCompare(*lhs, *rhs, context);
2099 struct PackageNameOrdering :
2100 std::binary_function<Package *, Package *, bool>
2102 _finline bool operator ()(Package *lhs, Package *rhs) const {
2103 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2107 @implementation Package
2109 - (NSString *) description {
2110 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2115 apr_pool_destroy(pool_);
2116 if (parsed_ != NULL)
2121 + (NSString *) webScriptNameForSelector:(SEL)selector {
2123 else if (selector == @selector(clear))
2125 else if (selector == @selector(getField:))
2127 else if (selector == @selector(hasTag:))
2129 else if (selector == @selector(install))
2131 else if (selector == @selector(remove))
2137 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2138 return [self webScriptNameForSelector:selector] == nil;
2141 + (NSArray *) _attributeKeys {
2142 return [NSArray arrayWithObjects:
2163 @"shortDescription",
2176 - (NSArray *) attributeKeys {
2177 return [[self class] _attributeKeys];
2180 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2181 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2184 - (NSArray *) relations {
2185 @synchronized (database_) {
2186 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2187 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2188 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2192 - (NSString *) architecture {
2194 @synchronized (database_) {
2195 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2198 - (NSString *) getField:(NSString *)name {
2199 @synchronized (database_) {
2200 if ([database_ era] != era_ || file_.end())
2203 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2205 const char *start, *end;
2206 if (!parser.Find([name UTF8String], start, end))
2207 return (NSString *) [NSNull null];
2209 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2213 if (parsed_ != NULL)
2215 @synchronized (database_) {
2216 if ([database_ era] != era_ || file_.end())
2219 ParsedPackage *parsed(new ParsedPackage);
2222 _profile(Package$parse)
2223 pkgRecords::Parser *parser;
2225 _profile(Package$parse$Lookup)
2226 parser = &[database_ records]->Lookup(file_);
2231 _profile(Package$parse$Find)
2236 {"architecture", &parsed->architecture_},
2237 {"icon", &parsed->icon_},
2238 {"depiction", &parsed->depiction_},
2239 {"homepage", &parsed->homepage_},
2240 {"website", &website},
2241 {"bugs", &parsed->bugs_},
2242 {"support", &parsed->support_},
2243 {"sponsor", &parsed->sponsor_},
2244 {"author", &parsed->author_},
2245 {"md5sum", &parsed->md5sum_},
2248 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2249 const char *start, *end;
2251 if (parser->Find(names[i].name_, start, end)) {
2252 CYString &value(*names[i].value_);
2253 _profile(Package$parse$Value)
2254 value.set(pool_, start, end - start);
2260 _profile(Package$parse$Tagline)
2261 const char *start, *end;
2262 if (parser->ShortDesc(start, end)) {
2263 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2266 while (stop != start && stop[-1] == '\r')
2268 parsed->tagline_.set(pool_, start, stop - start);
2272 _profile(Package$parse$Retain)
2273 if (parsed->homepage_.empty())
2274 parsed->homepage_ = website;
2275 if (parsed->homepage_ == parsed->depiction_)
2276 parsed->homepage_.clear();
2281 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2282 if ((self = [super init]) != nil) {
2283 _profile(Package$initWithVersion)
2285 apr_pool_create(&pool_, NULL);
2291 database_ = database;
2292 era_ = [database era];
2296 pkgCache::PkgIterator iterator(version.ParentPkg());
2297 iterator_ = iterator;
2299 _profile(Package$initWithVersion$Version)
2300 if (!version_.end())
2301 file_ = version_.FileList();
2303 pkgCache &cache([database_ cache]);
2304 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2308 _profile(Package$initWithVersion$Cache)
2309 name_.set(NULL, iterator.Display());
2311 latest_.set(NULL, StripVersion_(version_.VerStr()));
2313 pkgCache::VerIterator current(iterator.CurrentVer());
2315 installed_.set(NULL, StripVersion_(current.VerStr()));
2318 _profile(Package$initWithVersion$Tags)
2319 pkgCache::TagIterator tag(iterator.TagList());
2321 tags_ = [NSMutableArray arrayWithCapacity:8];
2323 const char *name(tag.Name());
2324 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2326 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2327 if (strcmp(name + 6, "enduser") == 0)
2329 else if (strcmp(name + 6, "hacker") == 0)
2331 else if (strcmp(name + 6, "developer") == 0)
2333 else if (strcmp(name + 6, "cydia") == 0)
2339 if (strncmp(name, "cydia::", 7) == 0) {
2340 if (strcmp(name + 7, "essential") == 0)
2342 else if (strcmp(name + 7, "obsolete") == 0)
2347 } while (!tag.end());
2351 _profile(Package$initWithVersion$Metadata)
2352 const char *mixed(iterator.Name());
2353 size_t size(strlen(mixed));
2354 char lower[size + 1];
2356 for (size_t i(0); i != size; ++i)
2357 lower[i] = mixed[i] | 0x20;
2360 PackageValue *metadata(PackageFind(lower, size));
2361 metadata_ = metadata;
2363 id_.set(NULL, metadata->name_, size);
2365 const char *latest(version_.VerStr());
2366 size_t length(strlen(latest));
2368 uint16_t vhash(hashlittle(latest, length));
2370 size_t capped(std::min<size_t>(8, length));
2371 latest = latest + length - capped;
2373 if (metadata->first_ == 0)
2374 metadata->first_ = now_;
2376 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2377 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2378 metadata->vhash_ = vhash;
2379 metadata->last_ = now_;
2380 } else if (metadata->last_ == 0)
2381 metadata->last_ = metadata->first_;
2384 _profile(Package$initWithVersion$Section)
2385 section_ = version_.Section();
2388 _profile(Package$initWithVersion$Flags)
2389 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2390 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2395 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2396 pkgCache::VerIterator version;
2398 _profile(Package$packageWithIterator$GetCandidateVer)
2399 version = [database policy]->GetCandidateVer(iterator);
2407 _profile(Package$packageWithIterator$Allocate)
2408 package = [Package allocWithZone:zone];
2411 _profile(Package$packageWithIterator$Initialize)
2413 initWithVersion:version
2420 _profile(Package$packageWithIterator$Autorelease)
2421 package = [package autorelease];
2427 - (pkgCache::PkgIterator) iterator {
2431 - (NSString *) section {
2432 if (section$_ == nil) {
2433 if (section_ == NULL)
2436 _profile(Package$section$mappedSectionForPointer)
2437 section$_ = [database_ mappedSectionForPointer:section_];
2442 - (NSString *) simpleSection {
2443 if (NSString *section = [self section])
2444 return Simplify(section);
2449 - (NSString *) longSection {
2450 return LocalizeSection([self section]);
2453 - (NSString *) shortSection {
2454 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2457 - (NSString *) uri {
2460 pkgIndexFile *index;
2461 pkgCache::PkgFileIterator file(file_.File());
2462 if (![database_ list].FindIndex(file, index))
2464 return [NSString stringWithUTF8String:iterator_->Path];
2465 //return [NSString stringWithUTF8String:file.Site()];
2466 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2470 - (MIMEAddress *) maintainer {
2471 @synchronized (database_) {
2472 if ([database_ era] != era_ || file_.end())
2475 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2476 const std::string &maintainer(parser->Maintainer());
2477 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2480 - (NSString *) md5sum {
2481 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2485 @synchronized (database_) {
2486 if ([database_ era] != era_ || version_.end())
2489 return version_->InstalledSize;
2492 - (NSString *) longDescription {
2493 @synchronized (database_) {
2494 if ([database_ era] != era_ || file_.end())
2497 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2498 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2500 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2501 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2502 if ([lines count] < 2)
2505 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2506 for (size_t i(1), e([lines count]); i != e; ++i) {
2507 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2508 [trimmed addObject:trim];
2511 return [trimmed componentsJoinedByString:@"\n"];
2514 - (NSString *) shortDescription {
2515 if (parsed_ != NULL)
2516 return static_cast<NSString *>(parsed_->tagline_);
2518 @synchronized (database_) {
2519 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2521 const char *start, *end;
2522 if (!parser.ShortDesc(start, end))
2525 if (end - start > 200)
2529 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2532 while (end != start && end[-1] == '\r')
2536 return [(id) CYStringCreate(start, end - start) autorelease];
2540 _profile(Package$index)
2541 CFStringRef name((CFStringRef) [self name]);
2542 if (CFStringGetLength(name) == 0)
2544 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2545 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2547 return toupper(character);
2551 - (PackageValue *) metadata {
2556 PackageValue *metadata([self metadata]);
2557 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2560 - (bool) subscribed {
2561 return [self metadata]->subscribed_;
2564 - (bool) setSubscribed:(bool)subscribed {
2565 PackageValue *metadata([self metadata]);
2566 if (metadata->subscribed_ == subscribed)
2568 metadata->subscribed_ = subscribed;
2576 - (NSString *) latest {
2580 - (NSString *) installed {
2584 - (BOOL) uninstalled {
2585 return installed_.empty();
2589 return !version_.end();
2592 - (BOOL) upgradableAndEssential:(BOOL)essential {
2593 _profile(Package$upgradableAndEssential)
2594 pkgCache::VerIterator current(iterator_.CurrentVer());
2596 return essential && essential_;
2598 return !version_.end() && version_ != current;
2602 - (BOOL) essential {
2607 return [database_ cache][iterator_].InstBroken();
2610 - (BOOL) unfiltered {
2611 _profile(Package$unfiltered$obsolete)
2612 if (_unlikely(obsolete_))
2616 _profile(Package$unfiltered$hasSupportingRole)
2617 if (_unlikely(![self hasSupportingRole]))
2625 if (![self unfiltered])
2630 _profile(Package$visible$section)
2631 section = [self section];
2634 _profile(Package$visible$isSectionVisible)
2635 if (!isSectionVisible(section))
2643 unsigned char current(iterator_->CurrentState);
2644 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2647 - (BOOL) halfConfigured {
2648 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2651 - (BOOL) halfInstalled {
2652 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2656 @synchronized (database_) {
2657 if ([database_ era] != era_ || iterator_.end())
2660 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2661 return state.Mode != pkgDepCache::ModeKeep;
2664 - (NSString *) mode {
2665 @synchronized (database_) {
2666 if ([database_ era] != era_ || iterator_.end())
2669 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2671 switch (state.Mode) {
2672 case pkgDepCache::ModeDelete:
2673 if ((state.iFlags & pkgDepCache::Purge) != 0)
2677 case pkgDepCache::ModeKeep:
2678 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2679 return @"REINSTALL";
2680 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2684 case pkgDepCache::ModeInstall:
2685 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2686 return @"REINSTALL";
2687 else*/ switch (state.Status) {
2689 return @"DOWNGRADE";
2695 return @"NEW_INSTALL";
2706 - (NSString *) name {
2707 return name_.empty() ? id_ : name_;
2710 - (UIImage *) icon {
2711 NSString *section = [self simpleSection];
2714 if (parsed_ != NULL)
2715 if (NSString *href = parsed_->icon_)
2716 if ([href hasPrefix:@"file:///"])
2717 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2718 if (icon == nil) if (section != nil)
2719 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2720 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2721 if ([dicon hasPrefix:@"file:///"])
2722 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2724 icon = [UIImage applicationImageNamed:@"unknown.png"];
2728 - (NSString *) homepage {
2729 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2732 - (NSString *) depiction {
2733 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2736 - (MIMEAddress *) sponsor {
2737 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2740 - (MIMEAddress *) author {
2741 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2744 - (NSString *) support {
2745 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2748 - (NSArray *) files {
2749 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2750 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2753 fin.open([path UTF8String]);
2758 while (std::getline(fin, line))
2759 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2764 - (NSString *) state {
2765 @synchronized (database_) {
2766 if ([database_ era] != era_ || file_.end())
2769 switch (iterator_->CurrentState) {
2770 case pkgCache::State::NotInstalled:
2771 return @"NotInstalled";
2772 case pkgCache::State::UnPacked:
2774 case pkgCache::State::HalfConfigured:
2775 return @"HalfConfigured";
2776 case pkgCache::State::HalfInstalled:
2777 return @"HalfInstalled";
2778 case pkgCache::State::ConfigFiles:
2779 return @"ConfigFiles";
2780 case pkgCache::State::Installed:
2781 return @"Installed";
2782 case pkgCache::State::TriggersAwaited:
2783 return @"TriggersAwaited";
2784 case pkgCache::State::TriggersPending:
2785 return @"TriggersPending";
2788 return (NSString *) [NSNull null];
2791 - (NSString *) selection {
2792 @synchronized (database_) {
2793 if ([database_ era] != era_ || file_.end())
2796 switch (iterator_->SelectedState) {
2797 case pkgCache::State::Unknown:
2799 case pkgCache::State::Install:
2801 case pkgCache::State::Hold:
2803 case pkgCache::State::DeInstall:
2804 return @"DeInstall";
2805 case pkgCache::State::Purge:
2809 return (NSString *) [NSNull null];
2812 - (NSArray *) warnings {
2813 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2814 const char *name(iterator_.Name());
2816 size_t length(strlen(name));
2817 if (length < 2) invalid:
2818 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2819 else for (size_t i(0); i != length; ++i)
2821 /* XXX: technically this is not allowed */
2822 (name[i] < 'A' || name[i] > 'Z') &&
2823 (name[i] < 'a' || name[i] > 'z') &&
2824 (name[i] < '0' || name[i] > '9') &&
2825 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2828 if (strcmp(name, "cydia") != 0) {
2831 bool _private = false;
2834 bool repository = [[self section] isEqualToString:@"Repositories"];
2836 if (NSArray *files = [self files])
2837 for (NSString *file in files)
2838 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2840 else if (!user && [file isEqualToString:@"/User"])
2842 else if (!_private && [file isEqualToString:@"/private"])
2844 else if (!stash && [file isEqualToString:@"/var/stash"])
2847 /* XXX: this is not sensitive enough. only some folders are valid. */
2848 if (cydia && !repository)
2849 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2851 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2853 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2855 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2858 return [warnings count] == 0 ? nil : warnings;
2861 - (NSArray *) applications {
2862 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2864 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2866 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2867 if (NSArray *files = [self files])
2868 for (NSString *file in files)
2869 if (application_r(file)) {
2870 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2871 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2872 if ([id isEqualToString:me])
2875 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2877 display = application_r[1];
2879 NSString *bundle([file stringByDeletingLastPathComponent]);
2880 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2881 if (icon == nil || [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 [[UIDevice currentDevice] 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 @"getAllSourcs";
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(removeButton))
4165 return @"removeButton";
4166 else if (selector == @selector(saveConfig))
4167 return @"saveConfig";
4168 else if (selector == @selector(setMetadataValue::))
4169 return @"setMetadataValue";
4170 else if (selector == @selector(setSessionValue::))
4171 return @"setSessionValue";
4172 else if (selector == @selector(setShowPromoted:))
4173 return @"setShowPromoted";
4174 else if (selector == @selector(substitutePackageNames:))
4175 return @"substitutePackageNames";
4176 else if (selector == @selector(scrollToBottom:))
4177 return @"scrollToBottom";
4178 else if (selector == @selector(setAllowsNavigationAction:))
4179 return @"setAllowsNavigationAction";
4180 else if (selector == @selector(setBadgeValue:))
4181 return @"setBadgeValue";
4182 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4183 return @"setButtonImage";
4184 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4185 return @"setButtonTitle";
4186 else if (selector == @selector(setHidesBackButton:))
4187 return @"setHidesBackButton";
4188 else if (selector == @selector(setHidesNavigationBar:))
4189 return @"setHidesNavigationBar";
4190 else if (selector == @selector(setNavigationBarStyle:))
4191 return @"setNavigationBarStyle";
4192 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4193 return @"setNavigationBarTintColor";
4194 else if (selector == @selector(setPasteboardString:))
4195 return @"setPasteboardString";
4196 else if (selector == @selector(setPasteboardURL:))
4197 return @"setPasteboardURL";
4198 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4199 return @"setScrollAlwaysBounceVertical";
4200 else if (selector == @selector(setScrollIndicatorStyle:))
4201 return @"setScrollIndicatorStyle";
4202 else if (selector == @selector(setToken:))
4204 else if (selector == @selector(setViewportWidth:))
4205 return @"setViewportWidth";
4206 else if (selector == @selector(statfs:))
4208 else if (selector == @selector(supports:))
4210 else if (selector == @selector(unload))
4216 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4217 return [self webScriptNameForSelector:selector] == nil;
4220 - (BOOL) supports:(NSString *)feature {
4221 return [feature isEqualToString:@"window.open"];
4225 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4228 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4229 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4232 - (void) setScrollIndicatorStyle:(NSString *)style {
4233 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4236 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4237 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4240 - (NSNumber *) getKernelNumber:(NSString *)name {
4241 const char *string([name UTF8String]);
4244 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4245 return (id) [NSNull null];
4247 if (size != sizeof(int))
4248 return (id) [NSNull null];
4251 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4252 return (id) [NSNull null];
4254 return [NSNumber numberWithInt:value];
4257 - (NSString *) getKernelString:(NSString *)name {
4258 const char *string([name UTF8String]);
4261 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4262 return (id) [NSNull null];
4264 char value[size + 1];
4265 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4266 return (id) [NSNull null];
4268 // XXX: just in case you request something ludicrous
4271 return [NSString stringWithCString:value];
4274 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4275 NSObject *value(CYIOGetValue([path UTF8String], entry));
4278 if ([value isKindOfClass:[NSData class]])
4279 value = CYHex((NSData *) value);
4284 - (NSArray *) getMetadataKeys {
4285 @synchronized (Values_) {
4286 return [Values_ allKeys];
4289 - (void) _setShowPromoted:(NSNumber *)value {
4290 [Metadata_ setObject:value forKey:@"ShowPromoted"];
4294 - (void) setShowPromoted:(NSNumber *)value {
4295 [self performSelectorOnMainThread:@selector(_setShowPromoted:) withObject:value waitUntilDone:NO];
4298 - (id) getMetadataValue:(NSString *)key {
4299 @synchronized (Values_) {
4300 return [Values_ objectForKey:key];
4303 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4304 @synchronized (Values_) {
4305 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4306 [Values_ removeObjectForKey:key];
4308 [Values_ setObject:value forKey:key];
4310 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4313 - (id) getSessionValue:(NSString *)key {
4314 @synchronized (SessionData_) {
4315 return [SessionData_ objectForKey:key];
4318 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4319 @synchronized (SessionData_) {
4320 if (value == (id) [WebUndefined undefined])
4321 [SessionData_ removeObjectForKey:key];
4323 [SessionData_ setObject:value forKey:key];
4326 - (void) addBridgedHost:(NSString *)host {
4327 @synchronized (HostConfig_) {
4328 [BridgedHosts_ addObject:host];
4331 - (void) addInsecureHost:(NSString *)host {
4332 @synchronized (HostConfig_) {
4333 [InsecureHosts_ addObject:host];
4336 - (void) addTokenHost:(NSString *)host {
4337 @synchronized (HostConfig_) {
4338 [TokenHosts_ addObject:host];
4341 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4342 @synchronized (HostConfig_) {
4343 if (scheme != (id) [WebUndefined undefined])
4344 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4346 [PipelinedHosts_ addObject:host];
4349 - (void) popViewController:(NSNumber *)value {
4350 if (value == (id) [WebUndefined undefined])
4351 value = [NSNumber numberWithBool:YES];
4352 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4355 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4356 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4358 for (NSString *section in sections)
4359 [array addObject:section];
4361 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4364 distribution, @"Distribution",
4366 nil] waitUntilDone:NO];
4369 - (void) addTrivialSource:(NSString *)href {
4370 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4373 - (void) refreshSources {
4374 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4377 - (void) saveConfig {
4378 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4381 - (NSArray *) getAllSources {
4382 return [[Database sharedInstance] sources];
4385 - (NSArray *) getInstalledPackages {
4386 Database *database([Database sharedInstance]);
4387 @synchronized (database) {
4388 NSArray *packages([database packages]);
4389 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4390 for (Package *package in packages)
4391 if (![package uninstalled])
4392 [installed addObject:package];
4396 - (Package *) getPackageById:(NSString *)id {
4397 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4401 return (Package *) [NSNull null];
4404 - (NSString *) getLocaleIdentifier {
4405 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4408 - (NSArray *) getPreferredLanguages {
4412 - (NSArray *) statfs:(NSString *)path {
4415 if (path == nil || statfs([path UTF8String], &stat) == -1)
4418 return [NSArray arrayWithObjects:
4419 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4420 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4421 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4425 - (NSNumber *) du:(NSString *)path {
4426 NSNumber *value(nil);
4429 _assert(pipe(fds) != -1);
4431 pid_t pid(ExecFork());
4433 _assert(dup2(fds[1], 1) != -1);
4434 _assert(close(fds[0]) != -1);
4435 _assert(close(fds[1]) != -1);
4436 /* XXX: this should probably not use du */
4437 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4442 _assert(close(fds[1]) != -1);
4444 if (FILE *du = fdopen(fds[0], "r")) {
4446 while (fgets(line, sizeof(line), du) != NULL) {
4447 size_t length(strlen(line));
4448 while (length != 0 && line[length - 1] == '\n')
4449 line[--length] = '\0';
4450 if (char *tab = strchr(line, '\t')) {
4452 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4457 } else _assert(close(fds[0]));
4465 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4468 - (NSNumber *) isReachable:(NSString *)name {
4469 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4472 - (void) installPackages:(NSArray *)packages {
4473 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4476 - (NSString *) substitutePackageNames:(NSString *)message {
4477 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4478 for (size_t i(0), e([words count]); i != e; ++i) {
4479 NSString *word([words objectAtIndex:i]);
4480 if (Package *package = [[Database sharedInstance] packageWithName:word])
4481 [words replaceObjectAtIndex:i withObject:[package name]];
4484 return [words componentsJoinedByString:@" "];
4487 - (void) removeButton {
4488 [indirect_ removeButton];
4491 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4492 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4495 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4496 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4499 - (void) setBadgeValue:(id)value {
4500 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4503 - (void) setAllowsNavigationAction:(NSString *)value {
4504 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4507 - (void) setHidesBackButton:(NSString *)value {
4508 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4511 - (void) setHidesNavigationBar:(NSString *)value {
4512 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4515 - (void) setNavigationBarStyle:(NSString *)value {
4516 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4519 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4520 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4521 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4522 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4525 - (void) setPasteboardString:(NSString *)value {
4526 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4529 - (void) setPasteboardURL:(NSString *)value {
4530 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4533 - (void) _setToken:(NSString *)token {
4537 [Metadata_ removeObjectForKey:@"Token"];
4539 [Metadata_ setObject:Token_ forKey:@"Token"];
4544 - (void) setToken:(NSString *)token {
4545 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4548 - (void) scrollToBottom:(NSNumber *)animated {
4549 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4552 - (void) setViewportWidth:(float)width {
4553 [indirect_ setViewportWidthOnMainThread:width];
4556 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4557 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4558 unsigned count([arguments count]);
4560 for (unsigned i(0); i != count; ++i)
4561 values[i] = [arguments objectAtIndex:i];
4562 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4565 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4566 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4568 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4570 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4576 @interface NSURL (CydiaSecure)
4579 @implementation NSURL (CydiaSecure)
4581 - (bool) isCydiaSecure {
4582 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4585 @synchronized (HostConfig_) {
4586 if ([InsecureHosts_ containsObject:[self host]])
4595 /* Cydia Browser Controller {{{ */
4596 @implementation CydiaWebViewController
4598 - (NSURL *) navigationURL {
4599 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4602 + (void) _initialize {
4603 [super _initialize];
4605 Diversions_ = [NSMutableSet setWithCapacity:0];
4608 + (void) addDiversion:(Diversion *)diversion {
4609 [Diversions_ addObject:diversion];
4612 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4613 [super webView:view didClearWindowObject:window forFrame:frame];
4614 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4617 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4618 WebDataSource *source([frame dataSource]);
4619 NSURLResponse *response([source response]);
4620 NSURL *url([response URL]);
4621 NSString *scheme([[url scheme] lowercaseString]);
4623 bool bridged(false);
4625 @synchronized (HostConfig_) {
4626 if ([scheme isEqualToString:@"file"])
4628 else if ([scheme isEqualToString:@"https"])
4629 if ([BridgedHosts_ containsObject:[url host]])
4634 [window setValue:cydia forKey:@"cydia"];
4637 - (void) _setupMail:(MFMailComposeViewController *)controller {
4638 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4640 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4641 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4644 - (NSURL *) URLWithURL:(NSURL *)url {
4645 return [Diversion divertURL:url];
4648 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4649 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4652 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4653 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4655 NSURL *url([copy URL]);
4656 NSString *href([url absoluteString]);
4657 NSString *host([url host]);
4659 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4660 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4661 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4662 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4665 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4666 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4668 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4672 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4673 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4674 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4675 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4680 @synchronized (HostConfig_) {
4681 bridged = [BridgedHosts_ containsObject:host];
4682 token = [TokenHosts_ containsObject:host];
4685 if ([url isCydiaSecure]) {
4687 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4688 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4690 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4691 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4698 - (void) setDelegate:(id)delegate {
4699 [super setDelegate:delegate];
4700 [cydia_ setDelegate:delegate];
4703 - (NSString *) applicationNameForUserAgent {
4708 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4709 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4715 @interface AppCacheController : CydiaWebViewController {
4720 @implementation AppCacheController
4722 - (void) didReceiveMemoryWarning {
4723 // XXX: this doesn't work
4726 - (bool) retainsNetworkActivityIndicator {
4734 @interface NSObject (CydiaScript)
4735 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4738 @implementation NSObject (CydiaScript)
4740 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4746 @implementation NSArray (CydiaScript)
4748 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4749 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4750 for (size_t i(0), e([self count]); i != e; ++i)
4751 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4757 @implementation NSDictionary (CydiaScript)
4759 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4760 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4762 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4769 /* Confirmation Controller {{{ */
4770 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4771 if (!iterator.end())
4772 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4773 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4775 pkgCache::PkgIterator package(dep.TargetPkg());
4778 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4785 @protocol ConfirmationControllerDelegate
4786 - (void) cancelAndClear:(bool)clear;
4787 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4791 @interface ConfirmationController : CydiaWebViewController {
4792 _transient Database *database_;
4794 _H<UIAlertView> essential_;
4796 _H<NSDictionary> changes_;
4797 _H<NSMutableArray> issues_;
4798 _H<NSDictionary> sizes_;
4803 - (id) initWithDatabase:(Database *)database;
4807 @implementation ConfirmationController
4811 RestartSubstrate_ = true;
4812 [delegate_ confirmWithNavigationController:[self navigationController]];
4815 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4816 NSString *context([alert context]);
4818 if ([context isEqualToString:@"remove"]) {
4819 if (button == [alert cancelButtonIndex])
4820 [self dismissModalViewControllerAnimated:YES];
4821 else if (button == [alert firstOtherButtonIndex]) {
4822 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
4825 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4826 } else if ([context isEqualToString:@"unable"]) {
4827 [self dismissModalViewControllerAnimated:YES];
4828 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4830 [super alertView:alert clickedButtonAtIndex:button];
4834 - (void) _doContinue {
4835 [delegate_ cancelAndClear:NO];
4836 [self dismissModalViewControllerAnimated:YES];
4839 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4840 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4844 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4845 [super webView:view didClearWindowObject:window forFrame:frame];
4847 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4848 (id) changes_, @"changes",
4849 (id) issues_, @"issues",
4850 (id) sizes_, @"sizes",
4852 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4855 - (id) initWithDatabase:(Database *)database {
4856 if ((self = [super init]) != nil) {
4857 database_ = database;
4859 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4860 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4861 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4862 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4863 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4867 pkgCacheFile &cache([database_ cache]);
4868 NSArray *packages([database_ packages]);
4869 pkgDepCache::Policy *policy([database_ policy]);
4871 issues_ = [NSMutableArray arrayWithCapacity:4];
4873 for (Package *package in packages) {
4874 pkgCache::PkgIterator iterator([package iterator]);
4875 NSString *name([package id]);
4877 if ([package broken]) {
4878 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4880 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4882 reasons, @"reasons",
4885 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4889 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4890 pkgCache::DepIterator start;
4891 pkgCache::DepIterator end;
4892 dep.GlobOr(start, end); // ++dep
4894 if (!cache->IsImportantDep(end))
4896 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4899 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4901 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4902 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4903 clauses, @"clauses",
4907 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4909 pkgCache::PkgIterator target(start.TargetPkg());
4910 if (target->ProvidesList != 0)
4911 reason = @"missing";
4913 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4915 reason = @"installed";
4916 installed = [NSString stringWithUTF8String:ver.VerStr()];
4917 } else if (!cache[target].CandidateVerIter(cache).end())
4918 reason = @"uninstalled";
4919 else if (target->ProvidesList == 0)
4920 reason = @"uninstallable";
4922 reason = @"virtual";
4925 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4926 [NSString stringWithUTF8String:start.CompType()], @"operator",
4927 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4930 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4931 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4932 version, @"version",
4934 installed, @"installed",
4937 // yes, seriously. (wtf?)
4945 pkgDepCache::StateCache &state(cache[iterator]);
4947 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4949 if (state.NewInstall())
4950 [installs addObject:name];
4951 // XXX: else if (state.Install())
4952 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4953 [reinstalls addObject:name];
4954 // XXX: move before previous if
4955 else if (state.Upgrade())
4956 [upgrades addObject:name];
4957 else if (state.Downgrade())
4958 [downgrades addObject:name];
4959 else if (!state.Delete())
4960 // XXX: _assert(state.Keep());
4962 else if (special_r(name))
4963 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4964 [NSNull null], @"package",
4965 [NSArray arrayWithObjects:
4966 [NSDictionary dictionaryWithObjectsAndKeys:
4967 @"Conflicts", @"relationship",
4968 [NSArray arrayWithObjects:
4969 [NSDictionary dictionaryWithObjectsAndKeys:
4971 [NSNull null], @"version",
4972 @"installed", @"reason",
4979 if ([package essential])
4981 [removes addObject:name];
4984 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4985 substrate_ |= DepSubstrate(iterator.CurrentVer());
4990 else if (Advanced_) {
4991 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4993 essential_ = [[[UIAlertView alloc]
4994 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4995 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4997 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4999 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5003 [essential_ setContext:@"remove"];
5004 [essential_ setNumberOfRows:2];
5006 essential_ = [[[UIAlertView alloc]
5007 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5008 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5010 cancelButtonTitle:UCLocalize("OKAY")
5011 otherButtonTitles:nil
5014 [essential_ setContext:@"unable"];
5017 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5018 installs, @"installs",
5019 reinstalls, @"reinstalls",
5020 upgrades, @"upgrades",
5021 downgrades, @"downgrades",
5022 removes, @"removes",
5025 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5026 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5027 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5030 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5034 - (UIBarButtonItem *) leftButton {
5035 return [[[UIBarButtonItem alloc]
5036 initWithTitle:UCLocalize("CANCEL")
5037 style:UIBarButtonItemStylePlain
5039 action:@selector(cancelButtonClicked)
5044 - (void) applyRightButton {
5045 if ([issues_ count] == 0 && ![self isLoading])
5046 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5047 initWithTitle:UCLocalize("CONFIRM")
5048 style:UIBarButtonItemStyleDone
5050 action:@selector(confirmButtonClicked)
5053 [[self navigationItem] setRightBarButtonItem:nil];
5057 - (void) cancelButtonClicked {
5058 [delegate_ cancelAndClear:YES];
5059 [self dismissModalViewControllerAnimated:YES];
5063 - (void) confirmButtonClicked {
5064 if (essential_ != nil)
5074 /* Progress Data {{{ */
5075 @interface CydiaProgressData : NSObject {
5076 _transient id delegate_;
5085 _H<NSMutableArray> events_;
5086 _H<NSString> title_;
5088 _H<NSString> status_;
5089 _H<NSString> finish_;
5094 @implementation CydiaProgressData
5096 + (NSArray *) _attributeKeys {
5097 return [NSArray arrayWithObjects:
5109 - (NSArray *) attributeKeys {
5110 return [[self class] _attributeKeys];
5113 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5114 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5118 if ((self = [super init]) != nil) {
5119 events_ = [NSMutableArray arrayWithCapacity:32];
5123 - (void) setDelegate:(id)delegate {
5124 delegate_ = delegate;
5127 - (void) setPercent:(float)value {
5131 - (NSNumber *) percent {
5132 return [NSNumber numberWithFloat:percent_];
5135 - (void) setCurrent:(float)value {
5139 - (NSNumber *) current {
5140 return [NSNumber numberWithFloat:current_];
5143 - (void) setTotal:(float)value {
5147 - (NSNumber *) total {
5148 return [NSNumber numberWithFloat:total_];
5151 - (void) setSpeed:(float)value {
5155 - (NSNumber *) speed {
5156 return [NSNumber numberWithFloat:speed_];
5159 - (NSArray *) events {
5163 - (void) removeAllEvents {
5164 [events_ removeAllObjects];
5167 - (void) addEvent:(CydiaProgressEvent *)event {
5168 [events_ addObject:event];
5171 - (void) setTitle:(NSString *)text {
5175 - (NSString *) title {
5179 - (void) setFinish:(NSString *)text {
5183 - (NSString *) finish {
5184 return (id) finish_ ?: [NSNull null];
5187 - (void) setRunning:(bool)running {
5191 - (NSNumber *) running {
5192 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5197 /* Progress Controller {{{ */
5198 @interface ProgressController : CydiaWebViewController <
5201 _transient Database *database_;
5202 _H<CydiaProgressData, 1> progress_;
5206 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5208 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5210 - (void) setTitle:(NSString *)title;
5211 - (void) setCancellable:(bool)cancellable;
5215 @implementation ProgressController
5218 [database_ setProgressDelegate:nil];
5222 - (UIBarButtonItem *) leftButton {
5223 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5224 initWithTitle:UCLocalize("CANCEL")
5225 style:UIBarButtonItemStylePlain
5227 action:@selector(cancel)
5228 ] autorelease] : nil;
5231 - (void) updateCancel {
5232 [super applyLeftButton];
5235 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5236 if ((self = [super init]) != nil) {
5237 database_ = database;
5238 delegate_ = delegate;
5240 [database_ setProgressDelegate:self];
5242 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5243 [progress_ setDelegate:self];
5245 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5247 [scroller_ setBackgroundColor:[UIColor blackColor]];
5249 [[self navigationItem] setHidesBackButton:YES];
5251 [self updateCancel];
5255 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5256 [super webView:view didClearWindowObject:window forFrame:frame];
5257 [window setValue:progress_ forKey:@"cydiaProgress"];
5260 - (void) updateProgress {
5261 [self dispatchEvent:@"CydiaProgressUpdate"];
5264 - (void) viewWillAppear:(BOOL)animated {
5265 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5266 [super viewWillAppear:animated];
5269 - (void) reloadSpringBoard {
5270 pid_t pid(ExecFork());
5272 pid_t pid(ExecFork());
5274 execl("/usr/bin/sbreload", "sbreload", NULL);
5285 system("/usr/bin/killall SpringBoard");
5289 UpdateExternalStatus(0);
5292 [delegate_ saveState];
5296 [delegate_ returnToCydia];
5300 [delegate_ terminateWithSuccess];
5301 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5302 [delegate_ suspendWithAnimation:YES];
5304 [delegate_ suspend];*/
5316 UIProgressHUD *hud([delegate_ addProgressHUD]);
5317 [hud setText:UCLocalize("LOADING")];
5318 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5324 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5325 SBReboot(SBSSpringBoardServerPort());
5327 reboot2(RB_AUTOBOOT);
5334 - (void) setTitle:(NSString *)title {
5335 [progress_ setTitle:title];
5336 [self updateProgress];
5339 - (UIBarButtonItem *) rightButton {
5340 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5341 initWithTitle:UCLocalize("CLOSE")
5342 style:UIBarButtonItemStylePlain
5344 action:@selector(close)
5348 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5349 UpdateExternalStatus(1);
5351 [progress_ setRunning:true];
5352 [self setTitle:title];
5353 // implicit updateProgress
5355 SHA1SumValue notifyconf; {
5357 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5360 MMap mmap(file, MMap::ReadOnly);
5362 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5363 notifyconf = sha1.Result();
5367 SHA1SumValue springlist; {
5369 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5372 MMap mmap(file, MMap::ReadOnly);
5374 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5375 springlist = sha1.Result();
5379 if (invocation != nil) {
5380 [invocation yieldToSelector:@selector(invoke)];
5381 [self setTitle:@"COMPLETE"];
5386 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5389 MMap mmap(file, MMap::ReadOnly);
5391 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5392 if (!(notifyconf == sha1.Result()))
5399 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5402 MMap mmap(file, MMap::ReadOnly);
5404 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5405 if (!(springlist == sha1.Result()))
5411 if (RestartSubstrate_)
5415 RestartSubstrate_ = false;
5418 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5419 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5420 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5421 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5422 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5425 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5427 [progress_ setRunning:false];
5428 [self updateProgress];
5430 [self applyRightButton];
5433 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5434 [progress_ addEvent:event];
5435 [self updateProgress];
5438 - (bool) isProgressCancelled {
5439 return cancel_ == 2;
5444 [self updateCancel];
5447 - (void) setCancellable:(bool)cancellable {
5448 unsigned cancel(cancel_);
5452 else if (cancel_ == 0)
5455 if (cancel != cancel_)
5456 [self updateCancel];
5459 - (void) setProgressCancellable:(NSNumber *)cancellable {
5460 [self setCancellable:[cancellable boolValue]];
5463 - (void) setProgressPercent:(NSNumber *)percent {
5464 [progress_ setPercent:[percent floatValue]];
5465 [self updateProgress];
5468 - (void) setProgressStatus:(NSDictionary *)status {
5469 if (status == nil) {
5470 [progress_ setCurrent:0];
5471 [progress_ setTotal:0];
5472 [progress_ setSpeed:0];
5474 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5476 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5477 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5478 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5481 [self updateProgress];
5487 /* Package Cell {{{ */
5488 @interface PackageCell : CyteTableViewCell <
5489 CyteTableViewCellDelegate
5493 _H<NSString> description_;
5495 _H<NSString> source_;
5497 _H<UIImage> placard_;
5501 - (PackageCell *) init;
5502 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5504 - (void) drawContentRect:(CGRect)rect;
5508 @implementation PackageCell
5510 - (PackageCell *) init {
5511 CGRect frame(CGRectMake(0, 0, 320, 74));
5512 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5513 UIView *content([self contentView]);
5514 CGRect bounds([content bounds]);
5516 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5517 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5518 [content addSubview:content_];
5520 [content_ setDelegate:self];
5521 [content_ setOpaque:YES];
5525 - (NSString *) accessibilityLabel {
5526 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5529 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5530 summarized_ = summary;
5540 [content_ setBackgroundColor:[UIColor whiteColor]];
5544 Source *source = [package source];
5546 icon_ = [package icon];
5548 if (NSString *name = [package name])
5549 name_ = [NSString stringWithString:name];
5551 NSString *description(nil);
5553 if (description == nil && IsWildcat_)
5554 description = [package longDescription];
5555 if (description == nil)
5556 description = [package shortDescription];
5558 if (description != nil)
5559 description_ = [NSString stringWithString:description];
5561 commercial_ = [package isCommercial];
5563 NSString *label = nil;
5564 bool trusted = false;
5566 if (source != nil) {
5567 label = [source label];
5568 trusted = [source trusted];
5569 } else if ([[package id] isEqualToString:@"firmware"])
5570 label = UCLocalize("APPLE");
5572 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5574 NSString *from(label);
5576 NSString *section = [package simpleSection];
5577 if (section != nil && ![section isEqualToString:label]) {
5578 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5579 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5582 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5584 if (NSString *purpose = [package primaryPurpose])
5585 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5590 if (NSString *mode = [package mode]) {
5591 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5592 color = RemovingColor_;
5593 //placard = @"removing";
5595 color = InstallingColor_;
5596 //placard = @"installing";
5599 // XXX: the removing/installing placards are not @2x
5602 color = [UIColor whiteColor];
5604 if ([package installed] != nil)
5605 placard = @"installed";
5610 [content_ setBackgroundColor:color];
5613 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5616 [self setNeedsDisplay];
5617 [content_ setNeedsDisplay];
5620 - (void) drawSummaryContentRect:(CGRect)rect {
5621 bool highlighted(highlighted_);
5622 float width([self bounds].size.width);
5626 rect.size = [(UIImage *) icon_ size];
5628 while (rect.size.width > 16 || rect.size.height > 16) {
5629 rect.size.width /= 2;
5630 rect.size.height /= 2;
5633 rect.origin.x = 18 - rect.size.width / 2;
5634 rect.origin.y = 18 - rect.size.height / 2;
5636 [icon_ drawInRect:rect];
5639 if (badge_ != nil) {
5641 rect.size = [(UIImage *) badge_ size];
5643 rect.size.width /= 4;
5644 rect.size.height /= 4;
5646 rect.origin.x = 23 - rect.size.width / 2;
5647 rect.origin.y = 23 - rect.size.height / 2;
5649 [badge_ drawInRect:rect];
5656 UISetColor(commercial_ ? Purple_ : Black_);
5657 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5659 if (placard_ != nil)
5660 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5663 - (void) drawNormalContentRect:(CGRect)rect {
5664 bool highlighted(highlighted_);
5665 float width([self bounds].size.width);
5669 rect.size = [(UIImage *) icon_ size];
5671 while (rect.size.width > 32 || rect.size.height > 32) {
5672 rect.size.width /= 2;
5673 rect.size.height /= 2;
5676 rect.origin.x = 25 - rect.size.width / 2;
5677 rect.origin.y = 25 - rect.size.height / 2;
5679 [icon_ drawInRect:rect];
5682 if (badge_ != nil) {
5684 rect.size = [(UIImage *) badge_ size];
5686 rect.size.width /= 2;
5687 rect.size.height /= 2;
5689 rect.origin.x = 36 - rect.size.width / 2;
5690 rect.origin.y = 36 - rect.size.height / 2;
5692 [badge_ drawInRect:rect];
5699 UISetColor(commercial_ ? Purple_ : Black_);
5700 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5701 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5704 UISetColor(commercial_ ? Purplish_ : Gray_);
5705 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5707 if (placard_ != nil)
5708 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5711 - (void) drawContentRect:(CGRect)rect {
5713 [self drawSummaryContentRect:rect];
5715 [self drawNormalContentRect:rect];
5720 /* Section Cell {{{ */
5721 @interface SectionCell : CyteTableViewCell <
5722 CyteTableViewCellDelegate
5724 _H<NSString> basic_;
5725 _H<NSString> section_;
5727 _H<NSString> count_;
5729 _H<UISwitch> switch_;
5733 - (void) setSection:(Section *)section editing:(BOOL)editing;
5737 @implementation SectionCell
5739 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5740 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5741 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5742 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5743 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5745 UIView *content([self contentView]);
5746 CGRect bounds([content bounds]);
5748 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5749 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5750 [content addSubview:content_];
5751 [content_ setBackgroundColor:[UIColor whiteColor]];
5753 [content_ setDelegate:self];
5757 - (void) onSwitch:(id)sender {
5758 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5759 if (metadata == nil) {
5760 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5761 [Sections_ setObject:metadata forKey:basic_];
5764 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5768 - (void) setSection:(Section *)section editing:(BOOL)editing {
5769 if (editing != editing_) {
5771 [switch_ removeFromSuperview];
5773 [self addSubview:switch_];
5782 if (section == nil) {
5783 name_ = UCLocalize("ALL_PACKAGES");
5786 basic_ = [section name];
5787 section_ = [section localized];
5789 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5790 count_ = [NSString stringWithFormat:@"%d", [section count]];
5793 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5796 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5797 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5799 [content_ setNeedsDisplay];
5802 - (void) setFrame:(CGRect)frame {
5803 [super setFrame:frame];
5805 CGRect rect([switch_ frame]);
5806 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5809 - (NSString *) accessibilityLabel {
5813 - (void) drawContentRect:(CGRect)rect {
5814 bool highlighted(highlighted_ && !editing_);
5816 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5821 float width(rect.size.width);
5827 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5829 CGSize size = [count_ sizeWithFont:Font14_];
5833 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5839 /* File Table {{{ */
5840 @interface FileTable : CyteViewController <
5841 UITableViewDataSource,
5844 _transient Database *database_;
5845 _H<Package> package_;
5847 _H<NSMutableArray> files_;
5848 _H<UITableView, 2> list_;
5851 - (id) initWithDatabase:(Database *)database;
5852 - (void) setPackage:(Package *)package;
5856 @implementation FileTable
5858 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5859 return files_ == nil ? 0 : [files_ count];
5862 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5866 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5867 static NSString *reuseIdentifier = @"Cell";
5869 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5871 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5872 [cell setFont:[UIFont systemFontOfSize:16]];
5874 [cell setText:[files_ objectAtIndex:indexPath.row]];
5875 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5880 - (NSURL *) navigationURL {
5881 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5885 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5886 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5887 [list_ setRowHeight:24.0f];
5888 [(UITableView *) list_ setDataSource:self];
5889 [list_ setDelegate:self];
5890 [self setView:list_];
5893 - (void) viewDidLoad {
5894 [super viewDidLoad];
5896 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5899 - (void) releaseSubviews {
5905 [super releaseSubviews];
5908 - (id) initWithDatabase:(Database *)database {
5909 if ((self = [super init]) != nil) {
5910 database_ = database;
5914 - (void) setPackage:(Package *)package {
5918 files_ = [NSMutableArray arrayWithCapacity:32];
5920 if (package != nil) {
5922 name_ = [package id];
5924 if (NSArray *files = [package files])
5925 [files_ addObjectsFromArray:files];
5927 if ([files_ count] != 0) {
5928 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5929 [files_ removeObjectAtIndex:0];
5930 [files_ sortUsingSelector:@selector(compareByPath:)];
5932 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5933 [stack addObject:@"/"];
5935 for (int i(0), e([files_ count]); i != e; ++i) {
5936 NSString *file = [files_ objectAtIndex:i];
5937 while (![file hasPrefix:[stack lastObject]])
5938 [stack removeLastObject];
5939 NSString *directory = [stack lastObject];
5940 [stack addObject:[file stringByAppendingString:@"/"]];
5941 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5942 ([stack count] - 2) * 3, "",
5943 [file substringFromIndex:[directory length]]
5952 - (void) reloadData {
5955 [self setPackage:[database_ packageWithName:name_]];
5960 /* Package Controller {{{ */
5961 @interface CYPackageController : CydiaWebViewController <
5962 UIActionSheetDelegate
5964 _transient Database *database_;
5965 _H<Package> package_;
5968 _H<NSMutableArray> buttons_;
5969 _H<UIBarButtonItem> button_;
5972 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
5976 @implementation CYPackageController
5978 - (NSURL *) navigationURL {
5979 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5982 /* XXX: this is not safe at all... localization of /fail/ */
5983 - (void) _clickButtonWithName:(NSString *)name {
5984 if ([name isEqualToString:UCLocalize("CLEAR")])
5985 [delegate_ clearPackage:package_];
5986 else if ([name isEqualToString:UCLocalize("INSTALL")])
5987 [delegate_ installPackage:package_];
5988 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5989 [delegate_ installPackage:package_];
5990 else if ([name isEqualToString:UCLocalize("REMOVE")])
5991 [delegate_ removePackage:package_];
5992 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5993 [delegate_ installPackage:package_];
5994 else _assert(false);
5997 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5998 NSString *context([sheet context]);
6000 if ([context isEqualToString:@"modify"]) {
6001 if (button != [sheet cancelButtonIndex]) {
6002 NSString *buttonName = [buttons_ objectAtIndex:button];
6003 [self _clickButtonWithName:buttonName];
6006 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6010 - (bool) _allowJavaScriptPanel {
6015 - (void) _customButtonClicked {
6016 int count([buttons_ count]);
6021 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6023 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6024 [buttons addObjectsFromArray:buttons_];
6026 UIActionSheet *sheet = [[[UIActionSheet alloc]
6029 cancelButtonTitle:nil
6030 destructiveButtonTitle:nil
6031 otherButtonTitles:nil
6034 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6036 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6037 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6039 [sheet setContext:@"modify"];
6041 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6045 // We don't want to allow non-commercial packages to do custom things to the install button,
6046 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6047 - (void) customButtonClicked {
6049 [super customButtonClicked];
6051 [self _customButtonClicked];
6054 - (void) reloadButtonClicked {
6055 // Don't reload a commerical package by tapping the loading button,
6056 // but if it's not an Install button, we should forward it on.
6057 if (![package_ uninstalled])
6058 [self _customButtonClicked];
6061 - (void) applyLoadingTitle {
6062 // Don't show "Loading" as the title. Ever.
6065 - (UIBarButtonItem *) rightButton {
6070 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6071 if ((self = [super init]) != nil) {
6072 database_ = database;
6073 buttons_ = [NSMutableArray arrayWithCapacity:4];
6074 name_ = name == nil ? @"" : [NSString stringWithString:name];
6075 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6079 - (void) reloadData {
6082 package_ = [database_ packageWithName:name_];
6084 [buttons_ removeAllObjects];
6086 if (package_ != nil) {
6087 [(Package *) package_ parse];
6089 commercial_ = [package_ isCommercial];
6091 if ([package_ mode] != nil)
6092 [buttons_ addObject:UCLocalize("CLEAR")];
6093 if ([package_ source] == nil);
6094 else if ([package_ upgradableAndEssential:NO])
6095 [buttons_ addObject:UCLocalize("UPGRADE")];
6096 else if ([package_ uninstalled])
6097 [buttons_ addObject:UCLocalize("INSTALL")];
6099 [buttons_ addObject:UCLocalize("REINSTALL")];
6100 if (![package_ uninstalled])
6101 [buttons_ addObject:UCLocalize("REMOVE")];
6105 switch ([buttons_ count]) {
6106 case 0: title = nil; break;
6107 case 1: title = [buttons_ objectAtIndex:0]; break;
6108 default: title = UCLocalize("MODIFY"); break;
6111 button_ = [[[UIBarButtonItem alloc]
6113 style:UIBarButtonItemStylePlain
6115 action:@selector(customButtonClicked)
6119 - (bool) isLoading {
6120 return commercial_ ? [super isLoading] : false;
6126 /* Package List Controller {{{ */
6127 @interface PackageListController : CyteViewController <
6128 UITableViewDataSource,
6131 _transient Database *database_;
6133 _H<NSArray> packages_;
6134 _H<NSMutableArray> sections_;
6135 _H<UITableView, 2> list_;
6136 _H<NSMutableArray> index_;
6137 _H<NSMutableDictionary> indices_;
6138 _H<NSString> title_;
6139 unsigned reloading_;
6142 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6143 - (void) setDelegate:(id)delegate;
6144 - (void) resetCursor;
6149 @implementation PackageListController
6151 - (NSURL *) referrerURL {
6152 return [self navigationURL];
6155 - (bool) isSummarized {
6159 - (bool) showsSections {
6163 - (void) deselectWithAnimation:(BOOL)animated {
6164 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6167 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6168 CGRect base = [[self view] bounds];
6169 base.size.height -= bounds.size.height;
6170 base.origin = [list_ frame].origin;
6172 [UIView beginAnimations:nil context:NULL];
6173 [UIView setAnimationBeginsFromCurrentState:YES];
6174 [UIView setAnimationCurve:curve];
6175 [UIView setAnimationDuration:duration];
6176 [list_ setFrame:base];
6177 [UIView commitAnimations];
6180 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6181 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6184 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6185 [self resizeForKeyboardBounds:bounds duration:0];
6188 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6189 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6190 *curve = UIViewAnimationCurveEaseInOut;
6192 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6194 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6197 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6200 - (void) keyboardWillShow:(NSNotification *)notification {
6203 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6204 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6206 NSTimeInterval duration;
6207 UIViewAnimationCurve curve;
6208 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6210 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);
6211 UIViewController *base = self;
6212 while ([base parentOrPresentingViewController] != nil)
6213 base = [base parentOrPresentingViewController];
6214 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6215 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6217 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6218 intersection.size.height += CYStatusBarHeight();
6220 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6223 - (void) keyboardWillHide:(NSNotification *)notification {
6224 NSTimeInterval duration;
6225 UIViewAnimationCurve curve;
6226 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6228 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6231 - (void) viewWillAppear:(BOOL)animated {
6232 [super viewWillAppear:animated];
6234 [self resizeForKeyboardBounds:CGRectZero];
6235 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6236 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6239 - (void) viewWillDisappear:(BOOL)animated {
6240 [super viewWillDisappear:animated];
6242 [self resizeForKeyboardBounds:CGRectZero];
6243 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6244 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6247 - (void) viewDidAppear:(BOOL)animated {
6248 [super viewDidAppear:animated];
6249 [self deselectWithAnimation:animated];
6252 - (void) didSelectPackage:(Package *)package {
6253 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6254 [view setDelegate:delegate_];
6255 [[self navigationController] pushViewController:view animated:YES];
6258 #if TryIndexedCollation
6259 + (BOOL) hasIndexedCollation {
6260 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6264 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6265 NSInteger count([sections_ count]);
6266 return count == 0 ? 1 : count;
6269 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6270 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6272 return [[sections_ objectAtIndex:section] name];
6275 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6276 if ([sections_ count] == 0)
6278 return [[sections_ objectAtIndex:section] count];
6281 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6282 @synchronized (database_) {
6283 if ([database_ era] != era_)
6286 Section *section([sections_ objectAtIndex:[path section]]);
6287 NSInteger row([path row]);
6288 Package *package([packages_ objectAtIndex:([section row] + row)]);
6289 return [[package retain] autorelease];
6292 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6293 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6295 cell = [[[PackageCell alloc] init] autorelease];
6297 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6298 [cell setPackage:package asSummary:[self isSummarized]];
6302 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6303 Package *package([self packageAtIndexPath:path]);
6304 package = [database_ packageWithName:[package id]];
6305 [self didSelectPackage:package];
6308 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6309 if (![self showsSections])
6315 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6316 #if TryIndexedCollation
6317 if ([[self class] hasIndexedCollation]) {
6318 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6325 - (void) updateHeight {
6326 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6329 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6330 if ((self = [super init]) != nil) {
6331 database_ = database;
6332 title_ = [title copy];
6333 [[self navigationItem] setTitle:title_];
6338 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6339 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6340 [self setView:view];
6342 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6343 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6344 [view addSubview:list_];
6346 // XXX: is 20 the most optimal number here?
6347 [list_ setSectionIndexMinimumDisplayRowCount:20];
6349 [(UITableView *) list_ setDataSource:self];
6350 [list_ setDelegate:self];
6352 [self updateHeight];
6355 - (void) releaseSubviews {
6363 [super releaseSubviews];
6366 - (void) setDelegate:(id)delegate {
6367 delegate_ = delegate;
6370 - (bool) shouldYield {
6374 - (bool) shouldBlock {
6378 - (NSMutableArray *) _reloadPackages {
6379 @synchronized (database_) {
6380 era_ = [database_ era];
6381 NSArray *packages([database_ packages]);
6383 return [NSMutableArray arrayWithArray:packages];
6386 - (void) _reloadData {
6387 if (reloading_ != 0) {
6395 if ([self shouldYield]) {
6399 if (![self shouldBlock])
6402 hud = [delegate_ addProgressHUD];
6403 [hud setText:UCLocalize("LOADING")];
6407 packages = [self yieldToSelector:@selector(_reloadPackages)];
6410 [delegate_ removeProgressHUD:hud];
6411 } while (reloading_ == 2);
6413 packages = [self _reloadPackages];
6416 @synchronized (database_) {
6417 if (era_ != [database_ era])
6421 packages_ = packages;
6423 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6424 sections_ = [NSMutableArray arrayWithCapacity:16];
6426 Section *section = nil;
6428 #if TryIndexedCollation
6429 if ([[self class] hasIndexedCollation]) {
6430 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6432 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6433 NSArray *titles = [collation sectionIndexTitles];
6436 _profile(PackageTable$reloadData$Section)
6437 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6441 _profile(PackageTable$reloadData$Section$Package)
6442 package = [packages_ objectAtIndex:offset];
6443 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6446 while (secidx < index) {
6449 _profile(PackageTable$reloadData$Section$Allocate)
6450 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6453 _profile(PackageTable$reloadData$Section$Add)
6454 [sections_ addObject:section];
6458 [section addToCount];
6464 index_ = [NSMutableArray arrayWithCapacity:32];
6466 bool sectioned([self showsSections]);
6468 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6469 [sections_ addObject:section];
6472 _profile(PackageTable$reloadData$Section)
6473 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6477 _profile(PackageTable$reloadData$Section$Package)
6478 package = [packages_ objectAtIndex:offset];
6479 index = [package index];
6482 if (sectioned && (section == nil || [section index] != index)) {
6483 _profile(PackageTable$reloadData$Section$Allocate)
6484 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6487 [index_ addObject:[section name]];
6488 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6490 _profile(PackageTable$reloadData$Section$Add)
6491 [sections_ addObject:section];
6495 [section addToCount];
6500 [self updateHeight];
6502 _profile(PackageTable$reloadData$List)
6503 [(UITableView *) list_ setDataSource:self];
6508 - (void) reloadData {
6511 if ([self shouldYield])
6512 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6517 - (void) resetCursor {
6518 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6521 - (void) clearData {
6522 [self updateHeight];
6524 [list_ setDataSource:nil];
6532 /* Filtered Package List Controller {{{ */
6533 @interface FilteredPackageListController : PackageListController {
6536 _H<NSObject> object_;
6539 - (void) setObject:(id)object;
6540 - (void) setObject:(id)object forFilter:(SEL)filter;
6543 - (void) setFilter:(SEL)filter;
6545 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6549 @implementation FilteredPackageListController
6555 - (void) setFilter:(SEL)filter {
6556 @synchronized (self) {
6559 /* XXX: this is an unsafe optimization of doomy hell */
6560 Method method(class_getInstanceMethod([Package class], filter));
6561 _assert(method != NULL);
6562 imp_ = method_getImplementation(method);
6563 _assert(imp_ != NULL);
6566 - (void) setObject:(id)object {
6567 @synchronized (self) {
6571 - (void) setObject:(id)object forFilter:(SEL)filter {
6572 @synchronized (self) {
6573 [self setFilter:filter];
6574 [self setObject:object];
6577 - (NSMutableArray *) _reloadPackages {
6578 @synchronized (database_) {
6579 era_ = [database_ era];
6580 NSArray *packages([database_ packages]);
6582 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6586 _H<NSObject> object;
6588 @synchronized (self) {
6594 _profile(PackageTable$reloadData$Filter)
6595 for (Package *package in packages)
6596 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6597 [filtered addObject:package];
6603 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6604 if ((self = [super initWithDatabase:database title:title]) != nil) {
6605 [self setFilter:filter];
6606 [self setObject:object];
6613 /* Home Controller {{{ */
6614 @interface HomeController : CydiaWebViewController {
6615 CFRunLoopRef runloop_;
6616 SCNetworkReachabilityRef reachability_;
6621 @implementation HomeController
6623 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6624 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6628 if ((self = [super init]) != nil) {
6629 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6632 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6633 if (reachability_ != NULL) {
6634 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6635 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6637 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6638 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6645 if (reachability_ != NULL && runloop_ != NULL)
6646 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6650 - (NSURL *) navigationURL {
6651 return [NSURL URLWithString:@"cydia://home"];
6654 - (void) aboutButtonClicked {
6655 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6657 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6658 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6659 [alert setCancelButtonIndex:0];
6662 @"Copyright \u00a9 2008-2011\n"
6665 "Jay Freeman (saurik)\n"
6666 "saurik@saurik.com\n"
6667 "http://www.saurik.com/"
6673 - (UIBarButtonItem *) leftButton {
6674 return [[[UIBarButtonItem alloc]
6675 initWithTitle:UCLocalize("ABOUT")
6676 style:UIBarButtonItemStylePlain
6678 action:@selector(aboutButtonClicked)
6684 /* Manage Controller {{{ */
6685 @interface ManageController : CydiaWebViewController {
6688 - (void) queueStatusDidChange;
6692 @implementation ManageController
6695 if ((self = [super init]) != nil) {
6696 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6700 - (NSURL *) navigationURL {
6701 return [NSURL URLWithString:@"cydia://manage"];
6704 - (UIBarButtonItem *) leftButton {
6705 return [[[UIBarButtonItem alloc]
6706 initWithTitle:UCLocalize("SETTINGS")
6707 style:UIBarButtonItemStylePlain
6709 action:@selector(settingsButtonClicked)
6713 - (void) settingsButtonClicked {
6714 [delegate_ showSettings];
6717 - (void) queueButtonClicked {
6721 - (UIBarButtonItem *) rightButton {
6722 return Queuing_ ? [[[UIBarButtonItem alloc]
6723 initWithTitle:UCLocalize("QUEUE")
6724 style:UIBarButtonItemStyleDone
6726 action:@selector(queueButtonClicked)
6727 ] autorelease] : nil;
6730 - (void) queueStatusDidChange {
6731 [self applyRightButton];
6734 - (bool) isLoading {
6735 return !Queuing_ && [super isLoading];
6741 /* Refresh Bar {{{ */
6742 @interface RefreshBar : UINavigationBar {
6743 _H<UIProgressIndicator> indicator_;
6744 _H<UITextLabel> prompt_;
6745 _H<UIProgressBar> progress_;
6746 _H<UINavigationButton> cancel_;
6751 @implementation RefreshBar
6753 - (void) positionViews {
6754 CGRect frame = [cancel_ frame];
6755 frame.size = [cancel_ sizeThatFits:frame.size];
6756 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6757 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6758 [cancel_ setFrame:frame];
6760 CGSize prgsize = {75, 100};
6762 [self frame].size.width - prgsize.width - 10,
6763 ([self frame].size.height - prgsize.height) / 2
6765 [progress_ setFrame:prgrect];
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 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6810 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6811 [(UIProgressBar *) progress_ setStyle:0];
6812 [self addSubview:progress_];
6814 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6815 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6816 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6817 [cancel_ setBarStyle:barstyle];
6819 [self positionViews];
6823 - (void) setCancellable:(bool)cancellable {
6825 [self addSubview:cancel_];
6827 [cancel_ removeFromSuperview];
6831 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6832 [progress_ setProgress:0];
6836 [self setCancellable:NO];
6839 - (void) setPrompt:(NSString *)prompt {
6840 [prompt_ setText:prompt];
6843 - (void) setProgress:(float)progress {
6844 [progress_ setProgress:progress];
6850 /* Cydia Navigation Controller Interface {{{ */
6851 @interface UINavigationController (Cydia)
6853 - (NSArray *) navigationURLCollection;
6854 - (void) unloadData;
6859 /* Cydia Tab Bar Controller {{{ */
6860 @interface CYTabBarController : UITabBarController <
6861 UITabBarControllerDelegate,
6864 _transient Database *database_;
6865 _H<RefreshBar, 1> refreshbar_;
6869 // XXX: ok, "updatedelegate_"?...
6870 _transient NSObject<CydiaDelegate> *updatedelegate_;
6872 _H<UIViewController> remembered_;
6873 _transient UIViewController *transient_;
6876 - (NSArray *) navigationURLCollection;
6877 - (void) dropBar:(BOOL)animated;
6878 - (void) beginUpdate;
6879 - (void) raiseBar:(BOOL)animated;
6881 - (void) unloadData;
6885 @implementation CYTabBarController
6887 - (void) didReceiveMemoryWarning {
6888 [super didReceiveMemoryWarning];
6890 // presenting a UINavigationController on 2.x does not update its transitionView
6891 // it thereby will not allow its topViewController to be unloaded by memory pressure
6892 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6893 UIViewController *selected([self selectedViewController]);
6894 for (UINavigationController *controller in [self viewControllers])
6895 if (controller != selected)
6896 if (UIViewController *top = [controller topViewController])
6901 - (void) setUnselectedViewController:(UIViewController *)transient {
6902 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6903 if (transient != nil) {
6904 [[[self viewControllers] objectAtIndex:0] pushViewController:transient animated:YES];
6905 [self setSelectedIndex:0];
6909 NSMutableArray *controllers = [[[self viewControllers] mutableCopy] autorelease];
6910 if (transient != nil) {
6911 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
6912 [navigation setViewControllers:[NSArray arrayWithObject:transient]];
6913 transient = navigation;
6915 if (transient_ == nil)
6916 remembered_ = [controllers objectAtIndex:0];
6917 transient_ = transient;
6918 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6919 [controllers replaceObjectAtIndex:0 withObject:transient_];
6920 [self setSelectedIndex:0];
6921 [self setViewControllers:controllers];
6922 [self concealTabBarSelection];
6923 } else if (remembered_ != nil) {
6924 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6925 transient_ = transient;
6926 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6928 [self setViewControllers:controllers];
6929 [self revealTabBarSelection];
6933 - (UIViewController *) unselectedViewController {
6937 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6938 if ([self unselectedViewController])
6939 [self setUnselectedViewController:nil];
6941 // presenting a UINavigationController on 2.x does not update its transitionView
6942 // if this view was unloaded, the tranitionView may currently be presenting nothing
6943 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6944 UINavigationController *navigation((UINavigationController *) viewController);
6945 [navigation pushViewController:[[[UIViewController alloc] init] autorelease] animated:NO];
6946 [navigation popViewControllerAnimated:NO];
6950 - (NSArray *) navigationURLCollection {
6951 NSMutableArray *items([NSMutableArray array]);
6953 // XXX: Should this deal with transient view controllers?
6954 for (id navigation in [self viewControllers]) {
6955 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6957 [items addObject:stack];
6963 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6964 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6965 [self setUnselectedViewController:nil];
6967 [super dismissModalViewControllerAnimated:YES];
6970 - (void) unloadData {
6973 for (UINavigationController *controller in [self viewControllers])
6974 [controller unloadData];
6976 if (UIViewController *selected = [self selectedViewController])
6977 [selected reloadData];
6979 if (UIViewController *unselected = [self unselectedViewController]) {
6980 [unselected unloadData];
6981 [unselected reloadData];
6986 [[NSNotificationCenter defaultCenter] removeObserver:self];
6991 - (id) initWithDatabase:(Database *)database {
6992 if ((self = [super init]) != nil) {
6993 database_ = database;
6994 [self setDelegate:self];
6996 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6997 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6999 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
7003 - (void) setUpdate:(NSDate *)date {
7007 - (void) beginUpdate {
7008 [(RefreshBar *) refreshbar_ start];
7011 [updatedelegate_ retainNetworkActivityIndicator];
7015 detachNewThreadSelector:@selector(performUpdate)
7021 - (void) performUpdate {
7022 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7025 status.setDelegate(self);
7026 [database_ updateWithStatus:status];
7029 performSelectorOnMainThread:@selector(completeUpdate)
7037 - (void) stopUpdateWithSelector:(SEL)selector {
7039 [updatedelegate_ releaseNetworkActivityIndicator];
7041 [self raiseBar:YES];
7044 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7047 - (void) completeUpdate {
7050 [self stopUpdateWithSelector:@selector(reloadData)];
7053 - (void) cancelUpdate {
7054 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7057 - (void) cancelPressed {
7058 [self cancelUpdate];
7065 - (void) addProgressEvent:(CydiaProgressEvent *)event {
7066 [refreshbar_ setPrompt:[event compoundMessage]];
7069 - (bool) isProgressCancelled {
7073 - (void) setProgressCancellable:(NSNumber *)cancellable {
7074 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
7077 - (void) setProgressPercent:(NSNumber *)percent {
7078 [refreshbar_ setProgress:[percent floatValue]];
7081 - (void) setProgressStatus:(NSDictionary *)status {
7083 [self setProgressPercent:[status objectForKey:@"Percent"]];
7086 - (void) setUpdateDelegate:(id)delegate {
7087 updatedelegate_ = delegate;
7090 - (UIView *) transitionView {
7091 if ([self respondsToSelector:@selector(_transitionView)])
7092 return [self _transitionView];
7094 return MSHookIvar<id>(self, "_viewControllerTransitionView");
7097 - (void) dropBar:(BOOL)animated {
7102 UIView *transition([self transitionView]);
7103 [[self view] addSubview:refreshbar_];
7105 CGRect barframe([refreshbar_ frame]);
7107 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
7108 barframe.origin.y = CYStatusBarHeight();
7110 barframe.origin.y = 0;
7112 [refreshbar_ setFrame:barframe];
7115 [UIView beginAnimations:nil context:NULL];
7117 CGRect viewframe = [transition frame];
7118 viewframe.origin.y += barframe.size.height;
7119 viewframe.size.height -= barframe.size.height;
7120 [transition setFrame:viewframe];
7123 [UIView commitAnimations];
7125 // Ensure bar has the proper width for our view, it might have changed
7126 barframe.size.width = viewframe.size.width;
7127 [refreshbar_ setFrame:barframe];
7130 - (void) raiseBar:(BOOL)animated {
7135 UIView *transition([self transitionView]);
7136 [refreshbar_ removeFromSuperview];
7138 CGRect barframe([refreshbar_ frame]);
7141 [UIView beginAnimations:nil context:NULL];
7143 CGRect viewframe = [transition frame];
7144 viewframe.origin.y -= barframe.size.height;
7145 viewframe.size.height += barframe.size.height;
7146 [transition setFrame:viewframe];
7149 [UIView commitAnimations];
7152 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7153 bool dropped(dropped_);
7158 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7164 - (void) statusBarFrameChanged:(NSNotification *)notification {
7174 /* Cydia Navigation Controller Implementation {{{ */
7175 @implementation UINavigationController (Cydia)
7177 - (NSArray *) navigationURLCollection {
7178 NSMutableArray *stack([NSMutableArray array]);
7180 for (CyteViewController *controller in [self viewControllers]) {
7181 NSString *url = [[controller navigationURL] absoluteString];
7183 [stack addObject:url];
7189 - (void) reloadData {
7192 UIViewController *visible([self visibleViewController]);
7194 [visible reloadData];
7196 // on the iPad, this view controller is ALSO visible. :(
7198 if (UIViewController *top = [self topViewController])
7203 - (void) unloadData {
7204 for (CyteViewController *page in [self viewControllers])
7213 /* Cydia:// Protocol {{{ */
7214 @interface CydiaURLProtocol : NSURLProtocol {
7219 @implementation CydiaURLProtocol
7221 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7222 NSURL *url([request URL]);
7226 NSString *scheme([[url scheme] lowercaseString]);
7227 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7229 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7235 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7239 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7240 id<NSURLProtocolClient> client([self client]);
7242 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7244 NSData *data(UIImagePNGRepresentation(icon));
7246 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7247 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7248 [client URLProtocol:self didLoadData:data];
7249 [client URLProtocolDidFinishLoading:self];
7253 - (void) startLoading {
7254 id<NSURLProtocolClient> client([self client]);
7255 NSURLRequest *request([self request]);
7257 NSURL *url([request URL]);
7258 NSString *href([url absoluteString]);
7259 NSString *scheme([[url scheme] lowercaseString]);
7263 if ([scheme isEqualToString:@"cydia"])
7264 path = [href substringFromIndex:8];
7265 else if ([scheme isEqualToString:@"about"])
7266 path = [href substringFromIndex:12];
7267 else _assert(false);
7269 NSRange slash([path rangeOfString:@"/"]);
7272 if (slash.location == NSNotFound) {
7276 command = [path substringToIndex:slash.location];
7277 path = [path substringFromIndex:(slash.location + 1)];
7280 Database *database([Database sharedInstance]);
7282 if ([command isEqualToString:@"package-icon"]) {
7285 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7286 Package *package([database packageWithName:path]);
7290 UIImage *icon([package icon]);
7291 [self _returnPNGWithImage:icon forRequest:request];
7292 } else if ([command isEqualToString:@"uikit-image"]) {
7295 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7296 UIImage *icon(_UIImageWithName(path));
7297 [self _returnPNGWithImage:icon forRequest:request];
7298 } else if ([command isEqualToString:@"section-icon"]) {
7301 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7302 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7304 icon = [UIImage applicationImageNamed:@"unknown.png"];
7305 [self _returnPNGWithImage:icon forRequest:request];
7307 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7311 - (void) stopLoading {
7317 /* Section Controller {{{ */
7318 @interface SectionController : FilteredPackageListController {
7319 _H<IndirectDelegate, 1> indirect_;
7320 _H<CydiaObject> cydia_;
7321 _H<NSString> section_;
7322 std::vector< _H<CyteWebViewTableViewCell, 1> > promoted_;
7325 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7329 @implementation SectionController
7331 - (NSURL *) referrerURL {
7332 NSString *name = section_;
7336 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@", UI_, [name stringByAddingPercentEscapesIncludingReserved]]];
7339 - (NSURL *) navigationURL {
7340 NSString *name = section_;
7344 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", [name stringByAddingPercentEscapesIncludingReserved]]];
7347 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7350 title = UCLocalize("ALL_PACKAGES");
7351 else if (![name isEqual:@""])
7352 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7354 title = UCLocalize("NO_SECTION");
7356 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7357 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7358 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7363 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7364 return [super numberOfSectionsInTableView:list] + 1;
7367 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7368 return section == 0 ? nil : [super tableView:list titleForHeaderInSection:(section - 1)];
7371 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7372 return section == 0 ? promoted_.size() : [super tableView:list numberOfRowsInSection:(section - 1)];
7375 + (NSIndexPath *) adjustedIndexPath:(NSIndexPath *)path {
7376 return [NSIndexPath indexPathForRow:[path row] inSection:([path section] - 1)];
7379 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7380 if ([path section] != 0)
7381 return [super tableView:table cellForRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7383 return promoted_[[path row]];
7386 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
7387 if ([path section] != 0)
7388 return [super tableView:table didSelectRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7391 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
7392 NSInteger section([super tableView:tableView sectionForSectionIndexTitle:title atIndex:index]);
7393 return section == 0 ? 0 : section + 1;
7396 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7397 NSURL *url([request URL]);
7401 if ([frame isEqualToString:@"_open"])
7402 [delegate_ openURL:url];
7404 WebFrame *frame(nil);
7405 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7406 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7408 frame = [view mainFrame];
7410 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7412 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7413 [controller setDelegate:delegate_];
7414 [[self navigationController] pushViewController:controller animated:YES];
7420 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7421 return [CydiaWebViewController requestWithHeaders:request];
7424 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7425 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7431 // XXX: this code is horrible. I mean, wtf Jay?
7432 if (ShowPromoted_ && [[Metadata_ objectForKey:@"ShowPromoted"] boolValue]) {
7433 promoted_.resize(1);
7435 for (unsigned i(0); i != promoted_.size(); ++i) {
7436 CyteWebViewTableViewCell *promoted([CyteWebViewTableViewCell cellWithRequest:[NSURLRequest
7437 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sectionhead/%u/%@",
7438 UI_, i, section_ == nil ? @"" : [section_ stringByAddingPercentEscapesIncludingReserved]]
7441 cachePolicy:NSURLRequestUseProtocolCachePolicy
7445 [promoted setDelegate:self];
7446 promoted_[i] = promoted;
7451 - (void) setDelegate:(id)delegate {
7452 [super setDelegate:delegate];
7453 [cydia_ setDelegate:delegate];
7456 - (void) releaseSubviews {
7458 [super releaseSubviews];
7463 /* Sections Controller {{{ */
7464 @interface SectionsController : CyteViewController <
7465 UITableViewDataSource,
7468 _transient Database *database_;
7469 _H<NSMutableArray> sections_;
7470 _H<NSMutableArray> filtered_;
7471 _H<UITableView, 2> list_;
7474 - (id) initWithDatabase:(Database *)database;
7475 - (void) editButtonClicked;
7479 @implementation SectionsController
7481 - (NSURL *) navigationURL {
7482 return [NSURL URLWithString:@"cydia://sections"];
7485 - (void) updateNavigationItem {
7486 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7487 if ([sections_ count] == 0) {
7488 [[self navigationItem] setRightBarButtonItem:nil];
7490 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7491 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7493 action:@selector(editButtonClicked)
7494 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7498 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7499 [super setEditing:editing animated:animated];
7504 [delegate_ updateData];
7506 [self updateNavigationItem];
7509 - (void) viewDidAppear:(BOOL)animated {
7510 [super viewDidAppear:animated];
7511 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7514 - (void) viewWillDisappear:(BOOL)animated {
7515 [super viewWillDisappear:animated];
7516 [self setEditing:NO];
7519 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7520 Section *section = nil;
7521 int index = [indexPath row];
7522 if (![self isEditing]) {
7525 section = [filtered_ objectAtIndex:index];
7527 section = [sections_ objectAtIndex:index];
7532 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7533 if ([self isEditing])
7534 return [sections_ count];
7536 return [filtered_ count] + 1;
7539 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7543 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7544 static NSString *reuseIdentifier = @"SectionCell";
7546 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7548 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7550 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7555 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7556 if ([self isEditing])
7559 Section *section = [self sectionAtIndexPath:indexPath];
7561 SectionController *controller = [[[SectionController alloc]
7562 initWithDatabase:database_
7563 section:[section name]
7565 [controller setDelegate:delegate_];
7567 [[self navigationController] pushViewController:controller animated:YES];
7571 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7572 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7573 [list_ setRowHeight:45.0f];
7574 [(UITableView *) list_ setDataSource:self];
7575 [list_ setDelegate:self];
7576 [self setView:list_];
7579 - (void) viewDidLoad {
7580 [super viewDidLoad];
7582 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7585 - (void) releaseSubviews {
7591 [super releaseSubviews];
7594 - (id) initWithDatabase:(Database *)database {
7595 if ((self = [super init]) != nil) {
7596 database_ = database;
7600 - (void) reloadData {
7603 NSArray *packages = [database_ packages];
7605 sections_ = [NSMutableArray arrayWithCapacity:16];
7606 filtered_ = [NSMutableArray arrayWithCapacity:16];
7608 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7611 for (Package *package in packages) {
7612 NSString *name([package section]);
7613 NSString *key(name == nil ? @"" : name);
7617 _profile(SectionsView$reloadData$Section)
7618 section = [sections objectForKey:key];
7619 if (section == nil) {
7620 _profile(SectionsView$reloadData$Section$Allocate)
7621 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7622 [sections setObject:section forKey:key];
7627 [section addToCount];
7629 _profile(SectionsView$reloadData$Filter)
7630 if (![package valid] || ![package visible])
7638 [sections_ addObjectsFromArray:[sections allValues]];
7640 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7642 for (Section *section in (id) sections_) {
7643 size_t count([section row]);
7647 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7648 [section setCount:count];
7649 [filtered_ addObject:section];
7652 [self updateNavigationItem];
7657 - (void) editButtonClicked {
7658 [self setEditing:![self isEditing] animated:YES];
7664 /* Changes Controller {{{ */
7665 @interface ChangesController : CyteViewController <
7666 CyteWebViewDelegate,
7667 UITableViewDataSource,
7670 _transient Database *database_;
7672 _H<NSMutableArray> packages_;
7673 _H<NSMutableArray> sections_;
7674 _H<UITableView, 2> list_;
7675 _H<CyteWebView, 1> dickbar_;
7677 _H<IndirectDelegate, 1> indirect_;
7678 _H<CydiaObject> cydia_;
7681 - (id) initWithDatabase:(Database *)database;
7685 @implementation ChangesController
7687 - (NSURL *) navigationURL {
7688 return [NSURL URLWithString:@"cydia://changes"];
7691 - (void) viewDidAppear:(BOOL)animated {
7692 [super viewDidAppear:animated];
7693 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7696 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7697 NSInteger count([sections_ count]);
7698 return count == 0 ? 1 : count;
7701 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7702 if ([sections_ count] == 0)
7704 return [[sections_ objectAtIndex:section] name];
7707 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7708 if ([sections_ count] == 0)
7710 return [[sections_ objectAtIndex:section] count];
7713 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7714 @synchronized (database_) {
7715 if ([database_ era] != era_)
7718 NSUInteger sectionIndex([path section]);
7719 if (sectionIndex >= [sections_ count])
7721 Section *section([sections_ objectAtIndex:sectionIndex]);
7722 NSInteger row([path row]);
7723 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7726 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7727 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7729 cell = [[[PackageCell alloc] init] autorelease];
7731 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7732 [cell setPackage:package asSummary:false];
7736 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7737 Package *package([self packageAtIndexPath:path]);
7738 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[NSString stringWithFormat:@"%@/#!/changes/", UI_]] autorelease]);
7739 [view setDelegate:delegate_];
7740 [[self navigationController] pushViewController:view animated:YES];
7744 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7745 NSString *context([alert context]);
7747 if ([context isEqualToString:@"norefresh"])
7748 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7751 - (void) refreshButtonClicked {
7752 if (IsReachable("cydia.saurik.com")) {
7753 [delegate_ beginUpdate];
7754 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7756 UIAlertView *alert = [[[UIAlertView alloc]
7757 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
7758 message:@"Host Unreachable" // XXX: Localize
7760 cancelButtonTitle:UCLocalize("OK")
7761 otherButtonTitles:nil
7764 [alert setContext:@"norefresh"];
7769 - (void) upgradeButtonClicked {
7770 [delegate_ distUpgrade];
7771 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7775 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7776 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7777 [self setView:view];
7779 list_ = [[[UITableView alloc] initWithFrame:[view bounds] style:UITableViewStylePlain] autorelease];
7780 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7781 [list_ setRowHeight:73];
7782 [(UITableView *) list_ setDataSource:self];
7783 [list_ setDelegate:self];
7784 [view addSubview:list_];
7786 if (AprilFools_ && kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
7787 CGRect dickframe([view bounds]);
7788 dickframe.size.height = 44;
7790 dickbar_ = [[[CyteWebView alloc] initWithFrame:dickframe] autorelease];
7791 [dickbar_ setDelegate:self];
7792 [view addSubview:dickbar_];
7794 [dickbar_ setBackgroundColor:[UIColor clearColor]];
7795 [dickbar_ setScalesPageToFit:YES];
7797 UIWebDocumentView *document([dickbar_ _documentView]);
7798 [document setBackgroundColor:[UIColor clearColor]];
7799 [document setDrawsBackground:NO];
7801 WebView *webview([document webView]);
7802 [webview setShouldUpdateWhileOffscreen:NO];
7804 UIScrollView *scroller([dickbar_ scrollView]);
7805 [scroller setScrollingEnabled:NO];
7806 [scroller setFixedBackgroundPattern:YES];
7807 [scroller setBackgroundColor:[UIColor clearColor]];
7809 WebPreferences *preferences([webview preferences]);
7810 [preferences setCacheModel:WebCacheModelDocumentBrowser];
7811 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
7812 [preferences setOfflineWebApplicationCacheEnabled:YES];
7814 [dickbar_ loadRequest:[NSURLRequest
7815 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/dickbar/", UI_]]]
7816 cachePolicy:NSURLRequestUseProtocolCachePolicy
7820 UIEdgeInsets inset = {44, 0, 0, 0};
7821 [list_ setContentInset:inset];
7823 [dickbar_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7827 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7828 NSURL *url([request URL]);
7832 if ([frame isEqualToString:@"_open"])
7833 [delegate_ openURL:url];
7835 WebFrame *frame(nil);
7836 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7837 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7839 frame = [view mainFrame];
7841 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7843 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7844 [controller setDelegate:delegate_];
7845 [[self navigationController] pushViewController:controller animated:YES];
7851 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7852 return [CydiaWebViewController requestWithHeaders:request];
7855 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7856 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7859 - (void) setDelegate:(id)delegate {
7860 [super setDelegate:delegate];
7861 [cydia_ setDelegate:delegate];
7864 - (void) viewDidLoad {
7865 [super viewDidLoad];
7867 [[self navigationItem] setTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES"))];
7870 - (void) releaseSubviews {
7877 [super releaseSubviews];
7880 - (id) initWithDatabase:(Database *)database {
7881 if ((self = [super init]) != nil) {
7882 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7883 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7884 database_ = database;
7888 - (NSMutableArray *) _reloadPackages {
7889 @synchronized (database_) {
7890 era_ = [database_ era];
7891 NSArray *packages([database_ packages]);
7893 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7896 _profile(ChangesController$_reloadPackages$Filter)
7897 for (Package *package in packages)
7898 if ([package upgradableAndEssential:YES] || [package visible])
7899 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7902 _profile(ChangesController$_reloadPackages$radixSort)
7903 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7910 - (void) _reloadData {
7911 NSMutableArray *packages;
7915 UIProgressHUD *hud([delegate_ addProgressHUD]);
7916 [hud setText:UCLocalize("LOADING")];
7917 //NSLog(@"HUD:%@::%@", delegate_, hud);
7918 packages = [self yieldToSelector:@selector(_reloadPackages)];
7919 [delegate_ removeProgressHUD:hud];
7921 packages = [self _reloadPackages];
7924 @synchronized (database_) {
7925 if (era_ != [database_ era])
7928 packages_ = packages;
7929 sections_ = [NSMutableArray arrayWithCapacity:16];
7931 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7932 Section *ignored = nil;
7933 Section *section = nil;
7937 bool unseens = false;
7939 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7941 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7942 Package *package = [packages_ objectAtIndex:offset];
7944 BOOL uae = [package upgradableAndEssential:YES];
7948 time_t seen([package seen]);
7950 if (section == nil || last != seen) {
7954 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7957 _profile(ChangesController$reloadData$Allocate)
7958 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7959 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7960 [sections_ addObject:section];
7964 [section addToCount];
7965 } else if ([package ignored]) {
7966 if (ignored == nil) {
7967 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7969 [ignored addToCount];
7972 [upgradable addToCount];
7977 CFRelease(formatter);
7980 Section *last = [sections_ lastObject];
7981 size_t count = [last count];
7982 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7983 [sections_ removeLastObject];
7986 if ([ignored count] != 0)
7987 [sections_ insertObject:ignored atIndex:0];
7989 [sections_ insertObject:upgradable atIndex:0];
7993 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7994 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7995 style:UIBarButtonItemStylePlain
7997 action:@selector(upgradeButtonClicked)
7998 ] autorelease]) animated:YES];
8000 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
8001 initWithTitle:UCLocalize("REFRESH")
8002 style:UIBarButtonItemStylePlain
8004 action:@selector(refreshButtonClicked)
8005 ] autorelease]) animated:YES];
8010 - (void) reloadData {
8012 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
8017 /* Search Controller {{{ */
8018 @interface SearchController : FilteredPackageListController <
8021 _H<UISearchBar, 1> search_;
8025 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
8026 - (void) reloadData;
8030 @implementation SearchController
8032 - (NSURL *) referrerURL {
8033 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
8036 - (NSURL *) navigationURL {
8037 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
8038 return [NSURL URLWithString:@"cydia://search"];
8040 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
8043 - (NSArray *) termsForQuery:(NSString *)query {
8044 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
8045 for (NSString *component in [query componentsSeparatedByString:@" "])
8046 if ([component length] != 0)
8047 [terms addObject:component];
8052 - (void) useSearch {
8053 [self setObject:[self termsForQuery:[search_ text]] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
8058 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
8059 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8064 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
8065 [search_ resignFirstResponder];
8069 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
8070 [search_ setText:@""];
8071 [self searchBarButtonClicked:searchBar];
8074 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
8075 [self searchBarButtonClicked:searchBar];
8078 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
8079 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8083 - (bool) shouldYield {
8087 - (bool) shouldBlock {
8088 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
8091 - (bool) isSummarized {
8092 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
8095 - (bool) showsSections {
8099 - (NSMutableArray *) _reloadPackages {
8100 NSMutableArray *packages([super _reloadPackages]);
8101 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8102 [packages radixSortUsingSelector:@selector(rank)];
8106 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
8107 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[self termsForQuery:query]])) {
8108 search_ = [[[UISearchBar alloc] init] autorelease];
8109 [search_ setDelegate:self];
8112 [search_ setText:query];
8116 - (void) viewDidAppear:(BOOL)animated {
8117 [super viewDidAppear:animated];
8119 if (!searchloaded_) {
8120 searchloaded_ = YES;
8121 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
8122 [search_ layoutSubviews];
8123 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
8125 UITextField *textField;
8126 if ([search_ respondsToSelector:@selector(searchField)])
8127 textField = [search_ searchField];
8129 textField = MSHookIvar<UITextField *>(search_, "_searchField");
8131 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8132 [textField setEnablesReturnKeyAutomatically:NO];
8133 [[self navigationItem] setTitleView:textField];
8136 if ([self isSummarized])
8137 [search_ becomeFirstResponder];
8140 - (void) reloadData {
8141 id object([search_ text]);
8142 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8143 object = [self termsForQuery:object];
8145 [self setObject:object];
8151 - (void) didSelectPackage:(Package *)package {
8152 [search_ resignFirstResponder];
8153 [super didSelectPackage:package];
8158 /* Package Settings Controller {{{ */
8159 @interface PackageSettingsController : CyteViewController <
8160 UITableViewDataSource,
8163 _transient Database *database_;
8165 _H<Package> package_;
8166 _H<UITableView, 2> table_;
8167 _H<UISwitch> subscribedSwitch_;
8168 _H<UISwitch> ignoredSwitch_;
8169 _H<UITableViewCell> subscribedCell_;
8170 _H<UITableViewCell> ignoredCell_;
8173 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
8177 @implementation PackageSettingsController
8179 - (NSURL *) navigationURL {
8180 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
8183 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8184 if (package_ == nil)
8187 if ([package_ installed] == nil)
8193 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8194 if (package_ == nil)
8197 // both sections contain just one item right now.
8201 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8205 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8207 return UCLocalize("SHOW_ALL_CHANGES_EX");
8209 return UCLocalize("IGNORE_UPGRADES_EX");
8212 - (void) onSubscribed:(id)control {
8213 bool value([control isOn]);
8214 if (package_ == nil)
8216 if ([package_ setSubscribed:value])
8217 [delegate_ updateData];
8220 - (void) _updateIgnored {
8221 const char *package([name_ UTF8String]);
8222 bool on([ignoredSwitch_ isOn]);
8224 pid_t pid(ExecFork());
8226 FILE *dpkg(popen("dpkg --set-selections", "w"));
8227 fwrite(package, strlen(package), 1, dpkg);
8230 fwrite(" hold\n", 6, 1, dpkg);
8232 fwrite(" install\n", 9, 1, dpkg);
8243 - (void) onIgnored:(id)control {
8244 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8245 [invocation setTarget:self];
8246 [invocation setSelector:@selector(_updateIgnored)];
8248 [delegate_ reloadDataWithInvocation:invocation];
8251 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8252 if (package_ == nil)
8255 switch ([indexPath section]) {
8256 case 0: return subscribedCell_;
8257 case 1: return ignoredCell_;
8266 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8267 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8268 [self setView:view];
8270 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8271 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8272 [(UITableView *) table_ setDataSource:self];
8273 [table_ setDelegate:self];
8274 [view addSubview:table_];
8276 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8277 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8278 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8280 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8281 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8282 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8284 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8285 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8286 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8287 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8289 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8290 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8291 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8292 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8295 - (void) viewDidLoad {
8296 [super viewDidLoad];
8298 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8301 - (void) releaseSubviews {
8303 subscribedCell_ = nil;
8305 ignoredSwitch_ = nil;
8306 subscribedSwitch_ = nil;
8308 [super releaseSubviews];
8311 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8312 if ((self = [super init]) != nil) {
8313 database_ = database;
8318 - (void) reloadData {
8321 package_ = [database_ packageWithName:name_];
8323 if (package_ != nil) {
8324 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8325 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8326 } // XXX: what now, G?
8328 [table_ reloadData];
8334 /* Installed Controller {{{ */
8335 @interface InstalledController : FilteredPackageListController {
8339 - (id) initWithDatabase:(Database *)database;
8341 - (void) updateRoleButton;
8342 - (void) queueStatusDidChange;
8346 @implementation InstalledController
8348 - (NSURL *) referrerURL {
8349 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8352 - (NSURL *) navigationURL {
8353 return [NSURL URLWithString:@"cydia://installed"];
8356 - (id) initWithDatabase:(Database *)database {
8357 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8358 [self updateRoleButton];
8359 [self queueStatusDidChange];
8364 - (void) queueButtonClicked {
8369 - (void) queueStatusDidChange {
8373 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8374 initWithTitle:UCLocalize("QUEUE")
8375 style:UIBarButtonItemStyleDone
8377 action:@selector(queueButtonClicked)
8380 [[self navigationItem] setLeftBarButtonItem:nil];
8386 - (void) updateRoleButton {
8387 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8388 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8389 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8390 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8392 action:@selector(roleButtonClicked)
8396 - (void) roleButtonClicked {
8397 [self setObject:[NSNumber numberWithBool:expert_]];
8401 [self updateRoleButton];
8407 /* Source Cell {{{ */
8408 @interface SourceCell : CyteTableViewCell <
8409 CyteTableViewCellDelegate
8413 _H<NSString> origin_;
8414 _H<NSString> label_;
8417 - (void) setSource:(Source *)source;
8421 @implementation SourceCell
8423 - (void) _setImage:(NSArray *)data {
8424 if ([url_ isEqual:[data objectAtIndex:0]]) {
8425 icon_ = [data objectAtIndex:1];
8426 [content_ setNeedsDisplay];
8430 - (void) _setSource:(NSURL *) url {
8431 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8433 if (NSData *data = [NSURLConnection
8434 sendSynchronousRequest:[NSURLRequest
8436 cachePolicy:NSURLRequestUseProtocolCachePolicy
8440 returningResponse:NULL
8443 if (UIImage *image = [UIImage imageWithData:data])
8444 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8449 - (void) setSource:(Source *)source {
8450 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8452 origin_ = [source name];
8453 label_ = [source rooturi];
8455 [content_ setNeedsDisplay];
8457 url_ = [source iconURL];
8458 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8461 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8462 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8463 UIView *content([self contentView]);
8464 CGRect bounds([content bounds]);
8466 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8467 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8468 [content_ setBackgroundColor:[UIColor whiteColor]];
8469 [content addSubview:content_];
8471 [content_ setDelegate:self];
8472 [content_ setOpaque:YES];
8474 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8478 - (NSString *) accessibilityLabel {
8482 - (void) drawContentRect:(CGRect)rect {
8483 bool highlighted(highlighted_);
8484 float width(rect.size.width);
8488 rect.size = [(UIImage *) icon_ size];
8490 while (rect.size.width > 32 || rect.size.height > 32) {
8491 rect.size.width /= 2;
8492 rect.size.height /= 2;
8495 rect.origin.x = 25 - rect.size.width / 2;
8496 rect.origin.y = 25 - rect.size.height / 2;
8498 [icon_ drawInRect:rect];
8506 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 65) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8510 [label_ drawAtPoint:CGPointMake(48, 29) forWidth:(width - 65) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8515 /* Source Controller {{{ */
8516 @interface SourceController : FilteredPackageListController {
8517 _transient Source *source_;
8521 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8525 @implementation SourceController
8527 - (NSURL *) referrerURL {
8528 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sources/%@", UI_, [key_ stringByAddingPercentEscapesIncludingReserved]]];
8531 - (NSURL *) navigationURL {
8532 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8535 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8536 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8538 key_ = [source key];
8542 - (void) reloadData {
8543 source_ = [database_ sourceWithKey:key_];
8544 key_ = [source_ key];
8545 [self setObject:source_];
8547 [[self navigationItem] setTitle:[source_ label]];
8554 /* Sources Controller {{{ */
8555 @interface SourcesController : CyteViewController <
8556 UITableViewDataSource,
8559 _transient Database *database_;
8562 _H<UITableView, 2> list_;
8563 _H<NSMutableArray> sources_;
8567 _H<UIProgressHUD> hud_;
8570 //NSURLConnection *installer_;
8571 NSURLConnection *trivial_;
8572 NSURLConnection *trivial_bz2_;
8573 NSURLConnection *trivial_gz_;
8574 //NSURLConnection *automatic_;
8579 - (id) initWithDatabase:(Database *)database;
8580 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8584 @implementation SourcesController
8586 - (void) _releaseConnection:(NSURLConnection *)connection {
8587 if (connection != nil) {
8588 [connection cancel];
8589 //[connection setDelegate:nil];
8590 [connection release];
8595 //[self _releaseConnection:installer_];
8596 [self _releaseConnection:trivial_];
8597 [self _releaseConnection:trivial_gz_];
8598 [self _releaseConnection:trivial_bz2_];
8599 //[self _releaseConnection:automatic_];
8604 - (NSURL *) navigationURL {
8605 return [NSURL URLWithString:@"cydia://sources"];
8608 - (void) viewDidAppear:(BOOL)animated {
8609 [super viewDidAppear:animated];
8610 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8613 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8617 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8621 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8622 return [sources_ count];
8625 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8626 @synchronized (database_) {
8627 if ([database_ era] != era_)
8630 NSUInteger index([indexPath row]);
8631 return index < [sources_ count] ? [sources_ objectAtIndex:index] : nil;
8634 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8635 static NSString *cellIdentifier = @"SourceCell";
8637 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8638 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8639 [cell setSource:[self sourceAtIndexPath:indexPath]];
8640 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8645 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8646 Source *source = [self sourceAtIndexPath:indexPath];
8647 if (source == nil) return;
8649 SourceController *controller = [[[SourceController alloc]
8650 initWithDatabase:database_
8654 [controller setDelegate:delegate_];
8656 [[self navigationController] pushViewController:controller animated:YES];
8659 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8660 Source *source = [self sourceAtIndexPath:indexPath];
8661 return [source record] != nil;
8664 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8665 if (editingStyle == UITableViewCellEditingStyleDelete) {
8666 Source *source = [self sourceAtIndexPath:indexPath];
8667 if (source == nil) return;
8669 [Sources_ removeObjectForKey:[source key]];
8670 [delegate_ _saveConfig];
8671 [delegate_ reloadDataWithInvocation:nil];
8676 [delegate_ addTrivialSource:href_];
8679 [delegate_ syncData];
8682 - (NSString *) getWarning {
8683 NSString *href(href_);
8684 NSRange colon([href rangeOfString:@"://"]);
8685 if (colon.location != NSNotFound)
8686 href = [href substringFromIndex:(colon.location + 3)];
8687 href = [href stringByAddingPercentEscapes];
8688 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8690 NSURL *url([NSURL URLWithString:href]);
8692 NSStringEncoding encoding;
8693 NSError *error(nil);
8695 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8696 return [warning length] == 0 ? nil : warning;
8700 - (void) _endConnection:(NSURLConnection *)connection {
8701 // XXX: the memory management in this method is horribly awkward
8703 NSURLConnection **field = NULL;
8704 if (connection == trivial_)
8706 else if (connection == trivial_bz2_)
8707 field = &trivial_bz2_;
8708 else if (connection == trivial_gz_)
8709 field = &trivial_gz_;
8710 _assert(field != NULL);
8711 [connection release];
8716 trivial_bz2_ == nil &&
8719 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8721 [delegate_ releaseNetworkActivityIndicator];
8723 [delegate_ removeProgressHUD:hud_];
8727 if (warning != nil) {
8728 UIAlertView *alert = [[[UIAlertView alloc]
8729 initWithTitle:UCLocalize("SOURCE_WARNING")
8732 cancelButtonTitle:UCLocalize("CANCEL")
8734 UCLocalize("ADD_ANYWAY"),
8738 [alert setContext:@"warning"];
8739 [alert setNumberOfRows:1];
8742 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8748 } else if (error_ != nil) {
8749 UIAlertView *alert = [[[UIAlertView alloc]
8750 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8751 message:[error_ localizedDescription]
8753 cancelButtonTitle:UCLocalize("OK")
8754 otherButtonTitles:nil
8757 [alert setContext:@"urlerror"];
8762 UIAlertView *alert = [[[UIAlertView alloc]
8763 initWithTitle:UCLocalize("NOT_REPOSITORY")
8764 message:UCLocalize("NOT_REPOSITORY_EX")
8766 cancelButtonTitle:UCLocalize("OK")
8767 otherButtonTitles:nil
8770 [alert setContext:@"trivial"];
8780 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8781 switch ([response statusCode]) {
8787 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8788 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8790 [self _endConnection:connection];
8793 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8794 [self _endConnection:connection];
8797 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8798 NSURL *url([NSURL URLWithString:href]);
8800 NSMutableURLRequest *request = [NSMutableURLRequest
8802 cachePolicy:NSURLRequestUseProtocolCachePolicy
8806 [request setHTTPMethod:method];
8808 if (Machine_ != NULL)
8809 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8811 if (UniqueID_ != nil)
8812 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8814 if ([url isCydiaSecure]) {
8815 if (UniqueID_ != nil)
8816 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8819 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8822 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8823 NSString *context([alert context]);
8825 if ([context isEqualToString:@"source"]) {
8828 NSString *href = [[alert textField] text];
8830 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8832 if (![href hasSuffix:@"/"])
8833 href_ = [href stringByAppendingString:@"/"];
8837 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8838 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8839 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8840 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8844 // XXX: this is stupid
8845 hud_ = [delegate_ addProgressHUD];
8846 [hud_ setText:UCLocalize("VERIFYING_URL")];
8847 [delegate_ retainNetworkActivityIndicator];
8856 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8857 } else if ([context isEqualToString:@"trivial"])
8858 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8859 else if ([context isEqualToString:@"urlerror"])
8860 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8861 else if ([context isEqualToString:@"warning"]) {
8864 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8873 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8878 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8879 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8880 [list_ setRowHeight:53];
8881 [(UITableView *) list_ setDataSource:self];
8882 [list_ setDelegate:self];
8883 [self setView:list_];
8886 - (void) viewDidLoad {
8887 [super viewDidLoad];
8889 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8890 [self updateButtonsForEditingStatusAnimated:NO];
8893 - (void) viewWillAppear:(BOOL)animated {
8894 [super viewWillAppear:animated];
8896 [list_ setEditing:NO];
8897 [self updateButtonsForEditingStatusAnimated:NO];
8900 - (void) releaseSubviews {
8905 [super releaseSubviews];
8908 - (id) initWithDatabase:(Database *)database {
8909 if ((self = [super init]) != nil) {
8910 database_ = database;
8914 - (void) reloadData {
8917 @synchronized (database_) {
8918 era_ = [database_ era];
8920 sources_ = [NSMutableArray arrayWithCapacity:16];
8921 [sources_ addObjectsFromArray:[database_ sources]];
8923 [sources_ sortUsingSelector:@selector(compareByName:)];
8926 int count([sources_ count]);
8928 for (int i = 0; i != count; i++) {
8929 if ([[sources_ objectAtIndex:i] record] == nil)
8937 - (void) showAddSourcePrompt {
8938 UIAlertView *alert = [[[UIAlertView alloc]
8939 initWithTitle:UCLocalize("ENTER_APT_URL")
8942 cancelButtonTitle:UCLocalize("CANCEL")
8944 UCLocalize("ADD_SOURCE"),
8948 [alert setContext:@"source"];
8950 [alert setNumberOfRows:1];
8951 [alert addTextFieldWithValue:@"http://" label:@""];
8953 UITextInputTraits *traits = [[alert textField] textInputTraits];
8954 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8955 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8956 [traits setKeyboardType:UIKeyboardTypeURL];
8957 // XXX: UIReturnKeyDone
8958 [traits setReturnKeyType:UIReturnKeyNext];
8963 - (void) addButtonClicked {
8964 [self showAddSourcePrompt];
8967 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8968 BOOL editing([list_ isEditing]);
8970 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8971 initWithTitle:UCLocalize("ADD")
8972 style:UIBarButtonItemStylePlain
8974 action:@selector(addButtonClicked)
8975 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8977 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8978 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8979 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8981 action:@selector(editButtonClicked)
8982 ] autorelease] animated:animated];
8984 if (IsWildcat_ && !editing)
8985 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8986 initWithTitle:UCLocalize("SETTINGS")
8987 style:UIBarButtonItemStylePlain
8989 action:@selector(settingsButtonClicked)
8993 - (void) settingsButtonClicked {
8994 [delegate_ showSettings];
8997 - (void) editButtonClicked {
8998 [list_ setEditing:![list_ isEditing] animated:YES];
8999 [self updateButtonsForEditingStatusAnimated:YES];
9005 /* Settings Controller {{{ */
9006 @interface SettingsController : CyteViewController <
9007 UITableViewDataSource,
9010 _transient Database *database_;
9011 // XXX: ok, "roledelegate_"?...
9012 _transient id roledelegate_;
9013 _H<UITableView, 2> table_;
9014 _H<UISegmentedControl> segment_;
9015 _H<UIView> container_;
9018 - (void) showDoneButton;
9019 - (void) resizeSegmentedControl;
9023 @implementation SettingsController
9026 table_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
9027 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9028 [table_ setDelegate:self];
9029 [(UITableView *) table_ setDataSource:self];
9030 [self setView:table_];
9032 NSArray *items = [NSArray arrayWithObjects:
9034 UCLocalize("HACKER"),
9035 UCLocalize("DEVELOPER"),
9037 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
9038 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
9039 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
9040 [container_ addSubview:segment_];
9043 - (void) viewDidLoad {
9044 [super viewDidLoad];
9046 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
9049 if ([Role_ isEqualToString:@"User"]) index = 0;
9050 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
9051 if ([Role_ isEqualToString:@"Developer"]) index = 2;
9053 [segment_ setSelectedSegmentIndex:index];
9054 [self showDoneButton];
9057 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
9058 [self resizeSegmentedControl];
9061 - (void) releaseSubviews {
9066 [super releaseSubviews];
9069 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
9070 if ((self = [super init]) != nil) {
9071 database_ = database;
9072 roledelegate_ = delegate;
9076 - (void) resizeSegmentedControl {
9077 CGFloat width = [[self view] frame].size.width;
9078 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
9081 - (void) viewWillAppear:(BOOL)animated {
9082 [super viewWillAppear:animated];
9084 [self resizeSegmentedControl];
9087 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
9088 [self resizeSegmentedControl];
9091 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
9092 [self resizeSegmentedControl];
9096 NSString *role(nil);
9098 switch ([segment_ selectedSegmentIndex]) {
9099 case 0: role = @"User"; break;
9100 case 1: role = @"Hacker"; break;
9101 case 2: role = @"Developer"; break;
9106 if (![role isEqualToString:Role_]) {
9107 bool rolling(Role_ == nil);
9110 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
9114 [Metadata_ setObject:Settings_ forKey:@"Settings"];
9118 [roledelegate_ loadData];
9120 [roledelegate_ updateData];
9124 - (void) segmentChanged:(UISegmentedControl *)control {
9125 [self showDoneButton];
9128 - (void) saveAndClose {
9131 [[self navigationItem] setRightBarButtonItem:nil];
9132 [[self navigationController] dismissModalViewControllerAnimated:YES];
9135 - (void) doneButtonClicked {
9136 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
9137 [spinner startAnimating];
9138 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
9139 [[self navigationItem] setRightBarButtonItem:spinItem];
9141 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
9144 - (void) showDoneButton {
9145 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
9146 initWithTitle:UCLocalize("DONE")
9147 style:UIBarButtonItemStyleDone
9149 action:@selector(doneButtonClicked)
9150 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
9153 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
9154 // XXX: For not having a single cell in the table, this sure is a lot of sections.
9158 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
9162 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
9163 return nil; // This method is required by the protocol.
9166 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
9168 return UCLocalize("ROLE_EX");
9170 return [NSString stringWithFormat:
9171 @"%@: %@\n%@: %@\n%@: %@",
9172 UCLocalize("USER"), UCLocalize("USER_EX"),
9173 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
9174 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
9179 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
9180 return section == 3 ? 44.0f : 0;
9183 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
9184 return section == 3 ? container_ : nil;
9187 - (void) reloadData {
9190 [table_ reloadData];
9195 /* Stash Controller {{{ */
9196 @interface StashController : CyteViewController {
9197 _H<UIActivityIndicatorView> spinner_;
9198 _H<UILabel> status_;
9199 _H<UILabel> caption_;
9204 @implementation StashController
9207 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
9208 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
9209 [self setView:view];
9211 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
9213 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
9214 CGRect spinrect = [spinner_ frame];
9215 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
9216 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
9217 [spinner_ setFrame:spinrect];
9218 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
9219 [view addSubview:spinner_];
9220 [spinner_ startAnimating];
9223 captrect.size.width = [[self view] frame].size.width;
9224 captrect.size.height = 40.0f;
9225 captrect.origin.x = 0;
9226 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
9227 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
9228 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
9229 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9230 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
9231 [caption_ setTextColor:[UIColor whiteColor]];
9232 [caption_ setBackgroundColor:[UIColor clearColor]];
9233 [caption_ setShadowColor:[UIColor blackColor]];
9234 [caption_ setTextAlignment:UITextAlignmentCenter];
9235 [view addSubview:caption_];
9238 statusrect.size.width = [[self view] frame].size.width;
9239 statusrect.size.height = 30.0f;
9240 statusrect.origin.x = 0;
9241 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
9242 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
9243 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9244 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
9245 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
9246 [status_ setTextColor:[UIColor whiteColor]];
9247 [status_ setBackgroundColor:[UIColor clearColor]];
9248 [status_ setShadowColor:[UIColor blackColor]];
9249 [status_ setTextAlignment:UITextAlignmentCenter];
9250 [view addSubview:status_];
9253 - (void) releaseSubviews {
9258 [super releaseSubviews];
9264 @interface CYURLCache : SDURLCache {
9269 @implementation CYURLCache
9271 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
9274 else if ([event isEqualToString:@"no-cache"])
9276 else if ([event isEqualToString:@"store"])
9278 else if ([event isEqualToString:@"invalid"])
9280 else if ([event isEqualToString:@"memory"])
9282 else if ([event isEqualToString:@"disk"])
9284 else if ([event isEqualToString:@"miss"])
9287 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
9291 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
9292 if (NSURLResponse *response = [cached response])
9293 if (NSString *mime = [response MIMEType])
9294 if ([mime isEqualToString:@"text/cache-manifest"]) {
9295 NSURL *url([response URL]);
9298 NSLog(@"###: %@", [url absoluteString]);
9301 @synchronized (HostConfig_) {
9302 [CachedURLs_ addObject:url];
9306 [super storeCachedResponse:cached forRequest:request];
9311 @interface Cydia : UIApplication <
9312 ConfirmationControllerDelegate,
9315 UINavigationControllerDelegate,
9316 UITabBarControllerDelegate
9318 _H<UIWindow> window_;
9319 _H<CYTabBarController> tabbar_;
9320 _H<CydiaLoadingViewController> emulated_;
9322 _H<NSMutableArray> essential_;
9323 _H<NSMutableArray> broken_;
9325 Database *database_;
9327 _H<NSURL> starturl_;
9332 _H<StashController> stash_;
9341 @implementation Cydia
9343 - (void) beginUpdate {
9344 [tabbar_ beginUpdate];
9348 return [tabbar_ updating];
9352 if ([broken_ count] != 0) {
9353 int count = [broken_ count];
9355 UIAlertView *alert = [[[UIAlertView alloc]
9356 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9357 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9359 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9361 UCLocalize("TEMPORARY_IGNORE"),
9365 [alert setContext:@"fixhalf"];
9366 [alert setNumberOfRows:2];
9368 } else if (!Ignored_ && [essential_ count] != 0) {
9369 int count = [essential_ count];
9371 UIAlertView *alert = [[[UIAlertView alloc]
9372 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9373 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9375 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9377 UCLocalize("UPGRADE_ESSENTIAL"),
9378 UCLocalize("COMPLETE_UPGRADE"),
9382 [alert setContext:@"upgrade"];
9387 - (void) returnToCydia {
9391 - (void) _saveConfig {
9392 @synchronized (database_) {
9399 NSString *error(nil);
9401 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9403 NSError *error(nil);
9404 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9405 NSLog(@"failure to save metadata data: %@", error);
9410 NSLog(@"failure to serialize metadata: %@", error);
9414 CydiaWriteSources();
9417 // Navigation controller for the queuing badge.
9418 - (UINavigationController *) queueNavigationController {
9419 NSArray *controllers = [tabbar_ viewControllers];
9420 return [controllers objectAtIndex:3];
9423 - (void) unloadData {
9424 [tabbar_ unloadData];
9427 - (void) _updateData {
9431 UINavigationController *navigation = [self queueNavigationController];
9433 id queuedelegate = nil;
9434 if ([[navigation viewControllers] count] > 0)
9435 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9437 [queuedelegate queueStatusDidChange];
9438 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9441 - (void) _refreshIfPossible:(NSDate *)update {
9442 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9444 bool recently = false;
9445 if (update != nil) {
9446 NSTimeInterval interval([update timeIntervalSinceNow]);
9447 if (interval <= 0 && interval > -(15*60))
9451 // Don't automatic refresh if:
9452 // - We already refreshed recently.
9453 // - We already auto-refreshed this launch.
9454 // - Auto-refresh is disabled.
9455 if (recently || loaded_ || ManualRefresh) {
9456 // If we are cancelling, we need to make sure it knows it's already loaded.
9459 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9461 // We are going to load, so remember that.
9464 // If we can reach the server, auto-refresh!
9465 if (IsReachable("cydia.saurik.com"))
9466 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9472 - (void) refreshIfPossible {
9473 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9476 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9477 @synchronized (self) {
9478 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9479 [hud setText:UCLocalize("RELOADING_DATA")];
9481 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9485 [essential_ removeAllObjects];
9486 [broken_ removeAllObjects];
9488 NSArray *packages([database_ packages]);
9489 for (Package *package in packages) {
9491 [broken_ addObject:package];
9492 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9493 if ([package essential] && [package installed] != nil)
9494 [essential_ addObject:package];
9499 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9502 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9503 [changesItem setBadgeValue:badge];
9504 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9505 [self setApplicationIconBadgeNumber:changes];
9508 [changesItem setBadgeValue:nil];
9509 [changesItem setAnimatedBadge:NO];
9510 [self setApplicationIconBadgeNumber:0];
9516 [self removeProgressHUD:hud];
9519 - (void) updateData {
9523 - (void) updateDataAndLoad {
9525 if ([database_ progressDelegate] == nil)
9531 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9534 - (void) disemulate {
9535 if (emulated_ == nil)
9538 [window_ addSubview:[tabbar_ view]];
9539 [[emulated_ view] removeFromSuperview];
9541 [window_ setUserInteractionEnabled:YES];
9544 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9545 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9547 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9549 UIViewController *parent;
9550 if (emulated_ == nil)
9559 [parent presentModalViewController:navigation animated:YES];
9562 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9563 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9565 if (navigation != nil)
9566 [navigation pushViewController:progress animated:YES];
9568 [self presentModalViewController:progress force:YES];
9570 [progress invoke:invocation withTitle:title];
9574 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9575 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9578 - (void) repairWithInvocation:(NSInvocation *)invocation {
9580 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9584 - (void) repairWithSelector:(SEL)selector {
9585 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9588 - (void) reloadData {
9589 [self reloadDataWithInvocation:nil];
9590 if ([database_ progressDelegate] == nil)
9596 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9599 - (void) addSource:(NSDictionary *) source {
9600 CydiaAddSource(source);
9603 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9604 CydiaAddSource(href, distribution, sections);
9607 - (void) addTrivialSource:(NSString *)href {
9608 CydiaAddSource(href, @"./");
9611 - (void) updateValues {
9616 pkgProblemResolver *resolver = [database_ resolver];
9618 resolver->InstallProtect();
9619 if (!resolver->Resolve(true))
9624 // XXX: this is a really crappy way of doing this.
9625 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9626 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9627 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9628 if ([tabbar_ updating])
9629 [tabbar_ cancelUpdate];
9631 if (![database_ prepare])
9634 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9635 [page setDelegate:self];
9636 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9639 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9640 [tabbar_ presentModalViewController:confirm_ animated:YES];
9646 @synchronized (self) {
9651 - (void) clearPackage:(Package *)package {
9652 @synchronized (self) {
9659 - (void) installPackages:(NSArray *)packages {
9660 @synchronized (self) {
9661 for (Package *package in packages)
9668 - (void) installPackage:(Package *)package {
9669 @synchronized (self) {
9676 - (void) removePackage:(Package *)package {
9677 @synchronized (self) {
9684 - (void) distUpgrade {
9685 @synchronized (self) {
9686 if (![database_ upgrade])
9694 system("su -c /usr/bin/uicache mobile");
9699 UIProgressHUD *hud([self addProgressHUD]);
9700 [hud setText:UCLocalize("LOADING")];
9701 [self yieldToSelector:@selector(_uicache)];
9702 [self removeProgressHUD:hud];
9706 [database_ perform];
9707 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9708 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9711 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9714 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9718 - (void) showSettings {
9719 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9722 - (void) retainNetworkActivityIndicator {
9723 if (activity_++ == 0)
9724 [self setNetworkActivityIndicatorVisible:YES];
9727 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9731 - (void) releaseNetworkActivityIndicator {
9732 if (--activity_ == 0)
9733 [self setNetworkActivityIndicatorVisible:NO];
9736 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9741 - (void) cancelAndClear:(bool)clear {
9742 @synchronized (self) {
9754 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9755 NSString *context([alert context]);
9757 if ([context isEqualToString:@"conffile"]) {
9758 FILE *input = [database_ input];
9759 if (button == [alert cancelButtonIndex])
9760 fprintf(input, "N\n");
9761 else if (button == [alert firstOtherButtonIndex])
9762 fprintf(input, "Y\n");
9765 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9766 } else if ([context isEqualToString:@"fixhalf"]) {
9767 if (button == [alert cancelButtonIndex]) {
9768 @synchronized (self) {
9769 for (Package *broken in (id) broken_) {
9772 NSString *id = [broken id];
9773 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9774 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9775 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9776 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9782 } else if (button == [alert firstOtherButtonIndex]) {
9783 [broken_ removeAllObjects];
9787 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9788 } else if ([context isEqualToString:@"upgrade"]) {
9789 if (button == [alert firstOtherButtonIndex]) {
9790 @synchronized (self) {
9791 for (Package *essential in (id) essential_)
9792 [essential install];
9797 } else if (button == [alert firstOtherButtonIndex] + 1) {
9799 } else if (button == [alert cancelButtonIndex]) {
9803 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9807 - (void) system:(NSString *)command {
9808 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9811 system([command UTF8String]);
9817 - (void) applicationWillSuspend {
9819 [super applicationWillSuspend];
9822 - (BOOL) isSafeToSuspend {
9825 NSLog(@"isSafeToSuspend: locked_ != 0");
9830 // Use external process status API internally.
9831 // This is probably a really bad idea.
9832 // XXX: what is the point of this? does this solve anything at all?
9833 uint64_t status = 0;
9835 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9836 notify_get_state(notify_token, &status);
9837 notify_cancel(notify_token);
9842 NSLog(@"isSafeToSuspend: status != 0");
9848 NSLog(@"isSafeToSuspend: -> true");
9853 - (void) applicationSuspend:(__GSEvent *)event {
9854 if ([self isSafeToSuspend])
9855 [super applicationSuspend:event];
9858 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9859 if ([self isSafeToSuspend])
9860 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9863 - (void) _setSuspended:(BOOL)value {
9864 if ([self isSafeToSuspend])
9865 [super _setSuspended:value];
9868 - (UIProgressHUD *) addProgressHUD {
9869 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9870 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9872 [window_ setUserInteractionEnabled:NO];
9874 UIViewController *target(tabbar_);
9875 if (UIViewController *modal = [target modalViewController])
9878 [hud showInView:[target view]];
9884 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9887 [hud removeFromSuperview];
9888 [window_ setUserInteractionEnabled:YES];
9891 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9892 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9895 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9896 NSString *scheme([[url scheme] lowercaseString]);
9897 if ([[url absoluteString] length] <= [scheme length] + 3)
9899 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9900 NSArray *components([path componentsSeparatedByString:@"/"]);
9902 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9903 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9904 if (controller != nil)
9905 [controller setDelegate:self];
9909 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9912 NSString *base([components objectAtIndex:0]);
9914 CyteViewController *controller = nil;
9916 if ([base isEqualToString:@"url"]) {
9917 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9918 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9919 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9920 } else if (!external && [components count] == 1) {
9921 if ([base isEqualToString:@"manage"]) {
9922 controller = [[[ManageController alloc] init] autorelease];
9925 if ([base isEqualToString:@"storage"]) {
9926 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9929 if ([base isEqualToString:@"sources"]) {
9930 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9933 if ([base isEqualToString:@"home"]) {
9934 controller = [[[HomeController alloc] init] autorelease];
9937 if ([base isEqualToString:@"sections"]) {
9938 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9941 if ([base isEqualToString:@"search"]) {
9942 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9945 if ([base isEqualToString:@"changes"]) {
9946 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9949 if ([base isEqualToString:@"installed"]) {
9950 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9952 } else if ([components count] == 2) {
9953 NSString *argument = [components objectAtIndex:1];
9955 if ([base isEqualToString:@"package"]) {
9956 controller = [self pageForPackage:argument withReferrer:referrer];
9959 if (!external && [base isEqualToString:@"search"]) {
9960 controller = [[[SearchController alloc] initWithDatabase:database_ query:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9963 if (!external && [base isEqualToString:@"sections"]) {
9964 if ([argument isEqualToString:@"all"])
9966 controller = [[[SectionController alloc] initWithDatabase:database_ section:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9969 if (!external && [base isEqualToString:@"sources"]) {
9970 if ([argument isEqualToString:@"add"]) {
9971 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9972 [(SourcesController *)controller showAddSourcePrompt];
9974 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9975 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9979 if (!external && [base isEqualToString:@"launch"]) {
9980 [self launchApplicationWithIdentifier:argument suspended:NO];
9983 } else if (!external && [components count] == 3) {
9984 NSString *arg1 = [components objectAtIndex:1];
9985 NSString *arg2 = [components objectAtIndex:2];
9987 if ([base isEqualToString:@"package"]) {
9988 if ([arg2 isEqualToString:@"settings"]) {
9989 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9990 } else if ([arg2 isEqualToString:@"files"]) {
9991 if (Package *package = [database_ packageWithName:arg1]) {
9992 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9993 [(FileTable *)controller setPackage:package];
9999 [controller setDelegate:self];
10003 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
10004 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
10007 [tabbar_ setUnselectedViewController:page];
10009 return page != nil;
10012 - (void) applicationOpenURL:(NSURL *)url {
10013 [super applicationOpenURL:url];
10018 [self openCydiaURL:url forExternal:YES];
10021 - (void) applicationWillResignActive:(UIApplication *)application {
10022 // Stop refreshing if you get a phone call or lock the device.
10023 if ([tabbar_ updating])
10024 [tabbar_ cancelUpdate];
10026 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
10027 [super applicationWillResignActive:application];
10030 - (void) saveState {
10031 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
10032 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
10033 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
10036 [self _saveConfig];
10039 - (void) applicationWillTerminate:(UIApplication *)application {
10043 - (void) setConfigurationData:(NSString *)data {
10044 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
10046 if (!conffile_r(data)) {
10047 lprintf("E:invalid conffile\n");
10051 NSString *ofile = conffile_r[1];
10052 //NSString *nfile = conffile_r[2];
10054 UIAlertView *alert = [[[UIAlertView alloc]
10055 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
10056 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
10058 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
10060 UCLocalize("ACCEPT_NEW_COPY"),
10061 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
10065 [alert setContext:@"conffile"];
10066 [alert setNumberOfRows:2];
10070 - (void) addStashController {
10072 stash_ = [[[StashController alloc] init] autorelease];
10073 [window_ addSubview:[stash_ view]];
10076 - (void) removeStashController {
10077 [[stash_ view] removeFromSuperview];
10083 [self setIdleTimerDisabled:YES];
10085 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
10086 UpdateExternalStatus(1);
10087 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
10088 UpdateExternalStatus(0);
10090 [self removeStashController];
10092 pid_t pid(ExecFork());
10094 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
10095 perror("launchctl stop");
10102 - (void) setupViewControllers {
10103 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
10105 NSMutableArray *items([NSMutableArray arrayWithObjects:
10106 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
10107 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
10108 [[[UITabBarItem alloc] initWithTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES")) image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
10109 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
10113 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
10114 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10116 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10119 NSMutableArray *controllers([NSMutableArray array]);
10120 for (UITabBarItem *item in items) {
10121 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
10122 [controller setTabBarItem:item];
10123 [controllers addObject:controller];
10125 [tabbar_ setViewControllers:controllers];
10127 [tabbar_ setUpdateDelegate:self];
10130 - (void) _sendMemoryWarningNotification {
10131 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
10132 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
10134 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
10137 - (void) _sendMemoryWarningNotifications {
10139 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
10145 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
10147 [[NSURLCache sharedURLCache] removeAllCachedResponses];
10150 - (void) applicationDidFinishLaunching:(id)unused {
10151 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
10154 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
10155 [self setApplicationSupportsShakeToEdit:NO];
10157 @synchronized (HostConfig_) {
10158 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
10161 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
10162 initWithMemoryCapacity:524288
10163 diskCapacity:10485760
10164 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
10167 [CydiaWebViewController _initialize];
10169 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
10171 // this would disallow http{,s} URLs from accessing this data
10172 //[WebView registerURLSchemeAsLocal:@"cydia"];
10174 Font12_ = [UIFont systemFontOfSize:12];
10175 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
10176 Font14_ = [UIFont systemFontOfSize:14];
10177 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
10178 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
10180 essential_ = [NSMutableArray arrayWithCapacity:4];
10181 broken_ = [NSMutableArray arrayWithCapacity:4];
10183 // XXX: I really need this thing... like, seriously... I'm sorry
10184 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
10186 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
10187 [window_ orderFront:self];
10188 [window_ makeKey:self];
10189 [window_ setHidden:NO];
10191 if (false) stash: {
10192 [self addStashController];
10193 // XXX: this would be much cleaner as a yieldToSelector:
10194 // that way the removeStashController could happen right here inline
10195 // we also could no longer require the useless stash_ field anymore
10196 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
10201 int error(stat("/", &root));
10202 _assert(error != -1);
10204 #define Stash_(path) do { \
10205 struct stat folder; \
10206 int error(lstat((path), &folder)); \
10207 if (error != -1 && ( \
10208 folder.st_dev == root.st_dev && \
10209 S_ISDIR(folder.st_mode) \
10210 ) || error == -1 && ( \
10211 errno == ENOENT || \
10216 Stash_("/Applications");
10217 Stash_("/Library/Ringtones");
10218 Stash_("/Library/Wallpaper");
10219 //Stash_("/usr/bin");
10220 Stash_("/usr/include");
10221 Stash_("/usr/lib/pam");
10222 Stash_("/usr/libexec");
10223 Stash_("/usr/share");
10224 //Stash_("/var/lib");
10226 database_ = [Database sharedInstance];
10227 [database_ setDelegate:self];
10229 [window_ setUserInteractionEnabled:NO];
10230 [self setupViewControllers];
10232 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
10233 [window_ addSubview:[emulated_ view]];
10235 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
10239 - (NSArray *) defaultStartPages {
10240 NSMutableArray *standard = [NSMutableArray array];
10241 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
10242 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
10243 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
10245 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
10247 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
10248 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
10250 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10254 - (void) loadData {
10256 if (Role_ == nil) {
10257 [window_ setUserInteractionEnabled:YES];
10258 [self showSettings];
10261 if ([emulated_ modalViewController] != nil)
10262 [emulated_ dismissModalViewControllerAnimated:YES];
10263 [window_ setUserInteractionEnabled:NO];
10266 [self reloadDataWithInvocation:nil];
10267 [self refreshIfPossible];
10272 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
10273 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
10274 int standardIndex = 0;
10275 NSArray *standard = [self defaultStartPages];
10282 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
10283 if (valid && closed != nil) {
10284 NSTimeInterval interval([closed timeIntervalSinceNow]);
10285 // XXX: Is 30 minutes the optimal time here?
10286 if (interval <= -(30*60))
10290 if (valid && [saved count] != [standard count])
10294 for (unsigned int i = 0; i < [standard count]; i++) {
10295 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10296 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10297 // but it's good enough for now.
10298 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10305 NSArray *items = nil;
10307 [tabbar_ setSelectedIndex:savedIndex];
10310 [tabbar_ setSelectedIndex:standardIndex];
10314 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10315 NSArray *stack = [items objectAtIndex:tab];
10316 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10317 NSMutableArray *current = [NSMutableArray array];
10319 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10320 NSString *addr = [stack objectAtIndex:nav];
10321 NSURL *url = [NSURL URLWithString:addr];
10322 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10324 [current addObject:page];
10327 [navigation setViewControllers:current];
10330 // (Try to) show the startup URL.
10331 if (starturl_ != nil) {
10332 [self openCydiaURL:starturl_ forExternal:NO];
10337 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10338 if (item != nil && IsWildcat_) {
10339 [sheet showFromBarButtonItem:item animated:YES];
10341 [sheet showInView:window_];
10345 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10346 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10347 [progress setTitle:task];
10348 [progress addProgressEvent:event];
10351 - (void) addProgressEventForTask:(NSArray *)data {
10352 CydiaProgressEvent *event([data objectAtIndex:0]);
10353 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10354 [self addProgressEvent:event forTask:task];
10357 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10358 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10364 id Alloc_(id self, SEL selector) {
10365 id object = alloc_(self, selector);
10366 lprintf("[%s]A-%p\n", self->isa->name, object);
10371 id Dealloc_(id self, SEL selector) {
10372 id object = dealloc_(self, selector);
10373 lprintf("[%s]D-%p\n", self->isa->name, object);
10377 static NSSet *MobilizedFiles_;
10379 static NSURL *MobilizeURL(NSURL *url) {
10380 NSString *path([url path]);
10381 if ([path hasPrefix:@"/var/root/"]) {
10382 NSString *file([path substringFromIndex:10]);
10383 if ([MobilizedFiles_ containsObject:file])
10384 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10390 Class $CFXPreferencesPropertyListSource;
10391 @class CFXPreferencesPropertyListSource;
10393 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10394 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10395 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10396 url = MobilizeURL(url);
10397 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10398 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10404 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10405 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10406 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10407 url = MobilizeURL(url);
10408 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10409 //NSLog(@"%@ %@", [url absoluteString], value);
10415 Class $NSURLConnection;
10417 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10418 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10420 NSURL *url([copy URL]);
10422 NSString *host([url host]);
10423 NSString *scheme([[url scheme] lowercaseString]);
10425 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10427 @synchronized (HostConfig_) {
10428 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10429 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10430 [copy setHTTPShouldUsePipelining:YES];
10432 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10433 if ([control isEqualToString:@"max-age=0"])
10434 if ([CachedURLs_ containsObject:url]) {
10436 NSLog(@"~~~: %@", url);
10439 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10441 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10442 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10443 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10447 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10453 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10454 CGSize size([[UIScreen mainScreen] bounds].size);
10455 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10456 if ([$WAKWindow hasLandscapeOrientation])
10457 std::swap(size.width, size.height);*/
10461 int main(int argc, char *argv[]) {
10462 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10466 UpdateExternalStatus(0);
10468 if (Class $UIDevice = objc_getClass("UIDevice")) {
10469 UIDevice *device([$UIDevice currentDevice]);
10470 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10472 IsWildcat_ = false;
10474 UIScreen *screen([UIScreen mainScreen]);
10475 if ([screen respondsToSelector:@selector(scale)])
10476 ScreenScale_ = [screen scale];
10480 UIDevice *device([UIDevice currentDevice]);
10481 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10482 Idiom_ = @"iphone";
10484 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10485 if (idiom == UIUserInterfaceIdiomPhone)
10486 Idiom_ = @"iphone";
10487 else if (idiom == UIUserInterfaceIdiomPad)
10490 NSLog(@"unknown UIUserInterfaceIdiom!");
10493 Pcre pattern("^([0-9]+\\.[0-9]+)");
10495 if (pattern([device systemVersion]))
10496 Firmware_ = pattern[1];
10497 if (pattern(Cydia_))
10498 Major_ = pattern[1];
10500 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10502 HostConfig_ = [[[NSObject alloc] init] autorelease];
10503 @synchronized (HostConfig_) {
10504 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10505 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10506 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10507 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10508 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10511 NSString *ui(@"ui/ios");
10513 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10514 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10515 UI_ = CydiaURL(ui);
10517 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10519 MobilizedFiles_ = [NSMutableSet setWithObjects:
10520 @"Library/Preferences/com.apple.Accessibility.plist",
10521 @"Library/Preferences/com.apple.preferences.sounds.plist",
10524 /* Library Hacks {{{ */
10525 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10527 $WAKWindow = objc_getClass("WAKWindow");
10528 if ($WAKWindow != NULL)
10529 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10530 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10532 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10534 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10535 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10536 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10537 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10540 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10541 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10542 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10543 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10546 $NSURLConnection = objc_getClass("NSURLConnection");
10547 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10548 if (NSURLConnection$init$ != NULL) {
10549 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10550 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10553 /* Set Locale {{{ */
10554 Locale_ = CFLocaleCopyCurrent();
10555 Languages_ = [NSLocale preferredLanguages];
10557 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10558 //NSLog(@"%@", [Languages_ description]);
10561 if (Locale_ != NULL)
10562 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10563 else if (Languages_ != nil && [Languages_ count] != 0)
10564 lang = [[Languages_ objectAtIndex:0] UTF8String];
10566 // XXX: consider just setting to C and then falling through?
10569 if (lang != NULL) {
10570 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10571 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10574 NSLog(@"Setting Language: %s", lang);
10576 if (lang != NULL) {
10577 setenv("LANG", lang, true);
10578 std::setlocale(LC_ALL, lang);
10582 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10584 /* Parse Arguments {{{ */
10585 bool substrate(false);
10591 for (int argi(1); argi != argc; ++argi)
10592 if (strcmp(argv[argi], "--") == 0) {
10594 argv[argi] = argv[0];
10600 for (int argi(1); argi != arge; ++argi)
10601 if (strcmp(args[argi], "--substrate") == 0)
10604 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10608 App_ = [[NSBundle mainBundle] bundlePath];
10614 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10615 alloc_ = alloc->method_imp;
10616 alloc->method_imp = (IMP) &Alloc_;*/
10618 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10619 dealloc_ = dealloc->method_imp;
10620 dealloc->method_imp = (IMP) &Dealloc_;*/
10622 /* System Information {{{ */
10626 size = sizeof(maxproc);
10627 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10628 perror("sysctlbyname(\"kern.maxproc\", ?)");
10629 else if (maxproc < 64) {
10631 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10632 perror("sysctlbyname(\"kern.maxproc\", #)");
10635 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10636 char *osversion = new char[size];
10637 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10638 perror("sysctlbyname(\"kern.osversion\", ?)");
10640 System_ = [NSString stringWithUTF8String:osversion];
10642 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10643 char *machine = new char[size];
10644 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10645 perror("sysctlbyname(\"hw.machine\", ?)");
10647 Machine_ = machine;
10649 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10650 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10651 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10653 UniqueID_ = [device uniqueIdentifier];
10655 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10656 Product_ = [info objectForKey:@"SafariProductVersion"];
10657 Safari_ = [info objectForKey:@"CFBundleVersion"];
10660 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10662 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10663 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10664 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10665 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10666 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10667 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10669 UserAgent_ = agent;
10671 /* Load Database {{{ */
10673 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10675 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10677 if (Metadata_ == NULL)
10678 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10680 Settings_ = [Metadata_ objectForKey:@"Settings"];
10682 Packages_ = [Metadata_ objectForKey:@"Packages"];
10684 Values_ = [Metadata_ objectForKey:@"Values"];
10685 Sections_ = [Metadata_ objectForKey:@"Sections"];
10686 Sources_ = [Metadata_ objectForKey:@"Sources"];
10688 Token_ = [Metadata_ objectForKey:@"Token"];
10690 Version_ = [Metadata_ objectForKey:@"Version"];
10693 if (Settings_ != nil)
10694 Role_ = [Settings_ objectForKey:@"Role"];
10696 if (Values_ == nil) {
10697 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10698 [Metadata_ setObject:Values_ forKey:@"Values"];
10701 if (Sections_ == nil) {
10702 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10703 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10706 if (Sources_ == nil) {
10707 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10708 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10711 if (Version_ == nil) {
10712 Version_ = [NSNumber numberWithUnsignedInt:0];
10713 [Metadata_ setObject:Version_ forKey:@"Version"];
10716 if ([Version_ unsignedIntValue] == 0) {
10717 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10718 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10719 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10720 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10722 Version_ = [NSNumber numberWithUnsignedInt:1];
10723 [Metadata_ setObject:Version_ forKey:@"Version"];
10725 [Metadata_ removeObjectForKey:@"LastUpdate"];
10731 CydiaWriteSources();
10734 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10737 if (Packages_ != nil) {
10739 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10743 [Metadata_ removeObjectForKey:@"Packages"];
10749 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10751 #define MobileSubstrate_(name) \
10752 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10753 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10754 if (handle == NULL) \
10755 NSLog(@"%s", dlerror()); \
10758 MobileSubstrate_(Activator)
10759 MobileSubstrate_(libstatusbar)
10760 MobileSubstrate_(SimulatedKeyEvents)
10761 MobileSubstrate_(WinterBoard)
10763 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10764 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10766 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10768 if (access("/User", F_OK) != 0 || version != 5) {
10770 system("/usr/libexec/cydia/firmware.sh");
10774 _assert([[NSFileManager defaultManager]
10775 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10776 withIntermediateDirectories:YES
10781 if (access("/tmp/cydia.chk", F_OK) == 0) {
10782 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10783 _assert(errno == ENOENT);
10784 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10785 _assert(errno == ENOENT);
10788 /* APT Initialization {{{ */
10789 _assert(pkgInitConfig(*_config));
10790 _assert(pkgInitSystem(*_config, _system));
10793 _config->Set("APT::Acquire::Translation", lang);
10795 // XXX: this timeout might be important :(
10796 //_config->Set("Acquire::http::Timeout", 15);
10798 _config->Set("Acquire::http::MaxParallel", 3);
10800 /* Color Choices {{{ */
10801 space_ = CGColorSpaceCreateDeviceRGB();
10803 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10804 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10805 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10806 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10807 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10808 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10809 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10810 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10811 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10813 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10814 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10816 /* UIKit Configuration {{{ */
10817 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10818 if ($GSFontSetUseLegacyFontMetrics != NULL)
10819 $GSFontSetUseLegacyFontMetrics(YES);
10821 // XXX: I have a feeling this was important
10822 //UIKeyboardDisableAutomaticAppearance();
10825 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemHasCapability"));
10826 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10828 ShowPromoted_ = fast;
10829 PulseInterval_ = fast ? 50000 : 500000;
10831 Colon_ = UCLocalize("COLON_DELIMITED");
10832 Elision_ = UCLocalize("ELISION");
10833 Error_ = UCLocalize("ERROR");
10834 Warning_ = UCLocalize("WARNING");
10837 AprilFools_ = true;
10839 CFGregorianDate date(CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem()));
10840 AprilFools_ = date.month == 4 && date.day == 1;
10844 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10846 CGColorSpaceRelease(space_);
10847 CFRelease(Locale_);