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 extern NSString *Cydia_;
216 #define lprintf(args...) fprintf(stderr, args)
219 #define TraceLogging (1 && !ForRelease)
220 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
221 #define ProfileTimes (0 && !ForRelease)
222 #define ForSaurik (0 && !ForRelease)
223 #define LogBrowser (0 && !ForRelease)
224 #define TrackResize (0 && !ForRelease)
225 #define ManualRefresh (1 && !ForRelease)
226 #define ShowInternals (0 && !ForRelease)
227 #define AlwaysReload (0 && !ForRelease)
228 #define TryIndexedCollation (0 && !ForRelease)
232 #define _trace(args...)
237 #define _profile(name) {
240 #define PrintTimes() do {} while (false)
243 // Hash Functions/Structures {{{
244 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
252 static bool ShowPromoted_;
254 static NSString *Colon_;
256 static NSString *Error_;
257 static NSString *Warning_;
259 static bool AprilFools_;
261 static bool IsReachable(const char *name) {
262 SCNetworkReachabilityFlags flags; {
263 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
264 SCNetworkReachabilityGetFlags(reachability, &flags);
265 CFRelease(reachability);
268 // XXX: this elaborate mess is what Apple is using to determine this? :(
269 // XXX: do we care if the user has to intervene? maybe that's ok?
271 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
272 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
273 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
274 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
275 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
276 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
281 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
283 static _finline NSString *CydiaURL(NSString *path) {
285 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
286 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
287 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
288 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
289 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
291 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
294 static void ReapZombie(pid_t pid) {
297 if (waitpid(pid, &status, 0) == -1)
303 static _finline void UpdateExternalStatus(uint64_t newStatus) {
305 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
306 notify_set_state(notify_token, newStatus);
307 notify_cancel(notify_token);
309 notify_post("com.saurik.Cydia.status");
312 static CGFloat CYStatusBarHeight() {
313 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
314 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
317 /* NSForcedOrderingSearch doesn't work on the iPhone */
318 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
319 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
320 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
322 /* Insertion Sort {{{ */
324 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
325 const char *ptr = (const char *)list;
327 CFIndex half = count / 2;
328 const char *probe = ptr + elementSize * half;
329 CFComparisonResult cr = comparator(element, probe, context);
330 if (0 == cr) return (probe - (const char *)list) / elementSize;
331 ptr = (cr < 0) ? ptr : probe + elementSize;
332 count = (cr < 0) ? half : (half + (count & 1) - 1);
334 return (ptr - (const char *)list) / elementSize;
337 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
338 const char *ptr = (const char *)list;
340 CFIndex half = count / 2;
341 const char *probe = ptr + elementSize * half;
342 CFComparisonResult cr = comparator(element, probe, context);
343 if (0 == cr) return (probe - (const char *)list) / elementSize;
344 ptr = (cr < 0) ? ptr : probe + elementSize;
345 count = (cr < 0) ? half : (half + (count & 1) - 1);
347 return (ptr - (const char *)list) / elementSize;
350 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
351 if (range.length == 0)
353 const void **values(new const void *[range.length]);
354 CFArrayGetValues(array, range, values);
356 #if HistogramInsertionSort > 0
357 uint32_t total(0), *offsets(new uint32_t[range.length]);
360 for (CFIndex index(1); index != range.length; ++index) {
361 const void *value(values[index]);
362 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
363 CFIndex correct(index);
364 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
365 #if HistogramInsertionSort > 1
366 NSLog(@"%@ < %@", value, values[correct - 1]);
371 if (correct != index) {
372 size_t offset(index - correct);
373 #if HistogramInsertionSort
377 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
379 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
380 values[correct] = value;
384 CFArrayReplaceValues(array, range, values, range.length);
387 #if HistogramInsertionSort > 0
388 for (CFIndex index(0); index != range.length; ++index)
389 if (offsets[index] != 0)
390 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
391 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
398 /* Apple Bug Fixes {{{ */
399 @implementation UIWebDocumentView (Cydia)
401 - (void) _setScrollerOffset:(CGPoint)offset {
402 UIScroller *scroller([self _scroller]);
404 CGSize size([scroller contentSize]);
405 CGSize bounds([scroller bounds].size);
408 max.x = size.width - bounds.width;
409 max.y = size.height - bounds.height;
417 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
418 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
420 [scroller setOffset:offset];
426 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
427 size_t length([self length] - state->state);
430 else if (length > count)
432 for (size_t i(0); i != length; ++i)
433 objects[i] = [self item:state->state++];
434 state->itemsPtr = objects;
435 state->mutationsPtr = (unsigned long *) self;
439 /* Cydia NSString Additions {{{ */
440 @interface NSString (Cydia)
441 - (NSComparisonResult) compareByPath:(NSString *)other;
442 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
445 @implementation NSString (Cydia)
447 - (NSComparisonResult) compareByPath:(NSString *)other {
448 NSString *prefix = [self commonPrefixWithString:other options:0];
449 size_t length = [prefix length];
451 NSRange lrange = NSMakeRange(length, [self length] - length);
452 NSRange rrange = NSMakeRange(length, [other length] - length);
454 lrange = [self rangeOfString:@"/" options:0 range:lrange];
455 rrange = [other rangeOfString:@"/" options:0 range:rrange];
457 NSComparisonResult value;
459 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
460 value = NSOrderedSame;
461 else if (lrange.location == NSNotFound)
462 value = NSOrderedAscending;
463 else if (rrange.location == NSNotFound)
464 value = NSOrderedDescending;
466 value = NSOrderedSame;
468 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
469 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
470 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
471 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
473 NSComparisonResult result = [lpath compare:rpath];
474 return result == NSOrderedSame ? value : result;
477 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
478 return [(id)CFURLCreateStringByAddingPercentEscapes(
483 kCFStringEncodingUTF8
490 /* C++ NSString Wrapper Cache {{{ */
491 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
492 return size == 0 ? NULL :
493 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
494 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
497 static _finline CFStringRef CYStringCreate(const char *data) {
498 return CYStringCreate(data, strlen(data));
507 _finline void clear_() {
508 if (cache_ != NULL) {
515 _finline bool empty() const {
519 _finline size_t size() const {
523 _finline char *data() const {
527 _finline void clear() {
532 _finline CYString() :
539 _finline ~CYString() {
543 void operator =(const CYString &rhs) {
547 if (rhs.cache_ == nil)
550 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
553 void copy(apr_pool_t *pool) {
554 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
555 memcpy(temp, data_, size_);
560 void set(apr_pool_t *pool, const char *data, size_t size) {
566 data_ = const_cast<char *>(data);
574 _finline void set(apr_pool_t *pool, const char *data) {
575 set(pool, data, data == NULL ? 0 : strlen(data));
578 _finline void set(apr_pool_t *pool, const std::string &rhs) {
579 set(pool, rhs.data(), rhs.size());
582 bool operator ==(const CYString &rhs) const {
583 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
586 _finline operator CFStringRef() {
588 cache_ = CYStringCreate(data_, size_);
592 _finline operator id() {
593 return (NSString *) static_cast<CFStringRef>(*this);
596 _finline operator const char *() {
597 return reinterpret_cast<const char *>(data_);
601 /* C++ NSString Algorithm Adapters {{{ */
603 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
606 struct NSStringMapHash :
607 std::unary_function<NSString *, size_t>
609 _finline size_t operator ()(NSString *value) const {
610 return CFStringHashNSString((CFStringRef) value);
614 struct NSStringMapLess :
615 std::binary_function<NSString *, NSString *, bool>
617 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
618 return [lhs compare:rhs] == NSOrderedAscending;
622 struct NSStringMapEqual :
623 std::binary_function<NSString *, NSString *, bool>
625 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
626 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
627 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
628 //[lhs isEqualToString:rhs];
633 /* CoreGraphics Primitives {{{ */
638 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
639 CGFloat color[] = {red, green, blue, alpha};
640 return CGColorCreate(space, color);
649 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
650 color_(Create_(space, red, green, blue, alpha))
652 Set(space, red, green, blue, alpha);
657 CGColorRelease(color_);
664 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
666 color_ = Create_(space, red, green, blue, alpha);
669 operator CGColorRef() {
675 /* Random Global Variables {{{ */
676 static int PulseInterval_ = 500000;
678 static const NSString *UI_;
681 static bool RestartSubstrate_;
682 static NSArray *Finishes_;
684 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
685 #define NotifyConfig_ "/etc/notify.conf"
687 static bool Queuing_;
689 static CYColor Blue_;
690 static CYColor Blueish_;
691 static CYColor Black_;
693 static CYColor White_;
694 static CYColor Gray_;
695 static CYColor Green_;
696 static CYColor Purple_;
697 static CYColor Purplish_;
699 static UIColor *InstallingColor_;
700 static UIColor *RemovingColor_;
702 static NSString *App_;
704 static BOOL Advanced_;
705 static BOOL Ignored_;
707 static _H<UIFont> Font12_;
708 static _H<UIFont> Font12Bold_;
709 static _H<UIFont> Font14_;
710 static _H<UIFont> Font18Bold_;
711 static _H<UIFont> Font22Bold_;
713 static const char *Machine_ = NULL;
714 static _H<NSString> System_;
715 static NSString *SerialNumber_ = nil;
716 static NSString *ChipID_ = nil;
717 static NSString *BBSNum_ = nil;
718 static _H<NSString> Token_;
719 static NSString *UniqueID_ = nil;
720 static _H<NSString> UserAgent_;
721 static _H<NSString> Product_;
722 static _H<NSString> Safari_;
724 static CFLocaleRef Locale_;
725 static NSArray *Languages_;
726 static CGColorSpaceRef space_;
728 static NSDictionary *SectionMap_;
729 static NSMutableDictionary *Metadata_;
730 static _transient NSMutableDictionary *Settings_;
731 static _transient NSString *Role_;
732 static _transient NSMutableDictionary *Packages_;
733 static _transient NSMutableDictionary *Values_;
734 static _transient NSMutableDictionary *Sections_;
735 _H<NSMutableDictionary> Sources_;
736 static _transient NSNumber *Version_;
741 static CGFloat ScreenScale_;
742 static NSString *Idiom_;
743 static _H<NSString> Firmware_;
744 static NSString *Major_;
746 static _H<NSMutableDictionary> SessionData_;
747 static _H<NSObject> HostConfig_;
748 static _H<NSMutableSet> BridgedHosts_;
749 static _H<NSMutableSet> TokenHosts_;
750 static _H<NSMutableSet> InsecureHosts_;
751 static _H<NSMutableSet> PipelinedHosts_;
752 static _H<NSMutableSet> CachedURLs_;
754 static NSString *kCydiaProgressEventTypeError = @"Error";
755 static NSString *kCydiaProgressEventTypeInformation = @"Information";
756 static NSString *kCydiaProgressEventTypeStatus = @"Status";
757 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
760 /* Display Helpers {{{ */
761 inline float Interpolate(float begin, float end, float fraction) {
762 return (end - begin) * fraction + begin;
765 static _finline const char *StripVersion_(const char *version) {
766 const char *colon(strchr(version, ':'));
767 return colon == NULL ? version : colon + 1;
770 NSString *LocalizeSection(NSString *section) {
771 static Pcre title_r("^(.*?) \\((.*)\\)$");
772 if (title_r(section)) {
773 NSString *parent(title_r[1]);
774 NSString *child(title_r[2]);
776 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
777 LocalizeSection(parent),
778 LocalizeSection(child)
782 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
785 NSString *Simplify(NSString *title) {
786 const char *data = [title UTF8String];
787 size_t size = [title length];
789 static Pcre square_r("^\\[(.*)\\]$");
790 if (square_r(data, size))
791 return Simplify(square_r[1]);
793 static Pcre paren_r("^\\((.*)\\)$");
794 if (paren_r(data, size))
795 return Simplify(paren_r[1]);
797 static Pcre title_r("^(.*?) \\((.*)\\)$");
798 if (title_r(data, size))
799 return Simplify(title_r[1]);
805 NSString *GetLastUpdate() {
806 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
809 return UCLocalize("NEVER_OR_UNKNOWN");
811 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
812 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
814 CFRelease(formatter);
816 return [(NSString *) formatted autorelease];
819 bool isSectionVisible(NSString *section) {
820 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
821 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
822 return hidden == nil || ![hidden boolValue];
825 static NSObject *CYIOGetValue(const char *path, NSString *property) {
826 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
827 if (entry == MACH_PORT_NULL)
830 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
831 IOObjectRelease(entry);
835 return [(id) value autorelease];
838 static NSString *CYHex(NSData *data, bool reverse = false) {
842 size_t length([data length]);
843 uint8_t bytes[length];
844 [data getBytes:bytes];
846 char string[length * 2 + 1];
847 for (size_t i(0); i != length; ++i)
848 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
850 return [NSString stringWithUTF8String:string];
855 /* Delegate Prototypes {{{ */
858 @class CydiaProgressEvent;
860 @protocol DatabaseDelegate
861 - (void) repairWithSelector:(SEL)selector;
862 - (void) setConfigurationData:(NSString *)data;
863 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
866 @class CYPackageController;
868 @protocol CydiaDelegate
869 - (void) returnToCydia;
871 - (void) retainNetworkActivityIndicator;
872 - (void) releaseNetworkActivityIndicator;
873 - (void) clearPackage:(Package *)package;
874 - (void) installPackage:(Package *)package;
875 - (void) installPackages:(NSArray *)packages;
876 - (void) removePackage:(Package *)package;
877 - (void) beginUpdate;
879 - (void) distUpgrade;
882 - (void) _saveConfig;
884 - (void) addSource:(NSDictionary *)source;
885 - (void) addTrivialSource:(NSString *)href;
886 - (void) showSettings;
887 - (UIProgressHUD *) addProgressHUD;
888 - (void) removeProgressHUD:(UIProgressHUD *)hud;
889 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
890 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
894 /* Status Delegation {{{ */
896 public pkgAcquireStatus
899 _transient NSObject<ProgressDelegate> *delegate_;
909 void setDelegate(NSObject<ProgressDelegate> *delegate) {
910 delegate_ = delegate;
913 NSObject<ProgressDelegate> *getDelegate() const {
917 virtual bool MediaChange(std::string media, std::string drive) {
921 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
925 virtual void Fetch(pkgAcquire::ItemDesc &item) {
926 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
927 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
928 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
931 virtual void Done(pkgAcquire::ItemDesc &item) {
932 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
933 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
934 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
937 virtual void Fail(pkgAcquire::ItemDesc &item) {
939 item.Owner->Status == pkgAcquire::Item::StatIdle ||
940 item.Owner->Status == pkgAcquire::Item::StatDone
944 std::string &error(item.Owner->ErrorText);
948 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
949 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
952 virtual bool Pulse(pkgAcquire *Owner) {
953 bool value = pkgAcquireStatus::Pulse(Owner);
956 double(CurrentBytes + CurrentItems) /
957 double(TotalBytes + TotalItems)
960 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
961 [NSNumber numberWithDouble:percent], @"Percent",
963 [NSNumber numberWithDouble:CurrentBytes], @"Current",
964 [NSNumber numberWithDouble:TotalBytes], @"Total",
965 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
966 nil] waitUntilDone:YES];
968 if (value && ![delegate_ isProgressCancelled])
976 _finline bool WasCancelled() const {
980 virtual void Start() {
981 pkgAcquireStatus::Start();
982 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
985 virtual void Stop() {
986 pkgAcquireStatus::Stop();
987 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
988 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
992 /* Database Interface {{{ */
993 typedef std::map< unsigned long, _H<Source> > SourceMap;
995 @interface Database : NSObject {
1001 pkgCacheFile cache_;
1002 pkgDepCache::Policy *policy_;
1003 pkgRecords *records_;
1004 pkgProblemResolver *resolver_;
1005 pkgAcquire *fetcher_;
1007 SPtr<pkgPackageManager> manager_;
1008 pkgSourceList *list_;
1010 SourceMap sourceMap_;
1011 _H<NSMutableArray> sourceList_;
1013 CFMutableArrayRef packages_;
1015 _transient NSObject<DatabaseDelegate> *delegate_;
1016 _transient NSObject<ProgressDelegate> *progress_;
1024 std::map<const char *, _H<NSString> > sections_;
1027 + (Database *) sharedInstance;
1030 - (void) _readCydia:(NSNumber *)fd;
1031 - (void) _readStatus:(NSNumber *)fd;
1032 - (void) _readOutput:(NSNumber *)fd;
1036 - (Package *) packageWithName:(NSString *)name;
1038 - (pkgCacheFile &) cache;
1039 - (pkgDepCache::Policy *) policy;
1040 - (pkgRecords *) records;
1041 - (pkgProblemResolver *) resolver;
1042 - (pkgAcquire &) fetcher;
1043 - (pkgSourceList &) list;
1044 - (NSArray *) packages;
1045 - (NSArray *) sources;
1046 - (Source *) sourceWithKey:(NSString *)key;
1047 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1055 - (void) updateWithStatus:(Status &)status;
1057 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1059 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1060 - (NSObject<ProgressDelegate> *) progressDelegate;
1062 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1064 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1068 /* ProgressEvent Implementation {{{ */
1069 @implementation CydiaProgressEvent
1071 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1072 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1075 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1076 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1077 [event setPackage:package];
1081 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1082 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1084 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1085 NSArray *fields([description componentsSeparatedByString:@" "]);
1086 [event setItem:fields];
1088 if ([fields count] > 3) {
1089 [event setPackage:[fields objectAtIndex:2]];
1090 [event setVersion:[fields objectAtIndex:3]];
1093 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1098 + (NSArray *) _attributeKeys {
1099 return [NSArray arrayWithObjects:
1109 - (NSArray *) attributeKeys {
1110 return [[self class] _attributeKeys];
1113 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1114 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1117 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1118 if ((self = [super init]) != nil) {
1124 - (NSString *) message {
1128 - (NSString *) type {
1132 - (NSArray *) item {
1133 return (id) item_ ?: [NSNull null];
1136 - (void) setItem:(NSArray *)item {
1140 - (NSString *) package {
1141 return (id) package_ ?: [NSNull null];
1144 - (void) setPackage:(NSString *)package {
1148 - (NSString *) url {
1149 return (id) url_ ?: [NSNull null];
1152 - (void) setURL:(NSString *)url {
1156 - (void) setVersion:(NSString *)version {
1160 - (NSString *) version {
1161 return (id) version_ ?: [NSNull null];
1164 - (NSString *) compound:(NSString *)value {
1166 NSString *mode(nil); {
1167 NSString *type([self type]);
1168 if ([type isEqualToString:kCydiaProgressEventTypeError])
1169 mode = UCLocalize("ERROR");
1170 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1171 mode = UCLocalize("WARNING");
1175 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1181 - (NSString *) compoundMessage {
1182 return [self compound:[self message]];
1185 - (NSString *) compoundTitle {
1188 if (package_ == nil)
1190 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1191 title = [package name];
1195 return [self compound:title];
1201 // Cytore Definitions {{{
1202 struct PackageValue :
1205 Cytore::Offset<PackageValue> next_;
1207 uint32_t index_ : 23;
1208 uint32_t subscribed_ : 1;
1225 Cytore::Offset<PackageValue> packages_[1 << 16];
1228 static Cytore::File<MetaValue> MetaFile_;
1230 // Cytore Helper Functions {{{
1231 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1232 SplitHash nhash = { hashlittle(name, length) };
1234 PackageValue *metadata;
1236 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1237 offset: if (offset->IsNull()) {
1238 *offset = MetaFile_.New<PackageValue>(length + 1);
1239 metadata = &MetaFile_.Get(*offset);
1241 if (metadata == NULL) {
1245 metadata = new PackageValue();
1246 memset(metadata, 0, sizeof(*metadata));
1249 memcpy(metadata->name_, name, length + 1);
1250 metadata->nhash_ = nhash.u16[1];
1252 metadata = &MetaFile_.Get(*offset);
1254 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1255 offset = &metadata->next_;
1263 static void PackageImport(const void *key, const void *value, void *context) {
1264 bool &fail(*reinterpret_cast<bool *>(context));
1267 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1268 NSLog(@"failed to import package %@", key);
1272 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1273 NSDictionary *package((NSDictionary *) value);
1275 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1276 if ([subscribed boolValue] && !metadata->subscribed_)
1277 metadata->subscribed_ = true;
1279 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1280 time_t time([date timeIntervalSince1970]);
1281 if (metadata->first_ > time || metadata->first_ == 0)
1282 metadata->first_ = time;
1285 NSDate *date([package objectForKey:@"LastSeen"]);
1286 NSString *version([package objectForKey:@"LastVersion"]);
1288 if (date != nil && version != nil) {
1289 time_t time([date timeIntervalSince1970]);
1290 if (metadata->last_ < time || metadata->last_ == 0)
1291 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1292 size_t length(strlen(buffer));
1293 uint16_t vhash(hashlittle(buffer, length));
1295 size_t capped(std::min<size_t>(8, length));
1296 char *latest(buffer + length - capped);
1298 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1299 metadata->vhash_ = vhash;
1301 metadata->last_ = time;
1307 /* Source Class {{{ */
1308 @interface Source : NSObject {
1310 Database *database_;
1313 CYString depiction_;
1314 CYString description_;
1320 CYString distribution_;
1326 _H<NSString> authority_;
1328 CYString defaultIcon_;
1330 _H<NSDictionary> record_;
1334 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1336 - (NSComparisonResult) compareByName:(Source *)source;
1338 - (NSString *) depictionForPackage:(NSString *)package;
1339 - (NSString *) supportForPackage:(NSString *)package;
1341 - (metaIndex *) metaIndex;
1342 - (NSDictionary *) record;
1345 - (NSString *) rooturi;
1346 - (NSString *) distribution;
1347 - (NSString *) type;
1350 - (NSString *) host;
1352 - (NSString *) name;
1353 - (NSString *) shortDescription;
1354 - (NSString *) label;
1355 - (NSString *) origin;
1356 - (NSString *) version;
1358 - (NSString *) defaultIcon;
1359 - (NSURL *) iconURL;
1363 @implementation Source
1367 distribution_.clear();
1372 description_.clear();
1378 defaultIcon_.clear();
1385 + (NSString *) webScriptNameForSelector:(SEL)selector {
1387 else if (selector == @selector(addSection:))
1388 return @"addSection";
1389 else if (selector == @selector(getField:))
1391 else if (selector == @selector(removeSection:))
1392 return @"removeSection";
1393 else if (selector == @selector(remove))
1399 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1400 return [self webScriptNameForSelector:selector] == nil;
1403 + (NSArray *) _attributeKeys {
1404 return [NSArray arrayWithObjects:
1415 @"shortDescription",
1422 - (NSArray *) attributeKeys {
1423 return [[self class] _attributeKeys];
1426 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1427 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1430 - (metaIndex *) metaIndex {
1434 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1437 trusted_ = index->IsTrusted();
1439 uri_.set(pool, index->GetURI());
1440 distribution_.set(pool, index->GetDist());
1441 type_.set(pool, index->GetType());
1443 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1444 if (dindex != NULL) {
1445 base_.set(pool, dindex->MetaIndexURI(""));
1448 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1451 pkgTagFile tags(&fd);
1453 pkgTagSection section;
1460 {"default-icon", &defaultIcon_},
1461 {"depiction", &depiction_},
1462 {"description", &description_},
1464 {"origin", &origin_},
1465 {"support", &support_},
1466 {"version", &version_},
1469 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1470 const char *start, *end;
1472 if (section.Find(names[i].name_, start, end)) {
1473 CYString &value(*names[i].value_);
1474 value.set(pool, start, end - start);
1480 record_ = [Sources_ objectForKey:[self key]];
1482 NSURL *url([NSURL URLWithString:uri_]);
1486 host_ = [host_ lowercaseString];
1491 authority_ = [url path];
1494 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1495 if ((self = [super init]) != nil) {
1496 era_ = [database era];
1497 database_ = database;
1500 [self setMetaIndex:index inPool:pool];
1504 - (NSString *) getField:(NSString *)name {
1505 @synchronized (database_) {
1506 if ([database_ era] != era_ || index_ == NULL)
1509 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1514 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1519 pkgTagFile tags(&fd);
1521 pkgTagSection section;
1524 const char *start, *end;
1525 if (!section.Find([name UTF8String], start, end))
1526 return (NSString *) [NSNull null];
1528 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1531 - (NSComparisonResult) compareByName:(Source *)source {
1532 NSString *lhs = [self name];
1533 NSString *rhs = [source name];
1535 if ([lhs length] != 0 && [rhs length] != 0) {
1536 unichar lhc = [lhs characterAtIndex:0];
1537 unichar rhc = [rhs characterAtIndex:0];
1539 if (isalpha(lhc) && !isalpha(rhc))
1540 return NSOrderedAscending;
1541 else if (!isalpha(lhc) && isalpha(rhc))
1542 return NSOrderedDescending;
1545 return [lhs compare:rhs options:LaxCompareOptions_];
1548 - (NSString *) depictionForPackage:(NSString *)package {
1549 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1552 - (NSString *) supportForPackage:(NSString *)package {
1553 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1556 - (NSArray *) sections {
1557 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1560 - (void) _addSection:(NSString *)section {
1563 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1564 if (![sections containsObject:section]) {
1565 [sections addObject:section];
1569 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1574 - (bool) addSection:(NSString *)section {
1578 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1582 - (void) _removeSection:(NSString *)section {
1586 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1587 if ([sections containsObject:section]) {
1588 [sections removeObject:section];
1593 - (bool) removeSection:(NSString *)section {
1597 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1602 [Sources_ removeObjectForKey:[self key]];
1607 bool value(record_ != nil);
1608 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1612 - (NSDictionary *) record {
1620 - (NSString *) rooturi {
1624 - (NSString *) distribution {
1625 return distribution_;
1628 - (NSString *) type {
1632 - (NSString *) baseuri {
1633 return base_.empty() ? nil : (id) base_;
1636 - (NSString *) iconuri {
1637 if (NSString *base = [self baseuri])
1638 return [base stringByAppendingString:@"CydiaIcon.png"];
1643 - (NSURL *) iconURL {
1644 if (NSString *uri = [self iconuri])
1645 return [NSURL URLWithString:uri];
1649 - (NSString *) key {
1650 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1653 - (NSString *) host {
1657 - (NSString *) name {
1658 return origin_.empty() ? (id) authority_ : origin_;
1661 - (NSString *) shortDescription {
1662 return description_;
1665 - (NSString *) label {
1666 return label_.empty() ? (id) authority_ : label_;
1669 - (NSString *) origin {
1673 - (NSString *) version {
1677 - (NSString *) defaultIcon {
1678 return defaultIcon_;
1683 /* CydiaOperation Class {{{ */
1684 @interface CydiaOperation : NSObject {
1685 _H<NSString> operator_;
1686 _H<NSString> value_;
1689 - (NSString *) operator;
1690 - (NSString *) value;
1694 @implementation CydiaOperation
1696 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1697 if ((self = [super init]) != nil) {
1698 operator_ = [NSString stringWithUTF8String:_operator];
1699 value_ = [NSString stringWithUTF8String:value];
1703 + (NSArray *) _attributeKeys {
1704 return [NSArray arrayWithObjects:
1710 - (NSArray *) attributeKeys {
1711 return [[self class] _attributeKeys];
1714 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1715 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1718 - (NSString *) operator {
1722 - (NSString *) value {
1728 /* CydiaClause Class {{{ */
1729 @interface CydiaClause : NSObject {
1730 _H<NSString> package_;
1731 _H<CydiaOperation> version_;
1734 - (NSString *) package;
1735 - (CydiaOperation *) version;
1739 @implementation CydiaClause
1741 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1742 if ((self = [super init]) != nil) {
1743 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1745 if (const char *version = dep.TargetVer())
1746 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1748 version_ = (id) [NSNull null];
1752 + (NSArray *) _attributeKeys {
1753 return [NSArray arrayWithObjects:
1759 - (NSArray *) attributeKeys {
1760 return [[self class] _attributeKeys];
1763 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1764 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1767 - (NSString *) package {
1771 - (CydiaOperation *) version {
1777 /* CydiaRelation Class {{{ */
1778 @interface CydiaRelation : NSObject {
1779 _H<NSString> relationship_;
1780 _H<NSMutableArray> clauses_;
1783 - (NSString *) relationship;
1784 - (NSArray *) clauses;
1788 @implementation CydiaRelation
1790 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1791 if ((self = [super init]) != nil) {
1792 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1793 clauses_ = [NSMutableArray arrayWithCapacity:8];
1795 pkgCache::DepIterator start;
1796 pkgCache::DepIterator end;
1797 dep.GlobOr(start, end); // ++dep
1800 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1802 // yes, seriously. (wtf?)
1810 + (NSArray *) _attributeKeys {
1811 return [NSArray arrayWithObjects:
1817 - (NSArray *) attributeKeys {
1818 return [[self class] _attributeKeys];
1821 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1822 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1825 - (NSString *) relationship {
1826 return relationship_;
1829 - (NSArray *) clauses {
1833 - (void) addClause:(CydiaClause *)clause {
1834 [clauses_ addObject:clause];
1839 /* Package Class {{{ */
1840 struct ParsedPackage {
1844 CYString architecture_;
1847 CYString depiction_;
1857 @interface Package : NSObject {
1860 uint32_t essential_ : 1;
1861 uint32_t obsolete_ : 1;
1862 uint32_t ignored_ : 1;
1863 uint32_t pooled_ : 1;
1869 _transient Database *database_;
1871 pkgCache::VerIterator version_;
1872 pkgCache::PkgIterator iterator_;
1873 pkgCache::VerFileIterator file_;
1879 CYString installed_;
1881 const char *section_;
1882 _transient NSString *section$_;
1886 PackageValue *metadata_;
1887 ParsedPackage *parsed_;
1889 _H<NSMutableArray> tags_;
1892 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1893 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1895 - (pkgCache::PkgIterator) iterator;
1898 - (NSString *) section;
1899 - (NSString *) simpleSection;
1901 - (NSString *) longSection;
1902 - (NSString *) shortSection;
1906 - (MIMEAddress *) maintainer;
1908 - (NSString *) longDescription;
1909 - (NSString *) shortDescription;
1912 - (PackageValue *) metadata;
1915 - (bool) subscribed;
1916 - (bool) setSubscribed:(bool)subscribed;
1920 - (NSString *) latest;
1921 - (NSString *) installed;
1922 - (BOOL) uninstalled;
1925 - (BOOL) upgradableAndEssential:(BOOL)essential;
1928 - (BOOL) unfiltered;
1932 - (BOOL) halfConfigured;
1933 - (BOOL) halfInstalled;
1935 - (NSString *) mode;
1938 - (NSString *) name;
1940 - (NSString *) homepage;
1941 - (NSString *) depiction;
1942 - (MIMEAddress *) author;
1944 - (NSString *) support;
1946 - (NSArray *) files;
1947 - (NSArray *) warnings;
1948 - (NSArray *) applications;
1950 - (Source *) source;
1953 - (BOOL) matches:(NSArray *)query;
1955 - (bool) hasSupportingRole;
1956 - (BOOL) hasTag:(NSString *)tag;
1957 - (NSString *) primaryPurpose;
1958 - (NSArray *) purposes;
1959 - (bool) isCommercial;
1961 - (void) setIndex:(size_t)index;
1963 - (CYString &) cyname;
1965 - (uint32_t) compareBySection:(NSArray *)sections;
1970 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1971 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1972 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1973 - (bool) isVisibleInSection:(NSString *)section;
1974 - (bool) isVisibleInSource:(Source *)source;
1978 uint32_t PackageChangesRadix(Package *self, void *) {
1983 uint32_t timestamp : 30;
1984 uint32_t ignored : 1;
1985 uint32_t upgradable : 1;
1989 bool upgradable([self upgradableAndEssential:YES]);
1990 value.bits.upgradable = upgradable ? 1 : 0;
1993 value.bits.timestamp = 0;
1994 value.bits.ignored = [self ignored] ? 0 : 1;
1995 value.bits.upgradable = 1;
1997 value.bits.timestamp = [self seen] >> 2;
1998 value.bits.ignored = 0;
1999 value.bits.upgradable = 0;
2002 return _not(uint32_t) - value.key;
2005 uint32_t PackagePrefixRadix(Package *self, void *context) {
2006 size_t offset(reinterpret_cast<size_t>(context));
2007 CYString &name([self cyname]);
2009 size_t size(name.size());
2012 char *text(name.data());
2015 if (!isdigit(text[0]))
2019 while (size != digits && isdigit(text[digits]))
2027 if (offset == 0 && zeros != 0) {
2028 memset(data, '0', zeros);
2029 memcpy(data + zeros, text, 4 - zeros);
2031 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2032 if (size <= offset - zeros)
2035 text += offset - zeros;
2036 size -= offset - zeros;
2039 memcpy(data, text, 4);
2041 memcpy(data, text, size);
2042 memset(data + size, 0, 4 - size);
2045 for (size_t i(0); i != 4; ++i)
2046 if (isalpha(data[i]))
2054 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2056 /* XXX: ntohl may be more honest */
2057 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2060 CYString &(*PackageName)(Package *self, SEL sel);
2062 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2063 _profile(PackageNameCompare)
2064 CYString &lhi(PackageName(lhs, @selector(cyname)));
2065 CYString &rhi(PackageName(rhs, @selector(cyname)));
2066 CFStringRef lhn(lhi), rhn(rhi);
2069 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2070 else if (rhn == NULL)
2071 return NSOrderedDescending;
2073 _profile(PackageNameCompare$NumbersLast)
2074 if (!lhi.empty() && !rhi.empty()) {
2075 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2076 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2077 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2078 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2079 return lha ? NSOrderedAscending : NSOrderedDescending;
2083 CFIndex length = CFStringGetLength(lhn);
2085 _profile(PackageNameCompare$Compare)
2086 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2091 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2092 return PackageNameCompare(*lhs, *rhs, context);
2095 struct PackageNameOrdering :
2096 std::binary_function<Package *, Package *, bool>
2098 _finline bool operator ()(Package *lhs, Package *rhs) const {
2099 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2103 @implementation Package
2105 - (NSString *) description {
2106 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2111 apr_pool_destroy(pool_);
2112 if (parsed_ != NULL)
2117 + (NSString *) webScriptNameForSelector:(SEL)selector {
2119 else if (selector == @selector(clear))
2121 else if (selector == @selector(getField:))
2123 else if (selector == @selector(hasTag:))
2125 else if (selector == @selector(install))
2127 else if (selector == @selector(remove))
2133 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2134 return [self webScriptNameForSelector:selector] == nil;
2137 + (NSArray *) _attributeKeys {
2138 return [NSArray arrayWithObjects:
2159 @"shortDescription",
2172 - (NSArray *) attributeKeys {
2173 return [[self class] _attributeKeys];
2176 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2177 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2180 - (NSArray *) relations {
2181 @synchronized (database_) {
2182 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2183 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2184 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2188 - (NSString *) architecture {
2190 @synchronized (database_) {
2191 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2194 - (NSString *) getField:(NSString *)name {
2195 @synchronized (database_) {
2196 if ([database_ era] != era_ || file_.end())
2199 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2201 const char *start, *end;
2202 if (!parser.Find([name UTF8String], start, end))
2203 return (NSString *) [NSNull null];
2205 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2209 if (parsed_ != NULL)
2211 @synchronized (database_) {
2212 if ([database_ era] != era_ || file_.end())
2215 ParsedPackage *parsed(new ParsedPackage);
2218 _profile(Package$parse)
2219 pkgRecords::Parser *parser;
2221 _profile(Package$parse$Lookup)
2222 parser = &[database_ records]->Lookup(file_);
2227 _profile(Package$parse$Find)
2232 {"architecture", &parsed->architecture_},
2233 {"icon", &parsed->icon_},
2234 {"depiction", &parsed->depiction_},
2235 {"homepage", &parsed->homepage_},
2236 {"website", &website},
2237 {"bugs", &parsed->bugs_},
2238 {"support", &parsed->support_},
2239 {"sponsor", &parsed->sponsor_},
2240 {"author", &parsed->author_},
2241 {"md5sum", &parsed->md5sum_},
2244 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2245 const char *start, *end;
2247 if (parser->Find(names[i].name_, start, end)) {
2248 CYString &value(*names[i].value_);
2249 _profile(Package$parse$Value)
2250 value.set(pool_, start, end - start);
2256 _profile(Package$parse$Tagline)
2257 const char *start, *end;
2258 if (parser->ShortDesc(start, end)) {
2259 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2262 while (stop != start && stop[-1] == '\r')
2264 parsed->tagline_.set(pool_, start, stop - start);
2268 _profile(Package$parse$Retain)
2269 if (parsed->homepage_.empty())
2270 parsed->homepage_ = website;
2271 if (parsed->homepage_ == parsed->depiction_)
2272 parsed->homepage_.clear();
2277 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2278 if ((self = [super init]) != nil) {
2279 _profile(Package$initWithVersion)
2281 apr_pool_create(&pool_, NULL);
2287 database_ = database;
2288 era_ = [database era];
2292 pkgCache::PkgIterator iterator(version.ParentPkg());
2293 iterator_ = iterator;
2295 _profile(Package$initWithVersion$Version)
2296 if (!version_.end())
2297 file_ = version_.FileList();
2299 pkgCache &cache([database_ cache]);
2300 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2304 _profile(Package$initWithVersion$Cache)
2305 name_.set(NULL, iterator.Display());
2307 latest_.set(NULL, StripVersion_(version_.VerStr()));
2309 pkgCache::VerIterator current(iterator.CurrentVer());
2311 installed_.set(NULL, StripVersion_(current.VerStr()));
2314 _profile(Package$initWithVersion$Tags)
2315 pkgCache::TagIterator tag(iterator.TagList());
2317 tags_ = [NSMutableArray arrayWithCapacity:8];
2319 const char *name(tag.Name());
2320 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2322 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2323 if (strcmp(name + 6, "enduser") == 0)
2325 else if (strcmp(name + 6, "hacker") == 0)
2327 else if (strcmp(name + 6, "developer") == 0)
2329 else if (strcmp(name + 6, "cydia") == 0)
2335 if (strncmp(name, "cydia::", 7) == 0) {
2336 if (strcmp(name + 7, "essential") == 0)
2338 else if (strcmp(name + 7, "obsolete") == 0)
2343 } while (!tag.end());
2347 _profile(Package$initWithVersion$Metadata)
2348 const char *mixed(iterator.Name());
2349 size_t size(strlen(mixed));
2350 char lower[size + 1];
2352 for (size_t i(0); i != size; ++i)
2353 lower[i] = mixed[i] | 0x20;
2356 PackageValue *metadata(PackageFind(lower, size));
2357 metadata_ = metadata;
2359 id_.set(NULL, metadata->name_, size);
2361 const char *latest(version_.VerStr());
2362 size_t length(strlen(latest));
2364 uint16_t vhash(hashlittle(latest, length));
2366 size_t capped(std::min<size_t>(8, length));
2367 latest = latest + length - capped;
2369 if (metadata->first_ == 0)
2370 metadata->first_ = now_;
2372 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2373 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2374 metadata->vhash_ = vhash;
2375 metadata->last_ = now_;
2376 } else if (metadata->last_ == 0)
2377 metadata->last_ = metadata->first_;
2380 _profile(Package$initWithVersion$Section)
2381 section_ = version_.Section();
2384 _profile(Package$initWithVersion$Flags)
2385 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2386 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2391 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2392 pkgCache::VerIterator version;
2394 _profile(Package$packageWithIterator$GetCandidateVer)
2395 version = [database policy]->GetCandidateVer(iterator);
2403 _profile(Package$packageWithIterator$Allocate)
2404 package = [Package allocWithZone:zone];
2407 _profile(Package$packageWithIterator$Initialize)
2409 initWithVersion:version
2416 _profile(Package$packageWithIterator$Autorelease)
2417 package = [package autorelease];
2423 - (pkgCache::PkgIterator) iterator {
2427 - (NSString *) section {
2428 if (section$_ == nil) {
2429 if (section_ == NULL)
2432 _profile(Package$section$mappedSectionForPointer)
2433 section$_ = [database_ mappedSectionForPointer:section_];
2438 - (NSString *) simpleSection {
2439 if (NSString *section = [self section])
2440 return Simplify(section);
2445 - (NSString *) longSection {
2446 return LocalizeSection([self section]);
2449 - (NSString *) shortSection {
2450 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2453 - (NSString *) uri {
2456 pkgIndexFile *index;
2457 pkgCache::PkgFileIterator file(file_.File());
2458 if (![database_ list].FindIndex(file, index))
2460 return [NSString stringWithUTF8String:iterator_->Path];
2461 //return [NSString stringWithUTF8String:file.Site()];
2462 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2466 - (MIMEAddress *) maintainer {
2467 @synchronized (database_) {
2468 if ([database_ era] != era_ || file_.end())
2471 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2472 const std::string &maintainer(parser->Maintainer());
2473 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2476 - (NSString *) md5sum {
2477 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2481 @synchronized (database_) {
2482 if ([database_ era] != era_ || version_.end())
2485 return version_->InstalledSize;
2488 - (NSString *) longDescription {
2489 @synchronized (database_) {
2490 if ([database_ era] != era_ || file_.end())
2493 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2494 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2496 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2497 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2498 if ([lines count] < 2)
2501 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2502 for (size_t i(1), e([lines count]); i != e; ++i) {
2503 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2504 [trimmed addObject:trim];
2507 return [trimmed componentsJoinedByString:@"\n"];
2510 - (NSString *) shortDescription {
2511 if (parsed_ != NULL)
2512 return static_cast<NSString *>(parsed_->tagline_);
2514 @synchronized (database_) {
2515 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2517 const char *start, *end;
2518 if (!parser.ShortDesc(start, end))
2521 if (end - start > 200)
2525 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2528 while (end != start && end[-1] == '\r')
2532 return [(id) CYStringCreate(start, end - start) autorelease];
2536 _profile(Package$index)
2537 CFStringRef name((CFStringRef) [self name]);
2538 if (CFStringGetLength(name) == 0)
2540 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2541 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2543 return toupper(character);
2547 - (PackageValue *) metadata {
2552 PackageValue *metadata([self metadata]);
2553 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2556 - (bool) subscribed {
2557 return [self metadata]->subscribed_;
2560 - (bool) setSubscribed:(bool)subscribed {
2561 PackageValue *metadata([self metadata]);
2562 if (metadata->subscribed_ == subscribed)
2564 metadata->subscribed_ = subscribed;
2572 - (NSString *) latest {
2576 - (NSString *) installed {
2580 - (BOOL) uninstalled {
2581 return installed_.empty();
2585 return !version_.end();
2588 - (BOOL) upgradableAndEssential:(BOOL)essential {
2589 _profile(Package$upgradableAndEssential)
2590 pkgCache::VerIterator current(iterator_.CurrentVer());
2592 return essential && essential_;
2594 return !version_.end() && version_ != current;
2598 - (BOOL) essential {
2603 return [database_ cache][iterator_].InstBroken();
2606 - (BOOL) unfiltered {
2607 _profile(Package$unfiltered$obsolete)
2608 if (_unlikely(obsolete_))
2612 _profile(Package$unfiltered$hasSupportingRole)
2613 if (_unlikely(![self hasSupportingRole]))
2621 if (![self unfiltered])
2626 _profile(Package$visible$section)
2627 section = [self section];
2630 _profile(Package$visible$isSectionVisible)
2631 if (!isSectionVisible(section))
2639 unsigned char current(iterator_->CurrentState);
2640 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2643 - (BOOL) halfConfigured {
2644 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2647 - (BOOL) halfInstalled {
2648 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2652 @synchronized (database_) {
2653 if ([database_ era] != era_ || iterator_.end())
2656 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2657 return state.Mode != pkgDepCache::ModeKeep;
2660 - (NSString *) mode {
2661 @synchronized (database_) {
2662 if ([database_ era] != era_ || iterator_.end())
2665 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2667 switch (state.Mode) {
2668 case pkgDepCache::ModeDelete:
2669 if ((state.iFlags & pkgDepCache::Purge) != 0)
2673 case pkgDepCache::ModeKeep:
2674 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2675 return @"REINSTALL";
2676 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2680 case pkgDepCache::ModeInstall:
2681 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2682 return @"REINSTALL";
2683 else*/ switch (state.Status) {
2685 return @"DOWNGRADE";
2691 return @"NEW_INSTALL";
2702 - (NSString *) name {
2703 return name_.empty() ? id_ : name_;
2706 - (UIImage *) icon {
2707 NSString *section = [self simpleSection];
2710 if (parsed_ != NULL)
2711 if (NSString *href = parsed_->icon_)
2712 if ([href hasPrefix:@"file:///"])
2713 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2714 if (icon == nil) if (section != nil)
2715 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2716 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2717 if ([dicon hasPrefix:@"file:///"])
2718 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2720 icon = [UIImage applicationImageNamed:@"unknown.png"];
2724 - (NSString *) homepage {
2725 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2728 - (NSString *) depiction {
2729 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2732 - (MIMEAddress *) sponsor {
2733 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2736 - (MIMEAddress *) author {
2737 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2740 - (NSString *) support {
2741 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2744 - (NSArray *) files {
2745 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2746 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2749 fin.open([path UTF8String]);
2754 while (std::getline(fin, line))
2755 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2760 - (NSString *) state {
2761 @synchronized (database_) {
2762 if ([database_ era] != era_ || file_.end())
2765 switch (iterator_->CurrentState) {
2766 case pkgCache::State::NotInstalled:
2767 return @"NotInstalled";
2768 case pkgCache::State::UnPacked:
2770 case pkgCache::State::HalfConfigured:
2771 return @"HalfConfigured";
2772 case pkgCache::State::HalfInstalled:
2773 return @"HalfInstalled";
2774 case pkgCache::State::ConfigFiles:
2775 return @"ConfigFiles";
2776 case pkgCache::State::Installed:
2777 return @"Installed";
2778 case pkgCache::State::TriggersAwaited:
2779 return @"TriggersAwaited";
2780 case pkgCache::State::TriggersPending:
2781 return @"TriggersPending";
2784 return (NSString *) [NSNull null];
2787 - (NSString *) selection {
2788 @synchronized (database_) {
2789 if ([database_ era] != era_ || file_.end())
2792 switch (iterator_->SelectedState) {
2793 case pkgCache::State::Unknown:
2795 case pkgCache::State::Install:
2797 case pkgCache::State::Hold:
2799 case pkgCache::State::DeInstall:
2800 return @"DeInstall";
2801 case pkgCache::State::Purge:
2805 return (NSString *) [NSNull null];
2808 - (NSArray *) warnings {
2809 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2810 const char *name(iterator_.Name());
2812 size_t length(strlen(name));
2813 if (length < 2) invalid:
2814 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2815 else for (size_t i(0); i != length; ++i)
2817 /* XXX: technically this is not allowed */
2818 (name[i] < 'A' || name[i] > 'Z') &&
2819 (name[i] < 'a' || name[i] > 'z') &&
2820 (name[i] < '0' || name[i] > '9') &&
2821 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2824 if (strcmp(name, "cydia") != 0) {
2827 bool _private = false;
2830 bool repository = [[self section] isEqualToString:@"Repositories"];
2832 if (NSArray *files = [self files])
2833 for (NSString *file in files)
2834 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2836 else if (!user && [file isEqualToString:@"/User"])
2838 else if (!_private && [file isEqualToString:@"/private"])
2840 else if (!stash && [file isEqualToString:@"/var/stash"])
2843 /* XXX: this is not sensitive enough. only some folders are valid. */
2844 if (cydia && !repository)
2845 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2847 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2849 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2851 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2854 return [warnings count] == 0 ? nil : warnings;
2857 - (NSArray *) applications {
2858 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2860 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2862 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2863 if (NSArray *files = [self files])
2864 for (NSString *file in files)
2865 if (application_r(file)) {
2866 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2867 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2868 if ([id isEqualToString:me])
2871 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2873 display = application_r[1];
2875 NSString *bundle([file stringByDeletingLastPathComponent]);
2876 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2877 if (icon == nil || [icon length] == 0)
2879 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2881 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2882 [applications addObject:application];
2884 [application addObject:id];
2885 [application addObject:display];
2886 [application addObject:url];
2889 return [applications count] == 0 ? nil : applications;
2892 - (Source *) source {
2893 if (source_ == nil) {
2894 @synchronized (database_) {
2895 if ([database_ era] != era_ || file_.end())
2896 source_ = (Source *) [NSNull null];
2898 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2902 return source_ == (Source *) [NSNull null] ? nil : source_;
2909 - (BOOL) matches:(NSArray *)query {
2910 if (query == nil || [query count] == 0)
2919 string = [self name];
2920 length = [string length];
2922 for (NSString *term in query) {
2923 range = [string rangeOfString:term options:MatchCompareOptions_];
2924 if (range.location != NSNotFound)
2925 rank_ -= 6 * 1000000 / length;
2930 length = [string length];
2932 for (NSString *term in query) {
2933 range = [string rangeOfString:term options:MatchCompareOptions_];
2934 if (range.location != NSNotFound)
2935 rank_ -= 6 * 1000000 / length;
2939 string = [self shortDescription];
2940 length = [string length];
2941 NSUInteger stop(std::min<NSUInteger>(length, 200));
2943 for (NSString *term in query) {
2944 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2945 if (range.location != NSNotFound)
2946 rank_ -= 2 * 100000;
2952 - (bool) hasSupportingRole {
2957 if ([Role_ isEqualToString:@"User"])
2961 if ([Role_ isEqualToString:@"Hacker"])
2965 if ([Role_ isEqualToString:@"Developer"])
2970 - (NSArray *) tags {
2974 - (BOOL) hasTag:(NSString *)tag {
2975 return tags_ == nil ? NO : [tags_ containsObject:tag];
2978 - (NSString *) primaryPurpose {
2979 for (NSString *tag in (NSArray *) tags_)
2980 if ([tag hasPrefix:@"purpose::"])
2981 return [tag substringFromIndex:9];
2985 - (NSArray *) purposes {
2986 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2987 for (NSString *tag in (NSArray *) tags_)
2988 if ([tag hasPrefix:@"purpose::"])
2989 [purposes addObject:[tag substringFromIndex:9]];
2990 return [purposes count] == 0 ? nil : purposes;
2993 - (bool) isCommercial {
2994 return [self hasTag:@"cydia::commercial"];
2997 - (void) setIndex:(size_t)index {
2998 if (metadata_->index_ != index)
2999 metadata_->index_ = index;
3002 - (CYString &) cyname {
3003 return name_.empty() ? id_ : name_;
3006 - (uint32_t) compareBySection:(NSArray *)sections {
3007 NSString *section([self section]);
3008 for (size_t i(0), e([sections count]); i != e; ++i) {
3009 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3013 return _not(uint32_t);
3017 @synchronized (database_) {
3018 pkgProblemResolver *resolver = [database_ resolver];
3019 resolver->Clear(iterator_);
3021 pkgCacheFile &cache([database_ cache]);
3022 cache->SetReInstall(iterator_, false);
3023 cache->MarkKeep(iterator_, false);
3027 @synchronized (database_) {
3028 pkgProblemResolver *resolver = [database_ resolver];
3029 resolver->Clear(iterator_);
3030 resolver->Protect(iterator_);
3032 pkgCacheFile &cache([database_ cache]);
3033 cache->SetReInstall(iterator_, false);
3034 cache->MarkInstall(iterator_, false);
3036 pkgDepCache::StateCache &state((*cache)[iterator_]);
3037 if (!state.Install())
3038 cache->SetReInstall(iterator_, true);
3042 @synchronized (database_) {
3043 pkgProblemResolver *resolver = [database_ resolver];
3044 resolver->Clear(iterator_);
3045 resolver->Remove(iterator_);
3046 resolver->Protect(iterator_);
3048 pkgCacheFile &cache([database_ cache]);
3049 cache->SetReInstall(iterator_, false);
3050 cache->MarkDelete(iterator_, true);
3053 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3054 _profile(Package$isUnfilteredAndSearchedForBy)
3057 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3058 value &= [self unfiltered];
3061 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3062 value &= [self matches:query];
3069 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3070 if ([search length] == 0)
3073 _profile(Package$isUnfilteredAndSelectedForBy)
3076 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3077 value &= [self unfiltered];
3080 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3081 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3088 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3089 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3092 - (bool) isVisibleInSection:(NSString *)name {
3093 NSString *section([self section]);
3097 section == nil && [name length] == 0 ||
3098 [name isEqualToString:section]
3099 ) && [self visible];
3102 - (bool) isVisibleInSource:(Source *)source {
3103 return [self source] == source && [self visible];
3108 /* Section Class {{{ */
3109 @interface Section : NSObject {
3114 _H<NSString> localized_;
3117 - (NSComparisonResult) compareByLocalized:(Section *)section;
3118 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3119 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3120 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3121 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3122 - (NSString *) name;
3129 - (void) addToCount;
3131 - (void) setCount:(size_t)count;
3132 - (NSString *) localized;
3136 @implementation Section
3138 - (NSComparisonResult) compareByLocalized:(Section *)section {
3139 NSString *lhs(localized_);
3140 NSString *rhs([section localized]);
3142 /*if ([lhs length] != 0 && [rhs length] != 0) {
3143 unichar lhc = [lhs characterAtIndex:0];
3144 unichar rhc = [rhs characterAtIndex:0];
3146 if (isalpha(lhc) && !isalpha(rhc))
3147 return NSOrderedAscending;
3148 else if (!isalpha(lhc) && isalpha(rhc))
3149 return NSOrderedDescending;
3152 return [lhs compare:rhs options:LaxCompareOptions_];
3155 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3156 if ((self = [self initWithName:name localize:NO]) != nil) {
3157 if (localized != nil)
3158 localized_ = localized;
3162 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3163 return [self initWithName:name row:0 localize:localize];
3166 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3167 if ((self = [super init]) != nil) {
3172 localized_ = LocalizeSection(name_);
3176 /* XXX: localize the index thingees */
3177 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3178 if ((self = [super init]) != nil) {
3179 name_ = [NSString stringWithCharacters:&index length:1];
3185 - (NSString *) name {
3205 - (void) addToCount {
3209 - (void) setCount:(size_t)count {
3213 - (NSString *) localized {
3220 class CydiaLogCleaner :
3221 public pkgArchiveCleaner
3224 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3229 /* Database Implementation {{{ */
3230 @implementation Database
3232 + (Database *) sharedInstance {
3233 static _H<Database> instance;
3234 if (instance == nil)
3235 instance = [[[Database alloc] init] autorelease];
3243 - (void) releasePackages {
3244 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3245 CFArrayRemoveAllValues(packages_);
3249 // XXX: actually implement this thing
3251 [self releasePackages];
3252 apr_pool_destroy(pool_);
3253 NSRecycleZone(zone_);
3257 - (void) _readCydia:(NSNumber *)fd {
3258 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3259 std::istream is(&ib);
3262 static Pcre finish_r("^finish:([^:]*)$");
3264 while (std::getline(is, line)) {
3265 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3267 const char *data(line.c_str());
3268 size_t size = line.size();
3269 lprintf("C:%s\n", data);
3271 if (finish_r(data, size)) {
3272 NSString *finish = finish_r[1];
3273 int index = [Finishes_ indexOfObject:finish];
3274 if (index != INT_MAX && index > Finish_)
3284 - (void) _readStatus:(NSNumber *)fd {
3285 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3286 std::istream is(&ib);
3289 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3290 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3292 while (std::getline(is, line)) {
3293 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3295 const char *data(line.c_str());
3296 size_t size(line.size());
3297 lprintf("S:%s\n", data);
3299 if (conffile_r(data, size)) {
3300 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3301 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3302 } else if (strncmp(data, "status: ", 8) == 0) {
3303 // status: <package>: {unpacked,half-configured,installed}
3304 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3305 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3306 } else if (strncmp(data, "processing: ", 12) == 0) {
3307 // processing: configure: config-test
3308 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3309 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3310 } else if (pmstatus_r(data, size)) {
3311 std::string type([pmstatus_r[1] UTF8String]);
3313 NSString *package = pmstatus_r[2];
3314 if ([package isEqualToString:@"dpkg-exec"])
3317 float percent([pmstatus_r[3] floatValue]);
3318 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3320 NSString *string = pmstatus_r[4];
3322 if (type == "pmerror") {
3323 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3324 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3325 } else if (type == "pmstatus") {
3326 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3327 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3328 } else if (type == "pmconffile")
3329 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3331 lprintf("E:unknown pmstatus\n");
3333 lprintf("E:unknown status\n");
3341 - (void) _readOutput:(NSNumber *)fd {
3342 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3343 std::istream is(&ib);
3346 while (std::getline(is, line)) {
3347 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3349 lprintf("O:%s\n", line.c_str());
3351 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3352 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3364 - (Package *) packageWithName:(NSString *)name {
3367 @synchronized (self) {
3368 if (static_cast<pkgDepCache *>(cache_) == NULL)
3370 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3371 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3375 if ((self = [super init]) != nil) {
3382 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3383 apr_pool_create(&pool_, NULL);
3385 size_t capacity(MetaFile_->active_);
3391 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3392 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3396 _assert(pipe(fds) != -1);
3399 _config->Set("APT::Keep-Fds::", cydiafd_);
3400 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3403 detachNewThreadSelector:@selector(_readCydia:)
3405 withObject:[NSNumber numberWithInt:fds[0]]
3408 _assert(pipe(fds) != -1);
3412 detachNewThreadSelector:@selector(_readStatus:)
3414 withObject:[NSNumber numberWithInt:fds[0]]
3417 _assert(pipe(fds) != -1);
3418 _assert(dup2(fds[0], 0) != -1);
3419 _assert(close(fds[0]) != -1);
3421 input_ = fdopen(fds[1], "a");
3423 _assert(pipe(fds) != -1);
3424 _assert(dup2(fds[1], 1) != -1);
3425 _assert(close(fds[1]) != -1);
3428 detachNewThreadSelector:@selector(_readOutput:)
3430 withObject:[NSNumber numberWithInt:fds[0]]
3435 - (pkgCacheFile &) cache {
3439 - (pkgDepCache::Policy *) policy {
3443 - (pkgRecords *) records {
3447 - (pkgProblemResolver *) resolver {
3451 - (pkgAcquire &) fetcher {
3455 - (pkgSourceList &) list {
3459 - (NSArray *) packages {
3460 return (NSArray *) packages_;
3463 - (NSArray *) sources {
3467 - (Source *) sourceWithKey:(NSString *)key {
3468 for (Source *source in [self sources]) {
3469 if ([[source key] isEqualToString:key])
3474 - (bool) popErrorWithTitle:(NSString *)title {
3477 while (!_error->empty()) {
3479 bool warning(!_error->PopMessage(error));
3484 size_t size(error.size());
3485 if (size == 0 || error[size - 1] != '\n')
3487 error.resize(size - 1);
3490 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3492 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3493 if (warning && no_pubkey(error.c_str()))
3496 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3502 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3503 return [self popErrorWithTitle:title] || !success;
3506 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3507 @synchronized (self) {
3510 [self releasePackages];
3513 [sourceList_ removeAllObjects];
3533 apr_pool_clear(pool_);
3535 NSRecycleZone(zone_);
3536 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3538 int chk(creat("/tmp/cydia.chk", 0644));
3542 if (invocation != nil)
3543 [invocation invoke];
3545 NSString *title(UCLocalize("DATABASE"));
3547 list_ = new pkgSourceList();
3548 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3551 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3552 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3553 [sourceList_ addObject:object];
3557 OpProgress progress;
3558 while (!cache_.Open(progress, true)) { pop:
3560 bool warning(!_error->PopMessage(error));
3561 lprintf("cache_.Open():[%s]\n", error.c_str());
3563 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3564 [delegate_ repairWithSelector:@selector(configure)];
3565 else if (error == "The package lists or status file could not be parsed or opened.")
3566 [delegate_ repairWithSelector:@selector(update)];
3567 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3568 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3569 // else if (error == "Malformed Status line")
3570 // else if (error == "The list of sources could not be read.")
3572 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3582 unlink("/tmp/cydia.chk");
3584 now_ = [[NSDate date] timeIntervalSince1970];
3586 policy_ = new pkgDepCache::Policy();
3587 records_ = new pkgRecords(cache_);
3588 resolver_ = new pkgProblemResolver(cache_);
3589 fetcher_ = new pkgAcquire(&status_);
3592 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3593 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3597 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3600 if (cache_->BrokenCount() != 0) {
3601 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3604 if (cache_->BrokenCount() != 0) {
3605 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3609 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3613 for (Source *object in (id) sourceList_) {
3614 metaIndex *source([object metaIndex]);
3615 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3616 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3617 // XXX: this could be more intelligent
3618 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3619 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3621 sourceMap_[cached->ID] = object;
3626 /*std::vector<Package *> packages;
3627 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3632 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3633 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3634 //packages.push_back(package);
3635 CFArrayAppendValue(packages_, CFRetain(package));
3639 /*if (packages.empty())
3640 packages_ = [[NSArray alloc] init];
3642 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3645 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3646 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3647 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3655 /*if (!packages.empty())
3656 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3657 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3659 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3661 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3663 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3667 size_t count(CFArrayGetCount(packages_));
3668 MetaFile_->active_ = count;
3670 for (size_t index(0); index != count; ++index)
3671 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3678 @synchronized (self) {
3680 resolver_ = new pkgProblemResolver(cache_);
3682 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3683 if (!cache_[iterator].Keep())
3684 cache_->MarkKeep(iterator, false);
3685 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3686 cache_->SetReInstall(iterator, false);
3689 - (void) configure {
3690 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3692 system([dpkg UTF8String]);
3697 @synchronized (self) {
3698 // XXX: I don't remember this condition
3703 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3705 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3707 if ([self popErrorWithTitle:title])
3711 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3713 CydiaLogCleaner cleaner;
3714 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3721 fetcher_->Shutdown();
3723 pkgRecords records(cache_);
3725 lock_ = new FileFd();
3726 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3728 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3730 if ([self popErrorWithTitle:title])
3734 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3737 manager_ = (_system->CreatePM(cache_));
3738 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3745 bool substrate(RestartSubstrate_);
3746 RestartSubstrate_ = false;
3748 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3750 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3752 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3754 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3755 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3758 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3760 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3762 [self popErrorWithTitle:title];
3766 bool failed = false;
3767 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3768 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3770 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3773 std::string uri = (*item)->DescURI();
3774 std::string error = (*item)->ErrorText;
3776 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3779 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3780 [delegate_ addProgressEventOnMainThread:event forTask:title];
3783 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3791 RestartSubstrate_ = true;
3794 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3795 if ([self popErrorWithTitle:title])
3798 if (result == pkgPackageManager::Failed) {
3803 if (result != pkgPackageManager::Completed) {
3808 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3810 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3812 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3813 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3816 if (![before isEqualToArray:after])
3821 NSString *title(UCLocalize("UPGRADE"));
3822 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3828 [self updateWithStatus:status_];
3831 - (void) updateWithStatus:(Status &)status {
3832 NSString *title(UCLocalize("REFRESHING_DATA"));
3835 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3839 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3840 if ([self popErrorWithTitle:title])
3843 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3845 bool success(ListUpdate(status, list, PulseInterval_));
3846 if (status.WasCancelled())
3849 [self popErrorWithTitle:title forOperation:success];
3850 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3854 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3857 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3858 delegate_ = delegate;
3861 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3862 progress_ = delegate;
3863 status_.setDelegate(delegate);
3866 - (NSObject<ProgressDelegate> *) progressDelegate {
3870 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3871 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3872 return i == sourceMap_.end() ? nil : i->second;
3875 - (NSString *) mappedSectionForPointer:(const char *)section {
3876 _H<NSString> *mapped;
3878 _profile(Database$mappedSectionForPointer$Cache)
3879 mapped = §ions_[section];
3882 if (*mapped == NULL) {
3883 size_t length(strlen(section));
3884 char spaced[length + 1];
3886 _profile(Database$mappedSectionForPointer$Replace)
3887 for (size_t index(0); index != length; ++index)
3888 spaced[index] = section[index] == '_' ? ' ' : section[index];
3889 spaced[length] = '\0';
3894 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3895 string = [NSString stringWithUTF8String:spaced];
3898 _profile(Database$mappedSectionForPointer$Map)
3899 string = [SectionMap_ objectForKey:string] ?: string;
3909 static _H<NSMutableSet> Diversions_;
3911 @interface Diversion : NSObject {
3914 _H<NSString> format_;
3919 @implementation Diversion
3921 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3922 if ((self = [super init]) != nil) {
3923 pattern_ = [from UTF8String];
3929 - (NSString *) divert:(NSString *)url {
3930 return !pattern_(url) ? nil : pattern_->*format_;
3933 + (NSURL *) divertURL:(NSURL *)url {
3935 NSString *href([url absoluteString]);
3937 for (Diversion *diversion in (id) Diversions_)
3938 if (NSString *diverted = [diversion divert:href]) {
3940 NSLog(@"div: %@", diverted);
3942 url = [NSURL URLWithString:diverted];
3949 - (NSString *) key {
3953 - (NSUInteger) hash {
3957 - (BOOL) isEqual:(Diversion *)object {
3958 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3963 @interface CydiaObject : NSObject {
3964 _H<IndirectDelegate> indirect_;
3965 _transient id delegate_;
3968 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3974 @interface CydiaWebViewController : CyteWebViewController {
3975 _H<CydiaObject> cydia_;
3978 + (void) addDiversion:(Diversion *)diversion;
3979 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
3980 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
3981 - (void) setDelegate:(id)delegate;
3985 /* Web Scripting {{{ */
3986 @implementation CydiaObject
3988 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3989 if ((self = [super init]) != nil) {
3990 indirect_ = indirect;
3994 - (void) setDelegate:(id)delegate {
3995 delegate_ = delegate;
3998 + (NSArray *) _attributeKeys {
3999 return [NSArray arrayWithObjects:
4002 @"coreFoundationVersionNumber",
4019 - (NSArray *) attributeKeys {
4020 return [[self class] _attributeKeys];
4023 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4024 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4027 - (NSString *) version {
4031 - (NSString *) build {
4035 - (NSString *) coreFoundationVersionNumber {
4036 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4039 - (NSString *) device {
4040 return [[UIDevice currentDevice] uniqueIdentifier];
4043 - (NSString *) firmware {
4044 return [[UIDevice currentDevice] systemVersion];
4047 - (NSString *) hostname {
4048 return [[UIDevice currentDevice] name];
4051 - (NSString *) idiom {
4052 return (id) Idiom_ ?: [NSNull null];
4055 - (NSString *) mcc {
4056 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4057 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4061 - (NSString *) mnc {
4062 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4063 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4067 - (NSString *) operator {
4068 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4069 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4073 - (NSString *) bbsnum {
4074 return (id) BBSNum_ ?: [NSNull null];
4077 - (NSString *) ecid {
4078 return (id) ChipID_ ?: [NSNull null];
4081 - (NSString *) serial {
4082 return SerialNumber_;
4085 - (NSString *) role {
4086 return (id) Role_ ?: [NSNull null];
4089 - (NSString *) model {
4090 return [NSString stringWithUTF8String:Machine_];
4093 - (NSString *) token {
4094 return (id) Token_ ?: [NSNull null];
4097 + (NSString *) webScriptNameForSelector:(SEL)selector {
4099 else if (selector == @selector(addBridgedHost:))
4100 return @"addBridgedHost";
4101 else if (selector == @selector(addInsecureHost:))
4102 return @"addInsecureHost";
4103 else if (selector == @selector(addInternalRedirect::))
4104 return @"addInternalRedirect";
4105 else if (selector == @selector(addPipelinedHost:scheme:))
4106 return @"addPipelinedHost";
4107 else if (selector == @selector(addSource:::))
4108 return @"addSource";
4109 else if (selector == @selector(addTokenHost:))
4110 return @"addTokenHost";
4111 else if (selector == @selector(addTrivialSource:))
4112 return @"addTrivialSource";
4113 else if (selector == @selector(close))
4115 else if (selector == @selector(du:))
4117 else if (selector == @selector(stringWithFormat:arguments:))
4119 else if (selector == @selector(getAllSources))
4120 return @"getAllSourcs";
4121 else if (selector == @selector(getKernelNumber:))
4122 return @"getKernelNumber";
4123 else if (selector == @selector(getKernelString:))
4124 return @"getKernelString";
4125 else if (selector == @selector(getInstalledPackages))
4126 return @"getInstalledPackages";
4127 else if (selector == @selector(getIORegistryEntry::))
4128 return @"getIORegistryEntry";
4129 else if (selector == @selector(getLocaleIdentifier))
4130 return @"getLocaleIdentifier";
4131 else if (selector == @selector(getPreferredLanguages))
4132 return @"getPreferredLanguages";
4133 else if (selector == @selector(getPackageById:))
4134 return @"getPackageById";
4135 else if (selector == @selector(getMetadataKeys))
4136 return @"getMetadataKeys";
4137 else if (selector == @selector(getMetadataValue:))
4138 return @"getMetadataValue";
4139 else if (selector == @selector(getSessionValue:))
4140 return @"getSessionValue";
4141 else if (selector == @selector(installPackages:))
4142 return @"installPackages";
4143 else if (selector == @selector(isReachable:))
4144 return @"isReachable";
4145 else if (selector == @selector(localizedStringForKey:value:table:))
4147 else if (selector == @selector(popViewController:))
4148 return @"popViewController";
4149 else if (selector == @selector(refreshSources))
4150 return @"refreshSources";
4151 else if (selector == @selector(removeButton))
4152 return @"removeButton";
4153 else if (selector == @selector(saveConfig))
4154 return @"saveConfig";
4155 else if (selector == @selector(setMetadataValue::))
4156 return @"setMetadataValue";
4157 else if (selector == @selector(setSessionValue::))
4158 return @"setSessionValue";
4159 else if (selector == @selector(setShowPromoted:))
4160 return @"setShowPromoted";
4161 else if (selector == @selector(substitutePackageNames:))
4162 return @"substitutePackageNames";
4163 else if (selector == @selector(scrollToBottom:))
4164 return @"scrollToBottom";
4165 else if (selector == @selector(setAllowsNavigationAction:))
4166 return @"setAllowsNavigationAction";
4167 else if (selector == @selector(setBadgeValue:))
4168 return @"setBadgeValue";
4169 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4170 return @"setButtonImage";
4171 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4172 return @"setButtonTitle";
4173 else if (selector == @selector(setHidesBackButton:))
4174 return @"setHidesBackButton";
4175 else if (selector == @selector(setHidesNavigationBar:))
4176 return @"setHidesNavigationBar";
4177 else if (selector == @selector(setNavigationBarStyle:))
4178 return @"setNavigationBarStyle";
4179 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4180 return @"setNavigationBarTintColor";
4181 else if (selector == @selector(setPasteboardString:))
4182 return @"setPasteboardString";
4183 else if (selector == @selector(setPasteboardURL:))
4184 return @"setPasteboardURL";
4185 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4186 return @"setScrollAlwaysBounceVertical";
4187 else if (selector == @selector(setScrollIndicatorStyle:))
4188 return @"setScrollIndicatorStyle";
4189 else if (selector == @selector(setToken:))
4191 else if (selector == @selector(setViewportWidth:))
4192 return @"setViewportWidth";
4193 else if (selector == @selector(statfs:))
4195 else if (selector == @selector(supports:))
4197 else if (selector == @selector(unload))
4203 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4204 return [self webScriptNameForSelector:selector] == nil;
4207 - (BOOL) supports:(NSString *)feature {
4208 return [feature isEqualToString:@"window.open"];
4212 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4215 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4216 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4219 - (void) setScrollIndicatorStyle:(NSString *)style {
4220 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4223 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4224 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4227 - (NSNumber *) getKernelNumber:(NSString *)name {
4228 const char *string([name UTF8String]);
4231 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4232 return (id) [NSNull null];
4234 if (size != sizeof(int))
4235 return (id) [NSNull null];
4238 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4239 return (id) [NSNull null];
4241 return [NSNumber numberWithInt:value];
4244 - (NSString *) getKernelString:(NSString *)name {
4245 const char *string([name UTF8String]);
4248 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4249 return (id) [NSNull null];
4251 char value[size + 1];
4252 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4253 return (id) [NSNull null];
4255 // XXX: just in case you request something ludicrous
4258 return [NSString stringWithCString:value];
4261 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4262 NSObject *value(CYIOGetValue([path UTF8String], entry));
4265 if ([value isKindOfClass:[NSData class]])
4266 value = CYHex((NSData *) value);
4271 - (NSArray *) getMetadataKeys {
4272 @synchronized (Values_) {
4273 return [Values_ allKeys];
4276 - (void) _setShowPromoted:(NSNumber *)value {
4277 [Metadata_ setObject:value forKey:@"ShowPromoted"];
4281 - (void) setShowPromoted:(NSNumber *)value {
4282 [self performSelectorOnMainThread:@selector(_setShowPromoted:) withObject:value waitUntilDone:NO];
4285 - (id) getMetadataValue:(NSString *)key {
4286 @synchronized (Values_) {
4287 return [Values_ objectForKey:key];
4290 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4291 @synchronized (Values_) {
4292 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4293 [Values_ removeObjectForKey:key];
4295 [Values_ setObject:value forKey:key];
4297 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4300 - (id) getSessionValue:(NSString *)key {
4301 @synchronized (SessionData_) {
4302 return [SessionData_ objectForKey:key];
4305 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4306 @synchronized (SessionData_) {
4307 if (value == (id) [WebUndefined undefined])
4308 [SessionData_ removeObjectForKey:key];
4310 [SessionData_ setObject:value forKey:key];
4313 - (void) addBridgedHost:(NSString *)host {
4314 @synchronized (HostConfig_) {
4315 [BridgedHosts_ addObject:host];
4318 - (void) addInsecureHost:(NSString *)host {
4319 @synchronized (HostConfig_) {
4320 [InsecureHosts_ addObject:host];
4323 - (void) addTokenHost:(NSString *)host {
4324 @synchronized (HostConfig_) {
4325 [TokenHosts_ addObject:host];
4328 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4329 @synchronized (HostConfig_) {
4330 if (scheme != (id) [WebUndefined undefined])
4331 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4333 [PipelinedHosts_ addObject:host];
4336 - (void) popViewController:(NSNumber *)value {
4337 if (value == (id) [WebUndefined undefined])
4338 value = [NSNumber numberWithBool:YES];
4339 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4342 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4343 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4345 for (NSString *section in sections)
4346 [array addObject:section];
4348 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4351 distribution, @"Distribution",
4353 nil] waitUntilDone:NO];
4356 - (void) addTrivialSource:(NSString *)href {
4357 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4360 - (void) refreshSources {
4361 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4364 - (void) saveConfig {
4365 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4368 - (NSArray *) getAllSources {
4369 return [[Database sharedInstance] sources];
4372 - (NSArray *) getInstalledPackages {
4373 Database *database([Database sharedInstance]);
4374 @synchronized (database) {
4375 NSArray *packages([database packages]);
4376 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4377 for (Package *package in packages)
4378 if (![package uninstalled])
4379 [installed addObject:package];
4383 - (Package *) getPackageById:(NSString *)id {
4384 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4388 return (Package *) [NSNull null];
4391 - (NSString *) getLocaleIdentifier {
4392 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4395 - (NSArray *) getPreferredLanguages {
4399 - (NSArray *) statfs:(NSString *)path {
4402 if (path == nil || statfs([path UTF8String], &stat) == -1)
4405 return [NSArray arrayWithObjects:
4406 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4407 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4408 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4412 - (NSNumber *) du:(NSString *)path {
4413 NSNumber *value(nil);
4416 _assert(pipe(fds) != -1);
4418 pid_t pid(ExecFork());
4420 _assert(dup2(fds[1], 1) != -1);
4421 _assert(close(fds[0]) != -1);
4422 _assert(close(fds[1]) != -1);
4423 /* XXX: this should probably not use du */
4424 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4429 _assert(close(fds[1]) != -1);
4431 if (FILE *du = fdopen(fds[0], "r")) {
4433 while (fgets(line, sizeof(line), du) != NULL) {
4434 size_t length(strlen(line));
4435 while (length != 0 && line[length - 1] == '\n')
4436 line[--length] = '\0';
4437 if (char *tab = strchr(line, '\t')) {
4439 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4444 } else _assert(close(fds[0]));
4452 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4455 - (NSNumber *) isReachable:(NSString *)name {
4456 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4459 - (void) installPackages:(NSArray *)packages {
4460 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4463 - (NSString *) substitutePackageNames:(NSString *)message {
4464 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4465 for (size_t i(0), e([words count]); i != e; ++i) {
4466 NSString *word([words objectAtIndex:i]);
4467 if (Package *package = [[Database sharedInstance] packageWithName:word])
4468 [words replaceObjectAtIndex:i withObject:[package name]];
4471 return [words componentsJoinedByString:@" "];
4474 - (void) removeButton {
4475 [indirect_ removeButton];
4478 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4479 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4482 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4483 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4486 - (void) setBadgeValue:(id)value {
4487 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4490 - (void) setAllowsNavigationAction:(NSString *)value {
4491 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4494 - (void) setHidesBackButton:(NSString *)value {
4495 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4498 - (void) setHidesNavigationBar:(NSString *)value {
4499 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4502 - (void) setNavigationBarStyle:(NSString *)value {
4503 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4506 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4507 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4508 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4509 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4512 - (void) setPasteboardString:(NSString *)value {
4513 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4516 - (void) setPasteboardURL:(NSString *)value {
4517 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4520 - (void) _setToken:(NSString *)token {
4524 [Metadata_ removeObjectForKey:@"Token"];
4526 [Metadata_ setObject:Token_ forKey:@"Token"];
4531 - (void) setToken:(NSString *)token {
4532 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4535 - (void) scrollToBottom:(NSNumber *)animated {
4536 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4539 - (void) setViewportWidth:(float)width {
4540 [indirect_ setViewportWidthOnMainThread:width];
4543 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4544 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4545 unsigned count([arguments count]);
4547 for (unsigned i(0); i != count; ++i)
4548 values[i] = [arguments objectAtIndex:i];
4549 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4552 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4553 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4555 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4557 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4563 @interface NSURL (CydiaSecure)
4566 @implementation NSURL (CydiaSecure)
4568 - (bool) isCydiaSecure {
4569 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4572 @synchronized (HostConfig_) {
4573 if ([InsecureHosts_ containsObject:[self host]])
4582 /* Cydia Browser Controller {{{ */
4583 @implementation CydiaWebViewController
4585 - (NSURL *) navigationURL {
4586 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4589 + (void) _initialize {
4590 [super _initialize];
4592 Diversions_ = [NSMutableSet setWithCapacity:0];
4595 + (void) addDiversion:(Diversion *)diversion {
4596 [Diversions_ addObject:diversion];
4599 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4600 [super webView:view didClearWindowObject:window forFrame:frame];
4601 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4604 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4605 WebDataSource *source([frame dataSource]);
4606 NSURLResponse *response([source response]);
4607 NSURL *url([response URL]);
4608 NSString *scheme([[url scheme] lowercaseString]);
4610 bool bridged(false);
4612 @synchronized (HostConfig_) {
4613 if ([scheme isEqualToString:@"file"])
4615 else if ([scheme isEqualToString:@"https"])
4616 if ([BridgedHosts_ containsObject:[url host]])
4621 [window setValue:cydia forKey:@"cydia"];
4624 - (void) _setupMail:(MFMailComposeViewController *)controller {
4625 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4627 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4628 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4631 - (NSURL *) URLWithURL:(NSURL *)url {
4632 return [Diversion divertURL:url];
4635 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4636 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4639 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4640 NSMutableURLRequest *copy([request mutableCopy]);
4642 NSURL *url([copy URL]);
4643 NSString *href([url absoluteString]);
4644 NSString *host([url host]);
4646 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4647 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4648 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4649 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4652 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4653 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4655 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4659 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4660 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4661 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4662 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4667 @synchronized (HostConfig_) {
4668 bridged = [BridgedHosts_ containsObject:host];
4669 token = [TokenHosts_ containsObject:host];
4672 if ([url isCydiaSecure]) {
4674 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4675 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4677 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4678 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4685 - (void) setDelegate:(id)delegate {
4686 [super setDelegate:delegate];
4687 [cydia_ setDelegate:delegate];
4690 - (NSString *) applicationNameForUserAgent {
4695 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4696 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4702 @interface AppCacheController : CydiaWebViewController {
4707 @implementation AppCacheController
4709 - (void) didReceiveMemoryWarning {
4710 // XXX: this doesn't work
4713 - (bool) retainsNetworkActivityIndicator {
4721 @interface NSObject (CydiaScript)
4722 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4725 @implementation NSObject (CydiaScript)
4727 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4733 @implementation NSArray (CydiaScript)
4735 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4736 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4737 for (size_t i(0), e([self count]); i != e; ++i)
4738 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4744 @implementation NSDictionary (CydiaScript)
4746 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4747 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4749 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4756 /* Confirmation Controller {{{ */
4757 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4758 if (!iterator.end())
4759 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4760 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4762 pkgCache::PkgIterator package(dep.TargetPkg());
4765 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4772 @protocol ConfirmationControllerDelegate
4773 - (void) cancelAndClear:(bool)clear;
4774 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4778 @interface ConfirmationController : CydiaWebViewController {
4779 _transient Database *database_;
4781 _H<UIAlertView> essential_;
4783 _H<NSDictionary> changes_;
4784 _H<NSMutableArray> issues_;
4785 _H<NSDictionary> sizes_;
4790 - (id) initWithDatabase:(Database *)database;
4794 @implementation ConfirmationController
4798 RestartSubstrate_ = true;
4799 [delegate_ confirmWithNavigationController:[self navigationController]];
4802 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4803 NSString *context([alert context]);
4805 if ([context isEqualToString:@"remove"]) {
4806 if (button == [alert cancelButtonIndex])
4807 [self dismissModalViewControllerAnimated:YES];
4808 else if (button == [alert firstOtherButtonIndex]) {
4809 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
4812 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4813 } else if ([context isEqualToString:@"unable"]) {
4814 [self dismissModalViewControllerAnimated:YES];
4815 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4817 [super alertView:alert clickedButtonAtIndex:button];
4821 - (void) _doContinue {
4822 [delegate_ cancelAndClear:NO];
4823 [self dismissModalViewControllerAnimated:YES];
4826 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4827 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4831 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4832 [super webView:view didClearWindowObject:window forFrame:frame];
4834 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4835 (id) changes_, @"changes",
4836 (id) issues_, @"issues",
4837 (id) sizes_, @"sizes",
4839 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4842 - (id) initWithDatabase:(Database *)database {
4843 if ((self = [super init]) != nil) {
4844 database_ = database;
4846 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4847 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4848 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4849 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4850 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4854 pkgCacheFile &cache([database_ cache]);
4855 NSArray *packages([database_ packages]);
4856 pkgDepCache::Policy *policy([database_ policy]);
4858 issues_ = [NSMutableArray arrayWithCapacity:4];
4860 for (Package *package in packages) {
4861 pkgCache::PkgIterator iterator([package iterator]);
4862 NSString *name([package id]);
4864 if ([package broken]) {
4865 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4867 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4869 reasons, @"reasons",
4872 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4876 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4877 pkgCache::DepIterator start;
4878 pkgCache::DepIterator end;
4879 dep.GlobOr(start, end); // ++dep
4881 if (!cache->IsImportantDep(end))
4883 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4886 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4888 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4889 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4890 clauses, @"clauses",
4894 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4896 pkgCache::PkgIterator target(start.TargetPkg());
4897 if (target->ProvidesList != 0)
4898 reason = @"missing";
4900 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4902 reason = @"installed";
4903 installed = [NSString stringWithUTF8String:ver.VerStr()];
4904 } else if (!cache[target].CandidateVerIter(cache).end())
4905 reason = @"uninstalled";
4906 else if (target->ProvidesList == 0)
4907 reason = @"uninstallable";
4909 reason = @"virtual";
4912 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4913 [NSString stringWithUTF8String:start.CompType()], @"operator",
4914 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4917 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4918 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4919 version, @"version",
4921 installed, @"installed",
4924 // yes, seriously. (wtf?)
4932 pkgDepCache::StateCache &state(cache[iterator]);
4934 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4936 if (state.NewInstall())
4937 [installs addObject:name];
4938 // XXX: else if (state.Install())
4939 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4940 [reinstalls addObject:name];
4941 // XXX: move before previous if
4942 else if (state.Upgrade())
4943 [upgrades addObject:name];
4944 else if (state.Downgrade())
4945 [downgrades addObject:name];
4946 else if (!state.Delete())
4947 // XXX: _assert(state.Keep());
4949 else if (special_r(name))
4950 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4951 [NSNull null], @"package",
4952 [NSArray arrayWithObjects:
4953 [NSDictionary dictionaryWithObjectsAndKeys:
4954 @"Conflicts", @"relationship",
4955 [NSArray arrayWithObjects:
4956 [NSDictionary dictionaryWithObjectsAndKeys:
4958 [NSNull null], @"version",
4959 @"installed", @"reason",
4966 if ([package essential])
4968 [removes addObject:name];
4971 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4972 substrate_ |= DepSubstrate(iterator.CurrentVer());
4977 else if (Advanced_) {
4978 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4980 essential_ = [[[UIAlertView alloc]
4981 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4982 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4984 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4986 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4990 [essential_ setContext:@"remove"];
4991 [essential_ setNumberOfRows:2];
4993 essential_ = [[[UIAlertView alloc]
4994 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4995 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4997 cancelButtonTitle:UCLocalize("OKAY")
4998 otherButtonTitles:nil
5001 [essential_ setContext:@"unable"];
5004 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5005 installs, @"installs",
5006 reinstalls, @"reinstalls",
5007 upgrades, @"upgrades",
5008 downgrades, @"downgrades",
5009 removes, @"removes",
5012 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5013 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5014 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5017 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5021 - (UIBarButtonItem *) leftButton {
5022 return [[[UIBarButtonItem alloc]
5023 initWithTitle:UCLocalize("CANCEL")
5024 style:UIBarButtonItemStylePlain
5026 action:@selector(cancelButtonClicked)
5031 - (void) applyRightButton {
5032 if ([issues_ count] == 0 && ![self isLoading])
5033 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5034 initWithTitle:UCLocalize("CONFIRM")
5035 style:UIBarButtonItemStyleDone
5037 action:@selector(confirmButtonClicked)
5040 [[self navigationItem] setRightBarButtonItem:nil];
5044 - (void) cancelButtonClicked {
5045 [delegate_ cancelAndClear:YES];
5046 [self dismissModalViewControllerAnimated:YES];
5050 - (void) confirmButtonClicked {
5051 if (essential_ != nil)
5061 /* Progress Data {{{ */
5062 @interface CydiaProgressData : NSObject {
5063 _transient id delegate_;
5072 _H<NSMutableArray> events_;
5073 _H<NSString> title_;
5075 _H<NSString> status_;
5076 _H<NSString> finish_;
5081 @implementation CydiaProgressData
5083 + (NSArray *) _attributeKeys {
5084 return [NSArray arrayWithObjects:
5096 - (NSArray *) attributeKeys {
5097 return [[self class] _attributeKeys];
5100 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5101 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5105 if ((self = [super init]) != nil) {
5106 events_ = [NSMutableArray arrayWithCapacity:32];
5110 - (void) setDelegate:(id)delegate {
5111 delegate_ = delegate;
5114 - (void) setPercent:(float)value {
5118 - (NSNumber *) percent {
5119 return [NSNumber numberWithFloat:percent_];
5122 - (void) setCurrent:(float)value {
5126 - (NSNumber *) current {
5127 return [NSNumber numberWithFloat:current_];
5130 - (void) setTotal:(float)value {
5134 - (NSNumber *) total {
5135 return [NSNumber numberWithFloat:total_];
5138 - (void) setSpeed:(float)value {
5142 - (NSNumber *) speed {
5143 return [NSNumber numberWithFloat:speed_];
5146 - (NSArray *) events {
5150 - (void) removeAllEvents {
5151 [events_ removeAllObjects];
5154 - (void) addEvent:(CydiaProgressEvent *)event {
5155 [events_ addObject:event];
5158 - (void) setTitle:(NSString *)text {
5162 - (NSString *) title {
5166 - (void) setFinish:(NSString *)text {
5170 - (NSString *) finish {
5171 return (id) finish_ ?: [NSNull null];
5174 - (void) setRunning:(bool)running {
5178 - (NSNumber *) running {
5179 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5184 /* Progress Controller {{{ */
5185 @interface ProgressController : CydiaWebViewController <
5188 _transient Database *database_;
5189 _H<CydiaProgressData, 1> progress_;
5193 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5195 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5197 - (void) setTitle:(NSString *)title;
5198 - (void) setCancellable:(bool)cancellable;
5202 @implementation ProgressController
5205 [database_ setProgressDelegate:nil];
5209 - (UIBarButtonItem *) leftButton {
5210 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5211 initWithTitle:UCLocalize("CANCEL")
5212 style:UIBarButtonItemStylePlain
5214 action:@selector(cancel)
5215 ] autorelease] : nil;
5218 - (void) updateCancel {
5219 [super applyLeftButton];
5222 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5223 if ((self = [super init]) != nil) {
5224 database_ = database;
5225 delegate_ = delegate;
5227 [database_ setProgressDelegate:self];
5229 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5230 [progress_ setDelegate:self];
5232 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5234 [scroller_ setBackgroundColor:[UIColor blackColor]];
5236 [[self navigationItem] setHidesBackButton:YES];
5238 [self updateCancel];
5242 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5243 [super webView:view didClearWindowObject:window forFrame:frame];
5244 [window setValue:progress_ forKey:@"cydiaProgress"];
5247 - (void) updateProgress {
5248 [self dispatchEvent:@"CydiaProgressUpdate"];
5251 - (void) viewWillAppear:(BOOL)animated {
5252 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5253 [super viewWillAppear:animated];
5256 - (void) reloadSpringBoard {
5257 pid_t pid(ExecFork());
5259 pid_t pid(ExecFork());
5261 execl("/usr/bin/sbreload", "sbreload", NULL);
5272 system("/usr/bin/killall SpringBoard");
5276 UpdateExternalStatus(0);
5279 [delegate_ saveState];
5283 [delegate_ returnToCydia];
5287 [delegate_ terminateWithSuccess];
5288 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5289 [delegate_ suspendWithAnimation:YES];
5291 [delegate_ suspend];*/
5303 UIProgressHUD *hud([delegate_ addProgressHUD]);
5304 [hud setText:UCLocalize("LOADING")];
5305 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5311 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5312 SBReboot(SBSSpringBoardServerPort());
5314 reboot2(RB_AUTOBOOT);
5321 - (void) setTitle:(NSString *)title {
5322 [progress_ setTitle:title];
5323 [self updateProgress];
5326 - (UIBarButtonItem *) rightButton {
5327 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5328 initWithTitle:UCLocalize("CLOSE")
5329 style:UIBarButtonItemStylePlain
5331 action:@selector(close)
5335 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5336 UpdateExternalStatus(1);
5338 [progress_ setRunning:true];
5339 [self setTitle:title];
5340 // implicit updateProgress
5342 SHA1SumValue notifyconf; {
5344 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5347 MMap mmap(file, MMap::ReadOnly);
5349 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5350 notifyconf = sha1.Result();
5354 SHA1SumValue springlist; {
5356 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5359 MMap mmap(file, MMap::ReadOnly);
5361 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5362 springlist = sha1.Result();
5366 if (invocation != nil) {
5367 [invocation yieldToSelector:@selector(invoke)];
5368 [self setTitle:@"COMPLETE"];
5373 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5376 MMap mmap(file, MMap::ReadOnly);
5378 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5379 if (!(notifyconf == sha1.Result()))
5386 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5389 MMap mmap(file, MMap::ReadOnly);
5391 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5392 if (!(springlist == sha1.Result()))
5398 if (RestartSubstrate_)
5402 RestartSubstrate_ = false;
5405 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5406 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5407 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5408 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5409 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5412 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5414 [progress_ setRunning:false];
5415 [self updateProgress];
5417 [self applyRightButton];
5420 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5421 [progress_ addEvent:event];
5422 [self updateProgress];
5425 - (bool) isProgressCancelled {
5426 return cancel_ == 2;
5431 [self updateCancel];
5434 - (void) setCancellable:(bool)cancellable {
5435 unsigned cancel(cancel_);
5439 else if (cancel_ == 0)
5442 if (cancel != cancel_)
5443 [self updateCancel];
5446 - (void) setProgressCancellable:(NSNumber *)cancellable {
5447 [self setCancellable:[cancellable boolValue]];
5450 - (void) setProgressPercent:(NSNumber *)percent {
5451 [progress_ setPercent:[percent floatValue]];
5452 [self updateProgress];
5455 - (void) setProgressStatus:(NSDictionary *)status {
5456 if (status == nil) {
5457 [progress_ setCurrent:0];
5458 [progress_ setTotal:0];
5459 [progress_ setSpeed:0];
5461 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5463 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5464 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5465 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5468 [self updateProgress];
5474 /* Package Cell {{{ */
5475 @interface PackageCell : CyteTableViewCell <
5476 CyteTableViewCellDelegate
5480 _H<NSString> description_;
5482 _H<NSString> source_;
5484 _H<UIImage> placard_;
5488 - (PackageCell *) init;
5489 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5491 - (void) drawContentRect:(CGRect)rect;
5495 @implementation PackageCell
5497 - (PackageCell *) init {
5498 CGRect frame(CGRectMake(0, 0, 320, 74));
5499 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5500 UIView *content([self contentView]);
5501 CGRect bounds([content bounds]);
5503 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5504 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5505 [content addSubview:content_];
5507 [content_ setDelegate:self];
5508 [content_ setOpaque:YES];
5512 - (NSString *) accessibilityLabel {
5513 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5516 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5517 summarized_ = summary;
5527 [content_ setBackgroundColor:[UIColor whiteColor]];
5531 Source *source = [package source];
5533 icon_ = [package icon];
5535 if (NSString *name = [package name])
5536 name_ = [NSString stringWithString:name];
5538 NSString *description(nil);
5540 if (description == nil && IsWildcat_)
5541 description = [package longDescription];
5542 if (description == nil)
5543 description = [package shortDescription];
5545 if (description != nil)
5546 description_ = [NSString stringWithString:description];
5548 commercial_ = [package isCommercial];
5550 NSString *label = nil;
5551 bool trusted = false;
5553 if (source != nil) {
5554 label = [source label];
5555 trusted = [source trusted];
5556 } else if ([[package id] isEqualToString:@"firmware"])
5557 label = UCLocalize("APPLE");
5559 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5561 NSString *from(label);
5563 NSString *section = [package simpleSection];
5564 if (section != nil && ![section isEqualToString:label]) {
5565 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5566 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5569 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5571 if (NSString *purpose = [package primaryPurpose])
5572 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5577 if (NSString *mode = [package mode]) {
5578 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5579 color = RemovingColor_;
5580 //placard = @"removing";
5582 color = InstallingColor_;
5583 //placard = @"installing";
5586 // XXX: the removing/installing placards are not @2x
5589 color = [UIColor whiteColor];
5591 if ([package installed] != nil)
5592 placard = @"installed";
5597 [content_ setBackgroundColor:color];
5600 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5603 [self setNeedsDisplay];
5604 [content_ setNeedsDisplay];
5607 - (void) drawSummaryContentRect:(CGRect)rect {
5608 bool highlighted(highlighted_);
5609 float width([self bounds].size.width);
5613 rect.size = [(UIImage *) icon_ size];
5615 while (rect.size.width > 16 || rect.size.height > 16) {
5616 rect.size.width /= 2;
5617 rect.size.height /= 2;
5620 rect.origin.x = 18 - rect.size.width / 2;
5621 rect.origin.y = 18 - rect.size.height / 2;
5623 [icon_ drawInRect:rect];
5626 if (badge_ != nil) {
5628 rect.size = [(UIImage *) badge_ size];
5630 rect.size.width /= 4;
5631 rect.size.height /= 4;
5633 rect.origin.x = 23 - rect.size.width / 2;
5634 rect.origin.y = 23 - rect.size.height / 2;
5636 [badge_ drawInRect:rect];
5643 UISetColor(commercial_ ? Purple_ : Black_);
5644 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5646 if (placard_ != nil)
5647 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5650 - (void) drawNormalContentRect:(CGRect)rect {
5651 bool highlighted(highlighted_);
5652 float width([self bounds].size.width);
5656 rect.size = [(UIImage *) icon_ size];
5658 while (rect.size.width > 32 || rect.size.height > 32) {
5659 rect.size.width /= 2;
5660 rect.size.height /= 2;
5663 rect.origin.x = 25 - rect.size.width / 2;
5664 rect.origin.y = 25 - rect.size.height / 2;
5666 [icon_ drawInRect:rect];
5669 if (badge_ != nil) {
5671 rect.size = [(UIImage *) badge_ size];
5673 rect.size.width /= 2;
5674 rect.size.height /= 2;
5676 rect.origin.x = 36 - rect.size.width / 2;
5677 rect.origin.y = 36 - rect.size.height / 2;
5679 [badge_ drawInRect:rect];
5686 UISetColor(commercial_ ? Purple_ : Black_);
5687 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5688 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5691 UISetColor(commercial_ ? Purplish_ : Gray_);
5692 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5694 if (placard_ != nil)
5695 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5698 - (void) drawContentRect:(CGRect)rect {
5700 [self drawSummaryContentRect:rect];
5702 [self drawNormalContentRect:rect];
5707 /* Section Cell {{{ */
5708 @interface SectionCell : CyteTableViewCell <
5709 CyteTableViewCellDelegate
5711 _H<NSString> basic_;
5712 _H<NSString> section_;
5714 _H<NSString> count_;
5716 _H<UISwitch> switch_;
5720 - (void) setSection:(Section *)section editing:(BOOL)editing;
5724 @implementation SectionCell
5726 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5727 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5728 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5729 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5730 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5732 UIView *content([self contentView]);
5733 CGRect bounds([content bounds]);
5735 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5736 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5737 [content addSubview:content_];
5738 [content_ setBackgroundColor:[UIColor whiteColor]];
5740 [content_ setDelegate:self];
5744 - (void) onSwitch:(id)sender {
5745 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5746 if (metadata == nil) {
5747 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5748 [Sections_ setObject:metadata forKey:basic_];
5751 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5755 - (void) setSection:(Section *)section editing:(BOOL)editing {
5756 if (editing != editing_) {
5758 [switch_ removeFromSuperview];
5760 [self addSubview:switch_];
5769 if (section == nil) {
5770 name_ = UCLocalize("ALL_PACKAGES");
5773 basic_ = [section name];
5774 section_ = [section localized];
5776 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5777 count_ = [NSString stringWithFormat:@"%d", [section count]];
5780 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5783 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5784 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5786 [content_ setNeedsDisplay];
5789 - (void) setFrame:(CGRect)frame {
5790 [super setFrame:frame];
5792 CGRect rect([switch_ frame]);
5793 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5796 - (NSString *) accessibilityLabel {
5800 - (void) drawContentRect:(CGRect)rect {
5801 bool highlighted(highlighted_ && !editing_);
5803 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5808 float width(rect.size.width);
5814 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5816 CGSize size = [count_ sizeWithFont:Font14_];
5820 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5826 /* File Table {{{ */
5827 @interface FileTable : CyteViewController <
5828 UITableViewDataSource,
5831 _transient Database *database_;
5832 _H<Package> package_;
5834 _H<NSMutableArray> files_;
5835 _H<UITableView, 2> list_;
5838 - (id) initWithDatabase:(Database *)database;
5839 - (void) setPackage:(Package *)package;
5843 @implementation FileTable
5845 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5846 return files_ == nil ? 0 : [files_ count];
5849 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5853 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5854 static NSString *reuseIdentifier = @"Cell";
5856 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5858 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5859 [cell setFont:[UIFont systemFontOfSize:16]];
5861 [cell setText:[files_ objectAtIndex:indexPath.row]];
5862 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5867 - (NSURL *) navigationURL {
5868 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5872 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5873 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5874 [list_ setRowHeight:24.0f];
5875 [(UITableView *) list_ setDataSource:self];
5876 [list_ setDelegate:self];
5877 [self setView:list_];
5880 - (void) viewDidLoad {
5881 [super viewDidLoad];
5883 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5886 - (void) releaseSubviews {
5892 [super releaseSubviews];
5895 - (id) initWithDatabase:(Database *)database {
5896 if ((self = [super init]) != nil) {
5897 database_ = database;
5901 - (void) setPackage:(Package *)package {
5905 files_ = [NSMutableArray arrayWithCapacity:32];
5907 if (package != nil) {
5909 name_ = [package id];
5911 if (NSArray *files = [package files])
5912 [files_ addObjectsFromArray:files];
5914 if ([files_ count] != 0) {
5915 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5916 [files_ removeObjectAtIndex:0];
5917 [files_ sortUsingSelector:@selector(compareByPath:)];
5919 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5920 [stack addObject:@"/"];
5922 for (int i(0), e([files_ count]); i != e; ++i) {
5923 NSString *file = [files_ objectAtIndex:i];
5924 while (![file hasPrefix:[stack lastObject]])
5925 [stack removeLastObject];
5926 NSString *directory = [stack lastObject];
5927 [stack addObject:[file stringByAppendingString:@"/"]];
5928 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5929 ([stack count] - 2) * 3, "",
5930 [file substringFromIndex:[directory length]]
5939 - (void) reloadData {
5942 [self setPackage:[database_ packageWithName:name_]];
5947 /* Package Controller {{{ */
5948 @interface CYPackageController : CydiaWebViewController <
5949 UIActionSheetDelegate
5951 _transient Database *database_;
5952 _H<Package> package_;
5955 _H<NSMutableArray> buttons_;
5956 _H<UIBarButtonItem> button_;
5959 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
5963 @implementation CYPackageController
5965 - (NSURL *) navigationURL {
5966 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5969 /* XXX: this is not safe at all... localization of /fail/ */
5970 - (void) _clickButtonWithName:(NSString *)name {
5971 if ([name isEqualToString:UCLocalize("CLEAR")])
5972 [delegate_ clearPackage:package_];
5973 else if ([name isEqualToString:UCLocalize("INSTALL")])
5974 [delegate_ installPackage:package_];
5975 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5976 [delegate_ installPackage:package_];
5977 else if ([name isEqualToString:UCLocalize("REMOVE")])
5978 [delegate_ removePackage:package_];
5979 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5980 [delegate_ installPackage:package_];
5981 else _assert(false);
5984 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5985 NSString *context([sheet context]);
5987 if ([context isEqualToString:@"modify"]) {
5988 if (button != [sheet cancelButtonIndex]) {
5989 NSString *buttonName = [buttons_ objectAtIndex:button];
5990 [self _clickButtonWithName:buttonName];
5993 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5997 - (bool) _allowJavaScriptPanel {
6002 - (void) _customButtonClicked {
6003 int count([buttons_ count]);
6008 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6010 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6011 [buttons addObjectsFromArray:buttons_];
6013 UIActionSheet *sheet = [[[UIActionSheet alloc]
6016 cancelButtonTitle:nil
6017 destructiveButtonTitle:nil
6018 otherButtonTitles:nil
6021 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6023 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6024 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6026 [sheet setContext:@"modify"];
6028 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6032 // We don't want to allow non-commercial packages to do custom things to the install button,
6033 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6034 - (void) customButtonClicked {
6036 [super customButtonClicked];
6038 [self _customButtonClicked];
6041 - (void) reloadButtonClicked {
6042 // Don't reload a commerical package by tapping the loading button,
6043 // but if it's not an Install button, we should forward it on.
6044 if (![package_ uninstalled])
6045 [self _customButtonClicked];
6048 - (void) applyLoadingTitle {
6049 // Don't show "Loading" as the title. Ever.
6052 - (UIBarButtonItem *) rightButton {
6057 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6058 if ((self = [super init]) != nil) {
6059 database_ = database;
6060 buttons_ = [NSMutableArray arrayWithCapacity:4];
6061 name_ = name == nil ? @"" : [NSString stringWithString:name];
6062 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6066 - (void) reloadData {
6069 package_ = [database_ packageWithName:name_];
6071 [buttons_ removeAllObjects];
6073 if (package_ != nil) {
6074 [(Package *) package_ parse];
6076 commercial_ = [package_ isCommercial];
6078 if ([package_ mode] != nil)
6079 [buttons_ addObject:UCLocalize("CLEAR")];
6080 if ([package_ source] == nil);
6081 else if ([package_ upgradableAndEssential:NO])
6082 [buttons_ addObject:UCLocalize("UPGRADE")];
6083 else if ([package_ uninstalled])
6084 [buttons_ addObject:UCLocalize("INSTALL")];
6086 [buttons_ addObject:UCLocalize("REINSTALL")];
6087 if (![package_ uninstalled])
6088 [buttons_ addObject:UCLocalize("REMOVE")];
6092 switch ([buttons_ count]) {
6093 case 0: title = nil; break;
6094 case 1: title = [buttons_ objectAtIndex:0]; break;
6095 default: title = UCLocalize("MODIFY"); break;
6098 button_ = [[[UIBarButtonItem alloc]
6100 style:UIBarButtonItemStylePlain
6102 action:@selector(customButtonClicked)
6106 - (bool) isLoading {
6107 return commercial_ ? [super isLoading] : false;
6113 /* Package List Controller {{{ */
6114 @interface PackageListController : CyteViewController <
6115 UITableViewDataSource,
6118 _transient Database *database_;
6120 _H<NSArray> packages_;
6121 _H<NSMutableArray> sections_;
6122 _H<UITableView, 2> list_;
6123 _H<NSMutableArray> index_;
6124 _H<NSMutableDictionary> indices_;
6125 _H<NSString> title_;
6126 unsigned reloading_;
6129 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6130 - (void) setDelegate:(id)delegate;
6131 - (void) resetCursor;
6136 @implementation PackageListController
6138 - (NSURL *) referrerURL {
6139 return [self navigationURL];
6142 - (bool) isSummarized {
6146 - (bool) showsSections {
6150 - (void) deselectWithAnimation:(BOOL)animated {
6151 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6154 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6155 CGRect base = [[self view] bounds];
6156 base.size.height -= bounds.size.height;
6157 base.origin = [list_ frame].origin;
6159 [UIView beginAnimations:nil context:NULL];
6160 [UIView setAnimationBeginsFromCurrentState:YES];
6161 [UIView setAnimationCurve:curve];
6162 [UIView setAnimationDuration:duration];
6163 [list_ setFrame:base];
6164 [UIView commitAnimations];
6167 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6168 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6171 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6172 [self resizeForKeyboardBounds:bounds duration:0];
6175 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6176 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6177 *curve = UIViewAnimationCurveEaseInOut;
6179 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6181 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6184 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6187 - (void) keyboardWillShow:(NSNotification *)notification {
6190 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6191 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6193 NSTimeInterval duration;
6194 UIViewAnimationCurve curve;
6195 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6197 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);
6198 UIViewController *base = self;
6199 while ([base parentViewController] != nil)
6200 base = [base parentViewController];
6201 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6202 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6204 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6205 intersection.size.height += CYStatusBarHeight();
6207 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6210 - (void) keyboardWillHide:(NSNotification *)notification {
6211 NSTimeInterval duration;
6212 UIViewAnimationCurve curve;
6213 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6215 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6218 - (void) viewWillAppear:(BOOL)animated {
6219 [super viewWillAppear:animated];
6221 [self resizeForKeyboardBounds:CGRectZero];
6222 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6223 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6226 - (void) viewWillDisappear:(BOOL)animated {
6227 [super viewWillDisappear:animated];
6229 [self resizeForKeyboardBounds:CGRectZero];
6230 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6231 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6234 - (void) viewDidAppear:(BOOL)animated {
6235 [super viewDidAppear:animated];
6236 [self deselectWithAnimation:animated];
6239 - (void) didSelectPackage:(Package *)package {
6240 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6241 [view setDelegate:delegate_];
6242 [[self navigationController] pushViewController:view animated:YES];
6245 #if TryIndexedCollation
6246 + (BOOL) hasIndexedCollation {
6247 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6251 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6252 NSInteger count([sections_ count]);
6253 return count == 0 ? 1 : count;
6256 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6257 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6259 return [[sections_ objectAtIndex:section] name];
6262 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6263 if ([sections_ count] == 0)
6265 return [[sections_ objectAtIndex:section] count];
6268 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6269 @synchronized (database_) {
6270 if ([database_ era] != era_)
6273 Section *section([sections_ objectAtIndex:[path section]]);
6274 NSInteger row([path row]);
6275 Package *package([packages_ objectAtIndex:([section row] + row)]);
6276 return [[package retain] autorelease];
6279 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6280 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6282 cell = [[[PackageCell alloc] init] autorelease];
6284 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6285 [cell setPackage:package asSummary:[self isSummarized]];
6289 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6290 Package *package([self packageAtIndexPath:path]);
6291 package = [database_ packageWithName:[package id]];
6292 [self didSelectPackage:package];
6295 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6296 if (![self showsSections])
6302 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6303 #if TryIndexedCollation
6304 if ([[self class] hasIndexedCollation]) {
6305 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6312 - (void) updateHeight {
6313 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6316 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6317 if ((self = [super init]) != nil) {
6318 database_ = database;
6319 title_ = [title copy];
6320 [[self navigationItem] setTitle:title_];
6325 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6326 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6327 [self setView:view];
6329 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6330 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6331 [view addSubview:list_];
6333 // XXX: is 20 the most optimal number here?
6334 [list_ setSectionIndexMinimumDisplayRowCount:20];
6336 [(UITableView *) list_ setDataSource:self];
6337 [list_ setDelegate:self];
6339 [self updateHeight];
6342 - (void) releaseSubviews {
6350 [super releaseSubviews];
6353 - (void) setDelegate:(id)delegate {
6354 delegate_ = delegate;
6357 - (bool) shouldYield {
6361 - (bool) shouldBlock {
6365 - (NSMutableArray *) _reloadPackages {
6366 @synchronized (database_) {
6367 era_ = [database_ era];
6368 NSArray *packages([database_ packages]);
6370 return [NSMutableArray arrayWithArray:packages];
6373 - (void) _reloadData {
6374 if (reloading_ != 0) {
6382 if ([self shouldYield]) {
6386 if (![self shouldBlock])
6389 hud = [delegate_ addProgressHUD];
6390 [hud setText:UCLocalize("LOADING")];
6394 packages = [self yieldToSelector:@selector(_reloadPackages)];
6397 [delegate_ removeProgressHUD:hud];
6398 } while (reloading_ == 2);
6400 packages = [self _reloadPackages];
6403 @synchronized (database_) {
6404 if (era_ != [database_ era])
6408 packages_ = packages;
6410 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6411 sections_ = [NSMutableArray arrayWithCapacity:16];
6413 Section *section = nil;
6415 #if TryIndexedCollation
6416 if ([[self class] hasIndexedCollation]) {
6417 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6419 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6420 NSArray *titles = [collation sectionIndexTitles];
6423 _profile(PackageTable$reloadData$Section)
6424 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6428 _profile(PackageTable$reloadData$Section$Package)
6429 package = [packages_ objectAtIndex:offset];
6430 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6433 while (secidx < index) {
6436 _profile(PackageTable$reloadData$Section$Allocate)
6437 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6440 _profile(PackageTable$reloadData$Section$Add)
6441 [sections_ addObject:section];
6445 [section addToCount];
6451 index_ = [NSMutableArray arrayWithCapacity:32];
6453 bool sectioned([self showsSections]);
6455 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6456 [sections_ addObject:section];
6459 _profile(PackageTable$reloadData$Section)
6460 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6464 _profile(PackageTable$reloadData$Section$Package)
6465 package = [packages_ objectAtIndex:offset];
6466 index = [package index];
6469 if (sectioned && (section == nil || [section index] != index)) {
6470 _profile(PackageTable$reloadData$Section$Allocate)
6471 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6474 [index_ addObject:[section name]];
6475 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6477 _profile(PackageTable$reloadData$Section$Add)
6478 [sections_ addObject:section];
6482 [section addToCount];
6487 [self updateHeight];
6489 _profile(PackageTable$reloadData$List)
6490 [(UITableView *) list_ setDataSource:self];
6495 - (void) reloadData {
6498 if ([self shouldYield])
6499 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6504 - (void) resetCursor {
6505 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6508 - (void) clearData {
6509 [self updateHeight];
6511 [list_ setDataSource:nil];
6519 /* Filtered Package List Controller {{{ */
6520 @interface FilteredPackageListController : PackageListController {
6523 _H<NSObject> object_;
6526 - (void) setObject:(id)object;
6527 - (void) setObject:(id)object forFilter:(SEL)filter;
6530 - (void) setFilter:(SEL)filter;
6532 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6536 @implementation FilteredPackageListController
6542 - (void) setFilter:(SEL)filter {
6543 @synchronized (self) {
6546 /* XXX: this is an unsafe optimization of doomy hell */
6547 Method method(class_getInstanceMethod([Package class], filter));
6548 _assert(method != NULL);
6549 imp_ = method_getImplementation(method);
6550 _assert(imp_ != NULL);
6553 - (void) setObject:(id)object {
6554 @synchronized (self) {
6558 - (void) setObject:(id)object forFilter:(SEL)filter {
6559 @synchronized (self) {
6560 [self setFilter:filter];
6561 [self setObject:object];
6564 - (NSMutableArray *) _reloadPackages {
6565 @synchronized (database_) {
6566 era_ = [database_ era];
6567 NSArray *packages([database_ packages]);
6569 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6573 _H<NSObject> object;
6575 @synchronized (self) {
6581 _profile(PackageTable$reloadData$Filter)
6582 for (Package *package in packages)
6583 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6584 [filtered addObject:package];
6590 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6591 if ((self = [super initWithDatabase:database title:title]) != nil) {
6592 [self setFilter:filter];
6593 [self setObject:object];
6600 /* Home Controller {{{ */
6601 @interface HomeController : CydiaWebViewController {
6602 CFRunLoopRef runloop_;
6603 SCNetworkReachabilityRef reachability_;
6608 @implementation HomeController
6610 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6611 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6615 if ((self = [super init]) != nil) {
6616 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6619 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6620 if (reachability_ != NULL) {
6621 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6622 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6624 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6625 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6632 if (reachability_ != NULL && runloop_ != NULL)
6633 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6637 - (NSURL *) navigationURL {
6638 return [NSURL URLWithString:@"cydia://home"];
6641 - (void) aboutButtonClicked {
6642 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6644 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6645 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6646 [alert setCancelButtonIndex:0];
6649 @"Copyright \u00a9 2008-2011\n"
6652 "Jay Freeman (saurik)\n"
6653 "saurik@saurik.com\n"
6654 "http://www.saurik.com/"
6660 - (UIBarButtonItem *) leftButton {
6661 return [[[UIBarButtonItem alloc]
6662 initWithTitle:UCLocalize("ABOUT")
6663 style:UIBarButtonItemStylePlain
6665 action:@selector(aboutButtonClicked)
6671 /* Manage Controller {{{ */
6672 @interface ManageController : CydiaWebViewController {
6675 - (void) queueStatusDidChange;
6679 @implementation ManageController
6682 if ((self = [super init]) != nil) {
6683 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6687 - (NSURL *) navigationURL {
6688 return [NSURL URLWithString:@"cydia://manage"];
6691 - (UIBarButtonItem *) leftButton {
6692 return [[[UIBarButtonItem alloc]
6693 initWithTitle:UCLocalize("SETTINGS")
6694 style:UIBarButtonItemStylePlain
6696 action:@selector(settingsButtonClicked)
6700 - (void) settingsButtonClicked {
6701 [delegate_ showSettings];
6704 - (void) queueButtonClicked {
6708 - (UIBarButtonItem *) rightButton {
6709 return Queuing_ ? [[[UIBarButtonItem alloc]
6710 initWithTitle:UCLocalize("QUEUE")
6711 style:UIBarButtonItemStyleDone
6713 action:@selector(queueButtonClicked)
6714 ] autorelease] : nil;
6717 - (void) queueStatusDidChange {
6718 [self applyRightButton];
6721 - (bool) isLoading {
6722 return !Queuing_ && [super isLoading];
6728 /* Refresh Bar {{{ */
6729 @interface RefreshBar : UINavigationBar {
6730 _H<UIProgressIndicator> indicator_;
6731 _H<UITextLabel> prompt_;
6732 _H<UIProgressBar> progress_;
6733 _H<UINavigationButton> cancel_;
6738 @implementation RefreshBar
6740 - (void) positionViews {
6741 CGRect frame = [cancel_ frame];
6742 frame.size = [cancel_ sizeThatFits:frame.size];
6743 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6744 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6745 [cancel_ setFrame:frame];
6747 CGSize prgsize = {75, 100};
6749 [self frame].size.width - prgsize.width - 10,
6750 ([self frame].size.height - prgsize.height) / 2
6752 [progress_ setFrame:prgrect];
6754 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6755 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6756 CGRect indrect = {{indoffset, indoffset}, indsize};
6757 [indicator_ setFrame:indrect];
6759 CGSize prmsize = {215, indsize.height + 4};
6761 indoffset * 2 + indsize.width,
6762 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6764 [prompt_ setFrame:prmrect];
6767 - (void) setFrame:(CGRect)frame {
6768 [super setFrame:frame];
6769 [self positionViews];
6772 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6773 if ((self = [super initWithFrame:frame]) != nil) {
6774 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6776 [self setBarStyle:UIBarStyleBlack];
6778 UIBarStyle barstyle([self _barStyle:NO]);
6779 bool ugly(barstyle == UIBarStyleDefault);
6781 UIProgressIndicatorStyle style = ugly ?
6782 UIProgressIndicatorStyleMediumBrown :
6783 UIProgressIndicatorStyleMediumWhite;
6785 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6786 [(UIProgressIndicator *) indicator_ setStyle:style];
6787 [indicator_ startAnimation];
6788 [self addSubview:indicator_];
6790 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6791 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6792 [prompt_ setBackgroundColor:[UIColor clearColor]];
6793 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6794 [self addSubview:prompt_];
6796 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6797 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6798 [(UIProgressBar *) progress_ setStyle:0];
6799 [self addSubview:progress_];
6801 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6802 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6803 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6804 [cancel_ setBarStyle:barstyle];
6806 [self positionViews];
6810 - (void) setCancellable:(bool)cancellable {
6812 [self addSubview:cancel_];
6814 [cancel_ removeFromSuperview];
6818 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6819 [progress_ setProgress:0];
6823 [self setCancellable:NO];
6826 - (void) setPrompt:(NSString *)prompt {
6827 [prompt_ setText:prompt];
6830 - (void) setProgress:(float)progress {
6831 [progress_ setProgress:progress];
6837 /* Cydia Navigation Controller Interface {{{ */
6838 @interface UINavigationController (Cydia)
6840 - (NSArray *) navigationURLCollection;
6841 - (void) unloadData;
6846 /* Cydia Tab Bar Controller {{{ */
6847 @interface CYTabBarController : UITabBarController <
6848 UITabBarControllerDelegate,
6851 _transient Database *database_;
6852 _H<RefreshBar, 1> refreshbar_;
6856 // XXX: ok, "updatedelegate_"?...
6857 _transient NSObject<CydiaDelegate> *updatedelegate_;
6859 _H<UIViewController> remembered_;
6860 _transient UIViewController *transient_;
6863 - (NSArray *) navigationURLCollection;
6864 - (void) dropBar:(BOOL)animated;
6865 - (void) beginUpdate;
6866 - (void) raiseBar:(BOOL)animated;
6868 - (void) unloadData;
6872 @implementation CYTabBarController
6874 - (void) didReceiveMemoryWarning {
6875 [super didReceiveMemoryWarning];
6877 // presenting a UINavigationController on 2.x does not update its transitionView
6878 // it thereby will not allow its topViewController to be unloaded by memory pressure
6879 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6880 UIViewController *selected([self selectedViewController]);
6881 for (UINavigationController *controller in [self viewControllers])
6882 if (controller != selected)
6883 if (UIViewController *top = [controller topViewController])
6888 - (void) setUnselectedViewController:(UIViewController *)transient {
6889 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6890 if (transient != nil) {
6891 [[[self viewControllers] objectAtIndex:0] pushViewController:transient animated:YES];
6892 [self setSelectedIndex:0];
6896 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6897 if (transient != nil) {
6898 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
6899 [navigation setViewControllers:[NSArray arrayWithObject:transient]];
6900 transient = navigation;
6902 if (transient_ == nil)
6903 remembered_ = [controllers objectAtIndex:0];
6904 transient_ = transient;
6905 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6906 [controllers replaceObjectAtIndex:0 withObject:transient_];
6907 [self setSelectedIndex:0];
6908 [self setViewControllers:controllers];
6909 [self concealTabBarSelection];
6910 } else if (remembered_ != nil) {
6911 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6912 transient_ = transient;
6913 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6915 [self setViewControllers:controllers];
6916 [self revealTabBarSelection];
6920 - (UIViewController *) unselectedViewController {
6924 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6925 if ([self unselectedViewController])
6926 [self setUnselectedViewController:nil];
6928 // presenting a UINavigationController on 2.x does not update its transitionView
6929 // if this view was unloaded, the tranitionView may currently be presenting nothing
6930 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6931 UINavigationController *navigation((UINavigationController *) viewController);
6932 [navigation pushViewController:[[[UIViewController alloc] init] autorelease] animated:NO];
6933 [navigation popViewControllerAnimated:NO];
6937 - (NSArray *) navigationURLCollection {
6938 NSMutableArray *items([NSMutableArray array]);
6940 // XXX: Should this deal with transient view controllers?
6941 for (id navigation in [self viewControllers]) {
6942 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6944 [items addObject:stack];
6950 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6951 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6952 [self setUnselectedViewController:nil];
6954 [super dismissModalViewControllerAnimated:YES];
6957 - (void) unloadData {
6960 for (UINavigationController *controller in [self viewControllers])
6961 [controller unloadData];
6963 if (UIViewController *selected = [self selectedViewController])
6964 [selected reloadData];
6966 if (UIViewController *unselected = [self unselectedViewController]) {
6967 [unselected unloadData];
6968 [unselected reloadData];
6973 [[NSNotificationCenter defaultCenter] removeObserver:self];
6978 - (id) initWithDatabase:(Database *)database {
6979 if ((self = [super init]) != nil) {
6980 database_ = database;
6981 [self setDelegate:self];
6983 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6984 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6986 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6990 - (void) setUpdate:(NSDate *)date {
6994 - (void) beginUpdate {
6995 [(RefreshBar *) refreshbar_ start];
6998 [updatedelegate_ retainNetworkActivityIndicator];
7002 detachNewThreadSelector:@selector(performUpdate)
7008 - (void) performUpdate {
7009 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7012 status.setDelegate(self);
7013 [database_ updateWithStatus:status];
7016 performSelectorOnMainThread:@selector(completeUpdate)
7024 - (void) stopUpdateWithSelector:(SEL)selector {
7026 [updatedelegate_ releaseNetworkActivityIndicator];
7028 [self raiseBar:YES];
7031 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7034 - (void) completeUpdate {
7037 [self stopUpdateWithSelector:@selector(reloadData)];
7040 - (void) cancelUpdate {
7041 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7044 - (void) cancelPressed {
7045 [self cancelUpdate];
7052 - (void) addProgressEvent:(CydiaProgressEvent *)event {
7053 [refreshbar_ setPrompt:[event compoundMessage]];
7056 - (bool) isProgressCancelled {
7060 - (void) setProgressCancellable:(NSNumber *)cancellable {
7061 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
7064 - (void) setProgressPercent:(NSNumber *)percent {
7065 [refreshbar_ setProgress:[percent floatValue]];
7068 - (void) setProgressStatus:(NSDictionary *)status {
7070 [self setProgressPercent:[status objectForKey:@"Percent"]];
7073 - (void) setUpdateDelegate:(id)delegate {
7074 updatedelegate_ = delegate;
7077 - (UIView *) transitionView {
7078 if ([self respondsToSelector:@selector(_transitionView)])
7079 return [self _transitionView];
7081 return MSHookIvar<id>(self, "_viewControllerTransitionView");
7084 - (void) dropBar:(BOOL)animated {
7089 UIView *transition([self transitionView]);
7090 [[self view] addSubview:refreshbar_];
7092 CGRect barframe([refreshbar_ frame]);
7094 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
7095 barframe.origin.y = CYStatusBarHeight();
7097 barframe.origin.y = 0;
7099 [refreshbar_ setFrame:barframe];
7102 [UIView beginAnimations:nil context:NULL];
7104 CGRect viewframe = [transition frame];
7105 viewframe.origin.y += barframe.size.height;
7106 viewframe.size.height -= barframe.size.height;
7107 [transition setFrame:viewframe];
7110 [UIView commitAnimations];
7112 // Ensure bar has the proper width for our view, it might have changed
7113 barframe.size.width = viewframe.size.width;
7114 [refreshbar_ setFrame:barframe];
7117 - (void) raiseBar:(BOOL)animated {
7122 UIView *transition([self transitionView]);
7123 [refreshbar_ removeFromSuperview];
7125 CGRect barframe([refreshbar_ frame]);
7128 [UIView beginAnimations:nil context:NULL];
7130 CGRect viewframe = [transition frame];
7131 viewframe.origin.y -= barframe.size.height;
7132 viewframe.size.height += barframe.size.height;
7133 [transition setFrame:viewframe];
7136 [UIView commitAnimations];
7139 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7140 bool dropped(dropped_);
7145 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7151 - (void) statusBarFrameChanged:(NSNotification *)notification {
7161 /* Cydia Navigation Controller Implementation {{{ */
7162 @implementation UINavigationController (Cydia)
7164 - (NSArray *) navigationURLCollection {
7165 NSMutableArray *stack([NSMutableArray array]);
7167 for (CyteViewController *controller in [self viewControllers]) {
7168 NSString *url = [[controller navigationURL] absoluteString];
7170 [stack addObject:url];
7176 - (void) reloadData {
7179 UIViewController *visible([self visibleViewController]);
7181 [visible reloadData];
7183 // on the iPad, this view controller is ALSO visible. :(
7185 if (UIViewController *top = [self topViewController])
7190 - (void) unloadData {
7191 for (CyteViewController *page in [self viewControllers])
7200 /* Cydia:// Protocol {{{ */
7201 @interface CydiaURLProtocol : NSURLProtocol {
7206 @implementation CydiaURLProtocol
7208 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7209 NSURL *url([request URL]);
7213 NSString *scheme([[url scheme] lowercaseString]);
7214 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7216 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7222 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7226 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7227 id<NSURLProtocolClient> client([self client]);
7229 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7231 NSData *data(UIImagePNGRepresentation(icon));
7233 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7234 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7235 [client URLProtocol:self didLoadData:data];
7236 [client URLProtocolDidFinishLoading:self];
7240 - (void) startLoading {
7241 id<NSURLProtocolClient> client([self client]);
7242 NSURLRequest *request([self request]);
7244 NSURL *url([request URL]);
7245 NSString *href([url absoluteString]);
7246 NSString *scheme([[url scheme] lowercaseString]);
7250 if ([scheme isEqualToString:@"cydia"])
7251 path = [href substringFromIndex:8];
7252 else if ([scheme isEqualToString:@"about"])
7253 path = [href substringFromIndex:12];
7254 else _assert(false);
7256 NSRange slash([path rangeOfString:@"/"]);
7259 if (slash.location == NSNotFound) {
7263 command = [path substringToIndex:slash.location];
7264 path = [path substringFromIndex:(slash.location + 1)];
7267 Database *database([Database sharedInstance]);
7269 if ([command isEqualToString:@"package-icon"]) {
7272 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7273 Package *package([database packageWithName:path]);
7277 UIImage *icon([package icon]);
7278 [self _returnPNGWithImage:icon forRequest:request];
7279 } else if ([command isEqualToString:@"uikit-image"]) {
7282 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7283 UIImage *icon(_UIImageWithName(path));
7284 [self _returnPNGWithImage:icon forRequest:request];
7285 } else if ([command isEqualToString:@"section-icon"]) {
7288 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7289 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7291 icon = [UIImage applicationImageNamed:@"unknown.png"];
7292 [self _returnPNGWithImage:icon forRequest:request];
7294 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7298 - (void) stopLoading {
7304 /* Section Controller {{{ */
7305 @interface SectionController : FilteredPackageListController {
7306 _H<IndirectDelegate, 1> indirect_;
7307 _H<CydiaObject> cydia_;
7308 _H<NSString> section_;
7309 std::vector< _H<CyteWebViewTableViewCell, 1> > promoted_;
7312 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7316 @implementation SectionController
7318 - (NSURL *) referrerURL {
7319 NSString *name = section_;
7323 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@", UI_, [name stringByAddingPercentEscapesIncludingReserved]]];
7326 - (NSURL *) navigationURL {
7327 NSString *name = section_;
7331 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", [name stringByAddingPercentEscapesIncludingReserved]]];
7334 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7337 title = UCLocalize("ALL_PACKAGES");
7338 else if (![name isEqual:@""])
7339 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7341 title = UCLocalize("NO_SECTION");
7343 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7344 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7345 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7350 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7351 return [super numberOfSectionsInTableView:list] + 1;
7354 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7355 return section == 0 ? nil : [super tableView:list titleForHeaderInSection:(section - 1)];
7358 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7359 return section == 0 ? promoted_.size() : [super tableView:list numberOfRowsInSection:(section - 1)];
7362 + (NSIndexPath *) adjustedIndexPath:(NSIndexPath *)path {
7363 return [NSIndexPath indexPathForRow:[path row] inSection:([path section] - 1)];
7366 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7367 if ([path section] != 0)
7368 return [super tableView:table cellForRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7370 return promoted_[[path row]];
7373 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
7374 if ([path section] != 0)
7375 return [super tableView:table didSelectRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7378 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
7379 NSInteger section([super tableView:tableView sectionForSectionIndexTitle:title atIndex:index]);
7380 return section == 0 ? 0 : section + 1;
7383 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7384 NSURL *url([request URL]);
7388 if ([frame isEqualToString:@"_open"])
7389 [delegate_ openURL:url];
7391 WebFrame *frame(nil);
7392 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7393 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7395 frame = [view mainFrame];
7397 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7399 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7400 [controller setDelegate:delegate_];
7401 [[self navigationController] pushViewController:controller animated:YES];
7407 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7408 return [CydiaWebViewController requestWithHeaders:request];
7411 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7412 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7418 // XXX: this code is horrible. I mean, wtf Jay?
7419 if (ShowPromoted_ && [[Metadata_ objectForKey:@"ShowPromoted"] boolValue]) {
7420 promoted_.resize(1);
7422 for (unsigned i(0); i != promoted_.size(); ++i) {
7423 CyteWebViewTableViewCell *promoted([CyteWebViewTableViewCell cellWithRequest:[NSURLRequest
7424 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sectionhead/%u/%@",
7425 UI_, i, section_ == nil ? @"" : [section_ stringByAddingPercentEscapesIncludingReserved]]
7428 cachePolicy:NSURLRequestUseProtocolCachePolicy
7432 [promoted setDelegate:self];
7433 promoted_[i] = promoted;
7438 - (void) setDelegate:(id)delegate {
7439 [super setDelegate:delegate];
7440 [cydia_ setDelegate:delegate];
7443 - (void) releaseSubviews {
7445 [super releaseSubviews];
7450 /* Sections Controller {{{ */
7451 @interface SectionsController : CyteViewController <
7452 UITableViewDataSource,
7455 _transient Database *database_;
7456 _H<NSMutableArray> sections_;
7457 _H<NSMutableArray> filtered_;
7458 _H<UITableView, 2> list_;
7461 - (id) initWithDatabase:(Database *)database;
7462 - (void) editButtonClicked;
7466 @implementation SectionsController
7468 - (NSURL *) navigationURL {
7469 return [NSURL URLWithString:@"cydia://sections"];
7472 - (void) updateNavigationItem {
7473 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7474 if ([sections_ count] == 0) {
7475 [[self navigationItem] setRightBarButtonItem:nil];
7477 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7478 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7480 action:@selector(editButtonClicked)
7481 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7485 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7486 [super setEditing:editing animated:animated];
7491 [delegate_ updateData];
7493 [self updateNavigationItem];
7496 - (void) viewDidAppear:(BOOL)animated {
7497 [super viewDidAppear:animated];
7498 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7501 - (void) viewWillDisappear:(BOOL)animated {
7502 [super viewWillDisappear:animated];
7503 [self setEditing:NO];
7506 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7507 Section *section = nil;
7508 int index = [indexPath row];
7509 if (![self isEditing]) {
7512 section = [filtered_ objectAtIndex:index];
7514 section = [sections_ objectAtIndex:index];
7519 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7520 if ([self isEditing])
7521 return [sections_ count];
7523 return [filtered_ count] + 1;
7526 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7530 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7531 static NSString *reuseIdentifier = @"SectionCell";
7533 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7535 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7537 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7542 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7543 if ([self isEditing])
7546 Section *section = [self sectionAtIndexPath:indexPath];
7548 SectionController *controller = [[[SectionController alloc]
7549 initWithDatabase:database_
7550 section:[section name]
7552 [controller setDelegate:delegate_];
7554 [[self navigationController] pushViewController:controller animated:YES];
7558 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7559 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7560 [list_ setRowHeight:45.0f];
7561 [(UITableView *) list_ setDataSource:self];
7562 [list_ setDelegate:self];
7563 [self setView:list_];
7566 - (void) viewDidLoad {
7567 [super viewDidLoad];
7569 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7572 - (void) releaseSubviews {
7578 [super releaseSubviews];
7581 - (id) initWithDatabase:(Database *)database {
7582 if ((self = [super init]) != nil) {
7583 database_ = database;
7587 - (void) reloadData {
7590 NSArray *packages = [database_ packages];
7592 sections_ = [NSMutableArray arrayWithCapacity:16];
7593 filtered_ = [NSMutableArray arrayWithCapacity:16];
7595 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7598 for (Package *package in packages) {
7599 NSString *name([package section]);
7600 NSString *key(name == nil ? @"" : name);
7604 _profile(SectionsView$reloadData$Section)
7605 section = [sections objectForKey:key];
7606 if (section == nil) {
7607 _profile(SectionsView$reloadData$Section$Allocate)
7608 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7609 [sections setObject:section forKey:key];
7614 [section addToCount];
7616 _profile(SectionsView$reloadData$Filter)
7617 if (![package valid] || ![package visible])
7625 [sections_ addObjectsFromArray:[sections allValues]];
7627 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7629 for (Section *section in (id) sections_) {
7630 size_t count([section row]);
7634 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7635 [section setCount:count];
7636 [filtered_ addObject:section];
7639 [self updateNavigationItem];
7644 - (void) editButtonClicked {
7645 [self setEditing:![self isEditing] animated:YES];
7651 /* Changes Controller {{{ */
7652 @interface ChangesController : CyteViewController <
7653 UITableViewDataSource,
7656 _transient Database *database_;
7658 _H<NSArray> packages_;
7659 _H<NSMutableArray> sections_;
7660 _H<UITableView, 2> list_;
7661 _H<CyteWebView, 1> dickbar_;
7663 _H<IndirectDelegate, 1> indirect_;
7664 _H<CydiaObject> cydia_;
7667 - (id) initWithDatabase:(Database *)database;
7671 @implementation ChangesController
7673 - (NSURL *) navigationURL {
7674 return [NSURL URLWithString:@"cydia://changes"];
7677 - (void) viewDidAppear:(BOOL)animated {
7678 [super viewDidAppear:animated];
7679 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7682 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7683 NSInteger count([sections_ count]);
7684 return count == 0 ? 1 : count;
7687 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7688 if ([sections_ count] == 0)
7690 return [[sections_ objectAtIndex:section] name];
7693 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7694 if ([sections_ count] == 0)
7696 return [[sections_ objectAtIndex:section] count];
7699 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7700 @synchronized (database_) {
7701 if ([database_ era] != era_)
7704 NSUInteger sectionIndex([path section]);
7705 if (sectionIndex >= [sections_ count])
7707 Section *section([sections_ objectAtIndex:sectionIndex]);
7708 NSInteger row([path row]);
7709 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7712 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7713 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7715 cell = [[[PackageCell alloc] init] autorelease];
7717 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7718 [cell setPackage:package asSummary:false];
7722 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7723 Package *package([self packageAtIndexPath:path]);
7724 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[NSString stringWithFormat:@"%@/#!/changes/", UI_]] autorelease]);
7725 [view setDelegate:delegate_];
7726 [[self navigationController] pushViewController:view animated:YES];
7730 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7731 NSString *context([alert context]);
7733 if ([context isEqualToString:@"norefresh"])
7734 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7737 - (void) refreshButtonClicked {
7738 if (IsReachable("cydia.saurik.com")) {
7739 [delegate_ beginUpdate];
7740 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7742 UIAlertView *alert = [[[UIAlertView alloc]
7743 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
7744 message:@"Host Unreachable" // XXX: Localize
7746 cancelButtonTitle:UCLocalize("OK")
7747 otherButtonTitles:nil
7750 [alert setContext:@"norefresh"];
7755 - (void) upgradeButtonClicked {
7756 [delegate_ distUpgrade];
7757 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7761 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7762 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7763 [self setView:view];
7765 list_ = [[[UITableView alloc] initWithFrame:[view bounds] style:UITableViewStylePlain] autorelease];
7766 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7767 [list_ setRowHeight:73];
7768 [(UITableView *) list_ setDataSource:self];
7769 [list_ setDelegate:self];
7770 [view addSubview:list_];
7772 if (AprilFools_ && kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
7773 CGRect dickframe([view bounds]);
7774 dickframe.size.height = 44;
7776 dickbar_ = [[[CyteWebView alloc] initWithFrame:dickframe] autorelease];
7777 [dickbar_ setDelegate:self];
7778 [view addSubview:dickbar_];
7780 [dickbar_ setBackgroundColor:[UIColor clearColor]];
7781 [dickbar_ setScalesPageToFit:YES];
7783 UIWebDocumentView *document([dickbar_ _documentView]);
7784 [document setBackgroundColor:[UIColor clearColor]];
7785 [document setDrawsBackground:NO];
7787 WebView *webview([document webView]);
7788 [webview setShouldUpdateWhileOffscreen:NO];
7790 UIScrollView *scroller([dickbar_ scrollView]);
7791 [scroller setScrollingEnabled:NO];
7792 [scroller setFixedBackgroundPattern:YES];
7793 [scroller setBackgroundColor:[UIColor clearColor]];
7795 WebPreferences *preferences([webview preferences]);
7796 [preferences setCacheModel:WebCacheModelDocumentBrowser];
7797 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
7798 [preferences setOfflineWebApplicationCacheEnabled:YES];
7800 [dickbar_ loadRequest:[NSURLRequest
7801 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/dickbar/", UI_]]]
7802 cachePolicy:NSURLRequestUseProtocolCachePolicy
7806 UIEdgeInsets inset = {44, 0, 0, 0};
7807 [list_ setContentInset:inset];
7809 [dickbar_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7813 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7814 NSURL *url([request URL]);
7818 if ([frame isEqualToString:@"_open"])
7819 [delegate_ openURL:url];
7821 WebFrame *frame(nil);
7822 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7823 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7825 frame = [view mainFrame];
7827 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7829 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7830 [controller setDelegate:delegate_];
7831 [[self navigationController] pushViewController:controller animated:YES];
7837 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7838 return [CydiaWebViewController requestWithHeaders:request];
7841 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7842 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7845 - (void) setDelegate:(id)delegate {
7846 [super setDelegate:delegate];
7847 [cydia_ setDelegate:delegate];
7850 - (void) viewDidLoad {
7851 [super viewDidLoad];
7853 [[self navigationItem] setTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES"))];
7856 - (void) releaseSubviews {
7863 [super releaseSubviews];
7866 - (id) initWithDatabase:(Database *)database {
7867 if ((self = [super init]) != nil) {
7868 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7869 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7870 database_ = database;
7874 - (NSMutableArray *) _reloadPackages {
7875 @synchronized (database_) {
7876 era_ = [database_ era];
7877 NSArray *packages([database_ packages]);
7879 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7882 _profile(ChangesController$_reloadPackages$Filter)
7883 for (Package *package in packages)
7884 if ([package upgradableAndEssential:YES] || [package visible])
7885 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7888 _profile(ChangesController$_reloadPackages$radixSort)
7889 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7896 - (void) _reloadData {
7901 UIProgressHUD *hud([delegate_ addProgressHUD]);
7902 [hud setText:UCLocalize("LOADING")];
7903 //NSLog(@"HUD:%@::%@", delegate_, hud);
7904 packages = [self yieldToSelector:@selector(_reloadPackages)];
7905 [delegate_ removeProgressHUD:hud];
7907 packages = [self _reloadPackages];
7910 @synchronized (database_) {
7911 if (era_ != [database_ era])
7914 packages_ = packages;
7915 sections_ = [NSMutableArray arrayWithCapacity:16];
7917 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7918 Section *ignored = nil;
7919 Section *section = nil;
7923 bool unseens = false;
7925 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7927 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7928 Package *package = [packages_ objectAtIndex:offset];
7930 BOOL uae = [package upgradableAndEssential:YES];
7934 time_t seen([package seen]);
7936 if (section == nil || last != seen) {
7940 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7943 _profile(ChangesController$reloadData$Allocate)
7944 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7945 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7946 [sections_ addObject:section];
7950 [section addToCount];
7951 } else if ([package ignored]) {
7952 if (ignored == nil) {
7953 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7955 [ignored addToCount];
7958 [upgradable addToCount];
7963 CFRelease(formatter);
7966 Section *last = [sections_ lastObject];
7967 size_t count = [last count];
7968 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7969 [sections_ removeLastObject];
7972 if ([ignored count] != 0)
7973 [sections_ insertObject:ignored atIndex:0];
7975 [sections_ insertObject:upgradable atIndex:0];
7979 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7980 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7981 style:UIBarButtonItemStylePlain
7983 action:@selector(upgradeButtonClicked)
7984 ] autorelease]) animated:YES];
7986 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7987 initWithTitle:UCLocalize("REFRESH")
7988 style:UIBarButtonItemStylePlain
7990 action:@selector(refreshButtonClicked)
7991 ] autorelease]) animated:YES];
7996 - (void) reloadData {
7998 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
8003 /* Search Controller {{{ */
8004 @interface SearchController : FilteredPackageListController <
8007 _H<UISearchBar, 1> search_;
8011 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
8012 - (void) reloadData;
8016 @implementation SearchController
8018 - (NSURL *) referrerURL {
8019 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
8022 - (NSURL *) navigationURL {
8023 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
8024 return [NSURL URLWithString:@"cydia://search"];
8026 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
8029 - (NSArray *) termsForQuery:(NSString *)query {
8030 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
8031 for (NSString *component in [query componentsSeparatedByString:@" "])
8032 if ([component length] != 0)
8033 [terms addObject:component];
8038 - (void) useSearch {
8039 [self setObject:[self termsForQuery:[search_ text]] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
8044 - (void) viewWillAppear:(BOOL)animated {
8045 [super viewWillAppear:animated];
8047 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
8051 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
8052 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8057 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
8058 [search_ resignFirstResponder];
8062 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
8063 [search_ setText:@""];
8064 [self searchBarButtonClicked:searchBar];
8067 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
8068 [self searchBarButtonClicked:searchBar];
8071 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
8072 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8076 - (bool) shouldYield {
8080 - (bool) shouldBlock {
8081 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
8084 - (bool) isSummarized {
8085 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
8088 - (bool) showsSections {
8092 - (NSMutableArray *) _reloadPackages {
8093 NSMutableArray *packages([super _reloadPackages]);
8094 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8095 [packages radixSortUsingSelector:@selector(rank)];
8099 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
8100 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[self termsForQuery:query]])) {
8101 search_ = [[[UISearchBar alloc] init] autorelease];
8102 [search_ setDelegate:self];
8105 [search_ setText:query];
8109 - (void) viewDidAppear:(BOOL)animated {
8110 [super viewDidAppear:animated];
8112 if (!searchloaded_) {
8113 searchloaded_ = YES;
8114 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
8115 [search_ layoutSubviews];
8116 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
8118 UITextField *textField;
8119 if ([search_ respondsToSelector:@selector(searchField)])
8120 textField = [search_ searchField];
8122 textField = MSHookIvar<UITextField *>(search_, "_searchField");
8124 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8125 [textField setEnablesReturnKeyAutomatically:NO];
8126 [[self navigationItem] setTitleView:textField];
8130 - (void) reloadData {
8131 id object([search_ text]);
8132 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8133 object = [self termsForQuery:object];
8135 [self setObject:object];
8141 - (void) didSelectPackage:(Package *)package {
8142 [search_ resignFirstResponder];
8143 [super didSelectPackage:package];
8148 /* Package Settings Controller {{{ */
8149 @interface PackageSettingsController : CyteViewController <
8150 UITableViewDataSource,
8153 _transient Database *database_;
8155 _H<Package> package_;
8156 _H<UITableView, 2> table_;
8157 _H<UISwitch> subscribedSwitch_;
8158 _H<UISwitch> ignoredSwitch_;
8159 _H<UITableViewCell> subscribedCell_;
8160 _H<UITableViewCell> ignoredCell_;
8163 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
8167 @implementation PackageSettingsController
8169 - (NSURL *) navigationURL {
8170 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
8173 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8174 if (package_ == nil)
8177 if ([package_ installed] == nil)
8183 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8184 if (package_ == nil)
8187 // both sections contain just one item right now.
8191 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8195 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8197 return UCLocalize("SHOW_ALL_CHANGES_EX");
8199 return UCLocalize("IGNORE_UPGRADES_EX");
8202 - (void) onSubscribed:(id)control {
8203 bool value([control isOn]);
8204 if (package_ == nil)
8206 if ([package_ setSubscribed:value])
8207 [delegate_ updateData];
8210 - (void) _updateIgnored {
8211 const char *package([name_ UTF8String]);
8212 bool on([ignoredSwitch_ isOn]);
8214 pid_t pid(ExecFork());
8216 FILE *dpkg(popen("dpkg --set-selections", "w"));
8217 fwrite(package, strlen(package), 1, dpkg);
8220 fwrite(" hold\n", 6, 1, dpkg);
8222 fwrite(" install\n", 9, 1, dpkg);
8233 - (void) onIgnored:(id)control {
8234 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8235 [invocation setTarget:self];
8236 [invocation setSelector:@selector(_updateIgnored)];
8238 [delegate_ reloadDataWithInvocation:invocation];
8241 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8242 if (package_ == nil)
8245 switch ([indexPath section]) {
8246 case 0: return subscribedCell_;
8247 case 1: return ignoredCell_;
8256 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8257 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8258 [self setView:view];
8260 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8261 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8262 [(UITableView *) table_ setDataSource:self];
8263 [table_ setDelegate:self];
8264 [view addSubview:table_];
8266 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8267 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8268 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8270 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8271 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8272 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8274 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8275 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8276 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8277 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8279 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8280 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8281 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8282 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8285 - (void) viewDidLoad {
8286 [super viewDidLoad];
8288 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8291 - (void) releaseSubviews {
8293 subscribedCell_ = nil;
8295 ignoredSwitch_ = nil;
8296 subscribedSwitch_ = nil;
8298 [super releaseSubviews];
8301 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8302 if ((self = [super init]) != nil) {
8303 database_ = database;
8308 - (void) reloadData {
8311 package_ = [database_ packageWithName:name_];
8313 if (package_ != nil) {
8314 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8315 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8316 } // XXX: what now, G?
8318 [table_ reloadData];
8324 /* Installed Controller {{{ */
8325 @interface InstalledController : FilteredPackageListController {
8329 - (id) initWithDatabase:(Database *)database;
8331 - (void) updateRoleButton;
8332 - (void) queueStatusDidChange;
8336 @implementation InstalledController
8338 - (NSURL *) referrerURL {
8339 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8342 - (NSURL *) navigationURL {
8343 return [NSURL URLWithString:@"cydia://installed"];
8346 - (id) initWithDatabase:(Database *)database {
8347 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8348 [self updateRoleButton];
8349 [self queueStatusDidChange];
8354 - (void) queueButtonClicked {
8359 - (void) queueStatusDidChange {
8363 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8364 initWithTitle:UCLocalize("QUEUE")
8365 style:UIBarButtonItemStyleDone
8367 action:@selector(queueButtonClicked)
8370 [[self navigationItem] setLeftBarButtonItem:nil];
8376 - (void) updateRoleButton {
8377 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8378 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8379 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8380 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8382 action:@selector(roleButtonClicked)
8386 - (void) roleButtonClicked {
8387 [self setObject:[NSNumber numberWithBool:expert_]];
8391 [self updateRoleButton];
8397 /* Source Cell {{{ */
8398 @interface SourceCell : CyteTableViewCell <
8399 CyteTableViewCellDelegate
8403 _H<NSString> origin_;
8404 _H<NSString> label_;
8407 - (void) setSource:(Source *)source;
8411 @implementation SourceCell
8413 - (void) _setImage:(NSArray *)data {
8414 if ([url_ isEqual:[data objectAtIndex:0]]) {
8415 icon_ = [data objectAtIndex:1];
8416 [content_ setNeedsDisplay];
8420 - (void) _setSource:(NSURL *) url {
8421 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8423 if (NSData *data = [NSURLConnection
8424 sendSynchronousRequest:[NSURLRequest
8426 cachePolicy:NSURLRequestUseProtocolCachePolicy
8430 returningResponse:NULL
8433 if (UIImage *image = [UIImage imageWithData:data])
8434 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8439 - (void) setSource:(Source *)source {
8440 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8442 origin_ = [source name];
8443 label_ = [source rooturi];
8445 [content_ setNeedsDisplay];
8447 url_ = [source iconURL];
8448 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8451 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8452 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8453 UIView *content([self contentView]);
8454 CGRect bounds([content bounds]);
8456 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8457 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8458 [content_ setBackgroundColor:[UIColor whiteColor]];
8459 [content addSubview:content_];
8461 [content_ setDelegate:self];
8462 [content_ setOpaque:YES];
8464 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8468 - (NSString *) accessibilityLabel {
8472 - (void) drawContentRect:(CGRect)rect {
8473 bool highlighted(highlighted_);
8474 float width(rect.size.width);
8478 rect.size = [(UIImage *) icon_ size];
8480 while (rect.size.width > 32 || rect.size.height > 32) {
8481 rect.size.width /= 2;
8482 rect.size.height /= 2;
8485 rect.origin.x = 25 - rect.size.width / 2;
8486 rect.origin.y = 25 - rect.size.height / 2;
8488 [icon_ drawInRect:rect];
8496 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 65) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8500 [label_ drawAtPoint:CGPointMake(48, 29) forWidth:(width - 65) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8505 /* Source Controller {{{ */
8506 @interface SourceController : FilteredPackageListController {
8507 _transient Source *source_;
8511 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8515 @implementation SourceController
8517 - (NSURL *) referrerURL {
8518 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sources/%@", UI_, [key_ stringByAddingPercentEscapesIncludingReserved]]];
8521 - (NSURL *) navigationURL {
8522 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8525 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8526 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8528 key_ = [source key];
8532 - (void) reloadData {
8533 source_ = [database_ sourceWithKey:key_];
8534 key_ = [source_ key];
8535 [self setObject:source_];
8537 [[self navigationItem] setTitle:[source_ label]];
8544 /* Sources Controller {{{ */
8545 @interface SourcesController : CyteViewController <
8546 UITableViewDataSource,
8549 _transient Database *database_;
8552 _H<UITableView, 2> list_;
8553 _H<NSMutableArray> sources_;
8557 _H<UIProgressHUD> hud_;
8560 //NSURLConnection *installer_;
8561 NSURLConnection *trivial_;
8562 NSURLConnection *trivial_bz2_;
8563 NSURLConnection *trivial_gz_;
8564 //NSURLConnection *automatic_;
8569 - (id) initWithDatabase:(Database *)database;
8570 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8574 @implementation SourcesController
8576 - (void) _releaseConnection:(NSURLConnection *)connection {
8577 if (connection != nil) {
8578 [connection cancel];
8579 //[connection setDelegate:nil];
8580 [connection release];
8585 //[self _releaseConnection:installer_];
8586 [self _releaseConnection:trivial_];
8587 [self _releaseConnection:trivial_gz_];
8588 [self _releaseConnection:trivial_bz2_];
8589 //[self _releaseConnection:automatic_];
8594 - (NSURL *) navigationURL {
8595 return [NSURL URLWithString:@"cydia://sources"];
8598 - (void) viewDidAppear:(BOOL)animated {
8599 [super viewDidAppear:animated];
8600 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8603 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8607 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8611 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8612 return [sources_ count];
8615 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8616 @synchronized (database_) {
8617 if ([database_ era] != era_)
8620 NSUInteger index([indexPath row]);
8621 return index < [sources_ count] ? [sources_ objectAtIndex:index] : nil;
8624 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8625 static NSString *cellIdentifier = @"SourceCell";
8627 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8628 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8629 [cell setSource:[self sourceAtIndexPath:indexPath]];
8630 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8635 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8636 Source *source = [self sourceAtIndexPath:indexPath];
8637 if (source == nil) return;
8639 SourceController *controller = [[[SourceController alloc]
8640 initWithDatabase:database_
8644 [controller setDelegate:delegate_];
8646 [[self navigationController] pushViewController:controller animated:YES];
8649 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8650 Source *source = [self sourceAtIndexPath:indexPath];
8651 return [source record] != nil;
8654 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8655 if (editingStyle == UITableViewCellEditingStyleDelete) {
8656 Source *source = [self sourceAtIndexPath:indexPath];
8657 if (source == nil) return;
8659 [Sources_ removeObjectForKey:[source key]];
8660 [delegate_ _saveConfig];
8661 [delegate_ reloadDataWithInvocation:nil];
8666 [delegate_ addTrivialSource:href_];
8669 [delegate_ syncData];
8672 - (NSString *) getWarning {
8673 NSString *href(href_);
8674 NSRange colon([href rangeOfString:@"://"]);
8675 if (colon.location != NSNotFound)
8676 href = [href substringFromIndex:(colon.location + 3)];
8677 href = [href stringByAddingPercentEscapes];
8678 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8680 NSURL *url([NSURL URLWithString:href]);
8682 NSStringEncoding encoding;
8683 NSError *error(nil);
8685 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8686 return [warning length] == 0 ? nil : warning;
8690 - (void) _endConnection:(NSURLConnection *)connection {
8691 // XXX: the memory management in this method is horribly awkward
8693 NSURLConnection **field = NULL;
8694 if (connection == trivial_)
8696 else if (connection == trivial_bz2_)
8697 field = &trivial_bz2_;
8698 else if (connection == trivial_gz_)
8699 field = &trivial_gz_;
8700 _assert(field != NULL);
8701 [connection release];
8706 trivial_bz2_ == nil &&
8709 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8711 [delegate_ releaseNetworkActivityIndicator];
8713 [delegate_ removeProgressHUD:hud_];
8717 if (warning != nil) {
8718 UIAlertView *alert = [[[UIAlertView alloc]
8719 initWithTitle:UCLocalize("SOURCE_WARNING")
8722 cancelButtonTitle:UCLocalize("CANCEL")
8724 UCLocalize("ADD_ANYWAY"),
8728 [alert setContext:@"warning"];
8729 [alert setNumberOfRows:1];
8732 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8738 } else if (error_ != nil) {
8739 UIAlertView *alert = [[[UIAlertView alloc]
8740 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8741 message:[error_ localizedDescription]
8743 cancelButtonTitle:UCLocalize("OK")
8744 otherButtonTitles:nil
8747 [alert setContext:@"urlerror"];
8752 UIAlertView *alert = [[[UIAlertView alloc]
8753 initWithTitle:UCLocalize("NOT_REPOSITORY")
8754 message:UCLocalize("NOT_REPOSITORY_EX")
8756 cancelButtonTitle:UCLocalize("OK")
8757 otherButtonTitles:nil
8760 [alert setContext:@"trivial"];
8770 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8771 switch ([response statusCode]) {
8777 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8778 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8780 [self _endConnection:connection];
8783 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8784 [self _endConnection:connection];
8787 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8788 NSURL *url([NSURL URLWithString:href]);
8790 NSMutableURLRequest *request = [NSMutableURLRequest
8792 cachePolicy:NSURLRequestUseProtocolCachePolicy
8796 [request setHTTPMethod:method];
8798 if (Machine_ != NULL)
8799 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8801 if (UniqueID_ != nil)
8802 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8804 if ([url isCydiaSecure]) {
8805 if (UniqueID_ != nil)
8806 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8809 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8812 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8813 NSString *context([alert context]);
8815 if ([context isEqualToString:@"source"]) {
8818 NSString *href = [[alert textField] text];
8820 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8822 if (![href hasSuffix:@"/"])
8823 href_ = [href stringByAppendingString:@"/"];
8827 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8828 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8829 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8830 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8834 // XXX: this is stupid
8835 hud_ = [delegate_ addProgressHUD];
8836 [hud_ setText:UCLocalize("VERIFYING_URL")];
8837 [delegate_ retainNetworkActivityIndicator];
8846 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8847 } else if ([context isEqualToString:@"trivial"])
8848 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8849 else if ([context isEqualToString:@"urlerror"])
8850 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8851 else if ([context isEqualToString:@"warning"]) {
8854 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8863 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8868 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8869 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8870 [list_ setRowHeight:53];
8871 [(UITableView *) list_ setDataSource:self];
8872 [list_ setDelegate:self];
8873 [self setView:list_];
8876 - (void) viewDidLoad {
8877 [super viewDidLoad];
8879 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8880 [self updateButtonsForEditingStatusAnimated:NO];
8883 - (void) viewWillDisappear:(BOOL)animated {
8884 [super viewWillAppear:animated];
8886 [list_ setEditing:NO];
8887 [self updateButtonsForEditingStatusAnimated:NO];
8890 - (void) releaseSubviews {
8895 [super releaseSubviews];
8898 - (id) initWithDatabase:(Database *)database {
8899 if ((self = [super init]) != nil) {
8900 database_ = database;
8904 - (void) reloadData {
8907 @synchronized (database_) {
8908 era_ = [database_ era];
8910 sources_ = [NSMutableArray arrayWithCapacity:16];
8911 [sources_ addObjectsFromArray:[database_ sources]];
8913 [sources_ sortUsingSelector:@selector(compareByName:)];
8916 int count([sources_ count]);
8918 for (int i = 0; i != count; i++) {
8919 if ([[sources_ objectAtIndex:i] record] == nil)
8927 - (void) showAddSourcePrompt {
8928 UIAlertView *alert = [[[UIAlertView alloc]
8929 initWithTitle:UCLocalize("ENTER_APT_URL")
8932 cancelButtonTitle:UCLocalize("CANCEL")
8934 UCLocalize("ADD_SOURCE"),
8938 [alert setContext:@"source"];
8940 [alert setNumberOfRows:1];
8941 [alert addTextFieldWithValue:@"http://" label:@""];
8943 UITextInputTraits *traits = [[alert textField] textInputTraits];
8944 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8945 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8946 [traits setKeyboardType:UIKeyboardTypeURL];
8947 // XXX: UIReturnKeyDone
8948 [traits setReturnKeyType:UIReturnKeyNext];
8953 - (void) addButtonClicked {
8954 [self showAddSourcePrompt];
8957 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8958 BOOL editing([list_ isEditing]);
8960 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8961 initWithTitle:UCLocalize("ADD")
8962 style:UIBarButtonItemStylePlain
8964 action:@selector(addButtonClicked)
8965 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8967 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8968 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8969 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8971 action:@selector(editButtonClicked)
8972 ] autorelease] animated:animated];
8974 if (IsWildcat_ && !editing)
8975 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8976 initWithTitle:UCLocalize("SETTINGS")
8977 style:UIBarButtonItemStylePlain
8979 action:@selector(settingsButtonClicked)
8983 - (void) settingsButtonClicked {
8984 [delegate_ showSettings];
8987 - (void) editButtonClicked {
8988 [list_ setEditing:![list_ isEditing] animated:YES];
8989 [self updateButtonsForEditingStatusAnimated:YES];
8995 /* Settings Controller {{{ */
8996 @interface SettingsController : CyteViewController <
8997 UITableViewDataSource,
9000 _transient Database *database_;
9001 // XXX: ok, "roledelegate_"?...
9002 _transient id roledelegate_;
9003 _H<UITableView, 2> table_;
9004 _H<UISegmentedControl> segment_;
9005 _H<UIView> container_;
9008 - (void) showDoneButton;
9009 - (void) resizeSegmentedControl;
9013 @implementation SettingsController
9016 table_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
9017 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9018 [table_ setDelegate:self];
9019 [(UITableView *) table_ setDataSource:self];
9020 [self setView:table_];
9022 NSArray *items = [NSArray arrayWithObjects:
9024 UCLocalize("HACKER"),
9025 UCLocalize("DEVELOPER"),
9027 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
9028 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
9029 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
9030 [container_ addSubview:segment_];
9033 - (void) viewDidLoad {
9034 [super viewDidLoad];
9036 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
9039 if ([Role_ isEqualToString:@"User"]) index = 0;
9040 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
9041 if ([Role_ isEqualToString:@"Developer"]) index = 2;
9043 [segment_ setSelectedSegmentIndex:index];
9044 [self showDoneButton];
9047 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
9048 [self resizeSegmentedControl];
9051 - (void) releaseSubviews {
9056 [super releaseSubviews];
9059 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
9060 if ((self = [super init]) != nil) {
9061 database_ = database;
9062 roledelegate_ = delegate;
9066 - (void) resizeSegmentedControl {
9067 CGFloat width = [[self view] frame].size.width;
9068 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
9071 - (void) viewWillAppear:(BOOL)animated {
9072 [super viewWillAppear:animated];
9074 [self resizeSegmentedControl];
9077 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
9078 [self resizeSegmentedControl];
9081 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
9082 [self resizeSegmentedControl];
9086 NSString *role(nil);
9088 switch ([segment_ selectedSegmentIndex]) {
9089 case 0: role = @"User"; break;
9090 case 1: role = @"Hacker"; break;
9091 case 2: role = @"Developer"; break;
9096 if (![role isEqualToString:Role_]) {
9097 bool rolling(Role_ == nil);
9100 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
9104 [Metadata_ setObject:Settings_ forKey:@"Settings"];
9108 [roledelegate_ loadData];
9110 [roledelegate_ updateData];
9114 - (void) segmentChanged:(UISegmentedControl *)control {
9115 [self showDoneButton];
9118 - (void) saveAndClose {
9121 [[self navigationItem] setRightBarButtonItem:nil];
9122 [[self navigationController] dismissModalViewControllerAnimated:YES];
9125 - (void) doneButtonClicked {
9126 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
9127 [spinner startAnimating];
9128 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
9129 [[self navigationItem] setRightBarButtonItem:spinItem];
9131 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
9134 - (void) showDoneButton {
9135 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
9136 initWithTitle:UCLocalize("DONE")
9137 style:UIBarButtonItemStyleDone
9139 action:@selector(doneButtonClicked)
9140 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
9143 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
9144 // XXX: For not having a single cell in the table, this sure is a lot of sections.
9148 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
9152 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
9153 return nil; // This method is required by the protocol.
9156 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
9158 return UCLocalize("ROLE_EX");
9160 return [NSString stringWithFormat:
9161 @"%@: %@\n%@: %@\n%@: %@",
9162 UCLocalize("USER"), UCLocalize("USER_EX"),
9163 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
9164 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
9169 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
9170 return section == 3 ? 44.0f : 0;
9173 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
9174 return section == 3 ? container_ : nil;
9177 - (void) reloadData {
9180 [table_ reloadData];
9185 /* Stash Controller {{{ */
9186 @interface StashController : CyteViewController {
9187 _H<UIActivityIndicatorView> spinner_;
9188 _H<UILabel> status_;
9189 _H<UILabel> caption_;
9194 @implementation StashController
9197 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
9198 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
9199 [self setView:view];
9201 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
9203 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
9204 CGRect spinrect = [spinner_ frame];
9205 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
9206 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
9207 [spinner_ setFrame:spinrect];
9208 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
9209 [view addSubview:spinner_];
9210 [spinner_ startAnimating];
9213 captrect.size.width = [[self view] frame].size.width;
9214 captrect.size.height = 40.0f;
9215 captrect.origin.x = 0;
9216 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
9217 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
9218 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
9219 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9220 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
9221 [caption_ setTextColor:[UIColor whiteColor]];
9222 [caption_ setBackgroundColor:[UIColor clearColor]];
9223 [caption_ setShadowColor:[UIColor blackColor]];
9224 [caption_ setTextAlignment:UITextAlignmentCenter];
9225 [view addSubview:caption_];
9228 statusrect.size.width = [[self view] frame].size.width;
9229 statusrect.size.height = 30.0f;
9230 statusrect.origin.x = 0;
9231 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
9232 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
9233 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9234 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
9235 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
9236 [status_ setTextColor:[UIColor whiteColor]];
9237 [status_ setBackgroundColor:[UIColor clearColor]];
9238 [status_ setShadowColor:[UIColor blackColor]];
9239 [status_ setTextAlignment:UITextAlignmentCenter];
9240 [view addSubview:status_];
9243 - (void) releaseSubviews {
9248 [super releaseSubviews];
9254 @interface CYURLCache : SDURLCache {
9259 @implementation CYURLCache
9261 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
9264 else if ([event isEqualToString:@"no-cache"])
9266 else if ([event isEqualToString:@"store"])
9268 else if ([event isEqualToString:@"invalid"])
9270 else if ([event isEqualToString:@"memory"])
9272 else if ([event isEqualToString:@"disk"])
9274 else if ([event isEqualToString:@"miss"])
9277 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
9281 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
9282 if (NSURLResponse *response = [cached response])
9283 if (NSString *mime = [response MIMEType])
9284 if ([mime isEqualToString:@"text/cache-manifest"]) {
9285 NSURL *url([response URL]);
9288 NSLog(@"###: %@", [url absoluteString]);
9291 @synchronized (HostConfig_) {
9292 [CachedURLs_ addObject:url];
9296 [super storeCachedResponse:cached forRequest:request];
9301 @interface Cydia : UIApplication <
9302 ConfirmationControllerDelegate,
9305 UINavigationControllerDelegate,
9306 UITabBarControllerDelegate
9308 _H<UIWindow> window_;
9309 _H<CYTabBarController> tabbar_;
9310 _H<CydiaLoadingViewController> emulated_;
9312 _H<NSMutableArray> essential_;
9313 _H<NSMutableArray> broken_;
9315 Database *database_;
9317 _H<NSURL> starturl_;
9322 _H<StashController> stash_;
9331 @implementation Cydia
9333 - (void) beginUpdate {
9334 [tabbar_ beginUpdate];
9338 return [tabbar_ updating];
9342 if ([broken_ count] != 0) {
9343 int count = [broken_ count];
9345 UIAlertView *alert = [[[UIAlertView alloc]
9346 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9347 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9349 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
9351 UCLocalize("TEMPORARY_IGNORE"),
9355 [alert setContext:@"fixhalf"];
9356 [alert setNumberOfRows:2];
9358 } else if (!Ignored_ && [essential_ count] != 0) {
9359 int count = [essential_ count];
9361 UIAlertView *alert = [[[UIAlertView alloc]
9362 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9363 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9365 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9367 UCLocalize("UPGRADE_ESSENTIAL"),
9368 UCLocalize("COMPLETE_UPGRADE"),
9372 [alert setContext:@"upgrade"];
9377 - (void) returnToCydia {
9381 - (void) _saveConfig {
9382 @synchronized (database_) {
9389 NSString *error(nil);
9391 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9393 NSError *error(nil);
9394 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9395 NSLog(@"failure to save metadata data: %@", error);
9400 NSLog(@"failure to serialize metadata: %@", error);
9404 CydiaWriteSources();
9407 // Navigation controller for the queuing badge.
9408 - (UINavigationController *) queueNavigationController {
9409 NSArray *controllers = [tabbar_ viewControllers];
9410 return [controllers objectAtIndex:3];
9413 - (void) unloadData {
9414 [tabbar_ unloadData];
9417 - (void) _updateData {
9421 UINavigationController *navigation = [self queueNavigationController];
9423 id queuedelegate = nil;
9424 if ([[navigation viewControllers] count] > 0)
9425 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9427 [queuedelegate queueStatusDidChange];
9428 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9431 - (void) _refreshIfPossible:(NSDate *)update {
9432 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9434 bool recently = false;
9435 if (update != nil) {
9436 NSTimeInterval interval([update timeIntervalSinceNow]);
9437 if (interval <= 0 && interval > -(15*60))
9441 // Don't automatic refresh if:
9442 // - We already refreshed recently.
9443 // - We already auto-refreshed this launch.
9444 // - Auto-refresh is disabled.
9445 if (recently || loaded_ || ManualRefresh) {
9446 // If we are cancelling, we need to make sure it knows it's already loaded.
9449 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9451 // We are going to load, so remember that.
9454 // If we can reach the server, auto-refresh!
9455 if (IsReachable("cydia.saurik.com"))
9456 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9462 - (void) refreshIfPossible {
9463 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9466 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9467 @synchronized (self) {
9468 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9469 [hud setText:UCLocalize("RELOADING_DATA")];
9471 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9475 [essential_ removeAllObjects];
9476 [broken_ removeAllObjects];
9478 NSArray *packages([database_ packages]);
9479 for (Package *package in packages) {
9481 [broken_ addObject:package];
9482 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9483 if ([package essential] && [package installed] != nil)
9484 [essential_ addObject:package];
9489 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9492 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9493 [changesItem setBadgeValue:badge];
9494 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9495 [self setApplicationIconBadgeNumber:changes];
9498 [changesItem setBadgeValue:nil];
9499 [changesItem setAnimatedBadge:NO];
9500 [self setApplicationIconBadgeNumber:0];
9506 [self removeProgressHUD:hud];
9509 - (void) updateData {
9513 - (void) updateDataAndLoad {
9515 if ([database_ progressDelegate] == nil)
9521 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9524 - (void) disemulate {
9525 if (emulated_ == nil)
9528 [window_ addSubview:[tabbar_ view]];
9529 [[emulated_ view] removeFromSuperview];
9531 [window_ setUserInteractionEnabled:YES];
9534 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9535 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9537 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9539 UIViewController *parent;
9540 if (emulated_ == nil)
9549 [parent presentModalViewController:navigation animated:YES];
9552 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9553 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9555 if (navigation != nil)
9556 [navigation pushViewController:progress animated:YES];
9558 [self presentModalViewController:progress force:YES];
9560 [progress invoke:invocation withTitle:title];
9564 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9565 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9568 - (void) repairWithInvocation:(NSInvocation *)invocation {
9570 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9574 - (void) repairWithSelector:(SEL)selector {
9575 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9578 - (void) reloadData {
9579 [self reloadDataWithInvocation:nil];
9580 if ([database_ progressDelegate] == nil)
9586 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9589 - (void) addSource:(NSDictionary *) source {
9590 CydiaAddSource(source);
9593 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9594 CydiaAddSource(href, distribution, sections);
9597 - (void) addTrivialSource:(NSString *)href {
9598 CydiaAddSource(href, @"./");
9601 - (void) updateValues {
9606 pkgProblemResolver *resolver = [database_ resolver];
9608 resolver->InstallProtect();
9609 if (!resolver->Resolve(true))
9614 // XXX: this is a really crappy way of doing this.
9615 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9616 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9617 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9618 if ([tabbar_ updating])
9619 [tabbar_ cancelUpdate];
9621 if (![database_ prepare])
9624 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9625 [page setDelegate:self];
9626 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9629 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9630 [tabbar_ presentModalViewController:confirm_ animated:YES];
9636 @synchronized (self) {
9641 - (void) clearPackage:(Package *)package {
9642 @synchronized (self) {
9649 - (void) installPackages:(NSArray *)packages {
9650 @synchronized (self) {
9651 for (Package *package in packages)
9658 - (void) installPackage:(Package *)package {
9659 @synchronized (self) {
9666 - (void) removePackage:(Package *)package {
9667 @synchronized (self) {
9674 - (void) distUpgrade {
9675 @synchronized (self) {
9676 if (![database_ upgrade])
9684 system("su -c /usr/bin/uicache mobile");
9689 UIProgressHUD *hud([self addProgressHUD]);
9690 [hud setText:UCLocalize("LOADING")];
9691 [self yieldToSelector:@selector(_uicache)];
9692 [self removeProgressHUD:hud];
9696 [database_ perform];
9697 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9698 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9701 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9704 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9708 - (void) showSettings {
9709 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9712 - (void) retainNetworkActivityIndicator {
9713 if (activity_++ == 0)
9714 [self setNetworkActivityIndicatorVisible:YES];
9717 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9721 - (void) releaseNetworkActivityIndicator {
9722 if (--activity_ == 0)
9723 [self setNetworkActivityIndicatorVisible:NO];
9726 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9731 - (void) cancelAndClear:(bool)clear {
9732 @synchronized (self) {
9744 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9745 NSString *context([alert context]);
9747 if ([context isEqualToString:@"conffile"]) {
9748 FILE *input = [database_ input];
9749 if (button == [alert cancelButtonIndex])
9750 fprintf(input, "N\n");
9751 else if (button == [alert firstOtherButtonIndex])
9752 fprintf(input, "Y\n");
9755 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9756 } else if ([context isEqualToString:@"fixhalf"]) {
9757 if (button == [alert cancelButtonIndex]) {
9758 @synchronized (self) {
9759 for (Package *broken in (id) broken_) {
9762 NSString *id = [broken id];
9763 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9764 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9765 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9766 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9772 } else if (button == [alert firstOtherButtonIndex]) {
9773 [broken_ removeAllObjects];
9777 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9778 } else if ([context isEqualToString:@"upgrade"]) {
9779 if (button == [alert firstOtherButtonIndex]) {
9780 @synchronized (self) {
9781 for (Package *essential in (id) essential_)
9782 [essential install];
9787 } else if (button == [alert firstOtherButtonIndex] + 1) {
9789 } else if (button == [alert cancelButtonIndex]) {
9793 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9797 - (void) system:(NSString *)command {
9798 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9801 system([command UTF8String]);
9807 - (void) applicationWillSuspend {
9809 [super applicationWillSuspend];
9812 - (BOOL) isSafeToSuspend {
9815 NSLog(@"isSafeToSuspend: locked_ != 0");
9820 // Use external process status API internally.
9821 // This is probably a really bad idea.
9822 // XXX: what is the point of this? does this solve anything at all?
9823 uint64_t status = 0;
9825 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9826 notify_get_state(notify_token, &status);
9827 notify_cancel(notify_token);
9832 NSLog(@"isSafeToSuspend: status != 0");
9838 NSLog(@"isSafeToSuspend: -> true");
9843 - (void) applicationSuspend:(__GSEvent *)event {
9844 if ([self isSafeToSuspend])
9845 [super applicationSuspend:event];
9848 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9849 if ([self isSafeToSuspend])
9850 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9853 - (void) _setSuspended:(BOOL)value {
9854 if ([self isSafeToSuspend])
9855 [super _setSuspended:value];
9858 - (UIProgressHUD *) addProgressHUD {
9859 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9860 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9862 [window_ setUserInteractionEnabled:NO];
9864 UIViewController *target(tabbar_);
9865 if (UIViewController *modal = [target modalViewController])
9868 [hud showInView:[target view]];
9874 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9877 [hud removeFromSuperview];
9878 [window_ setUserInteractionEnabled:YES];
9881 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9882 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9885 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9886 NSString *scheme([[url scheme] lowercaseString]);
9887 if ([[url absoluteString] length] <= [scheme length] + 3)
9889 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9890 NSArray *components([path componentsSeparatedByString:@"/"]);
9892 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9893 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9894 if (controller != nil)
9895 [controller setDelegate:self];
9899 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9902 NSString *base([components objectAtIndex:0]);
9904 CyteViewController *controller = nil;
9906 if ([base isEqualToString:@"url"]) {
9907 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9908 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9909 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9910 } else if (!external && [components count] == 1) {
9911 if ([base isEqualToString:@"manage"]) {
9912 controller = [[[ManageController alloc] init] autorelease];
9915 if ([base isEqualToString:@"storage"]) {
9916 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9919 if ([base isEqualToString:@"sources"]) {
9920 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9923 if ([base isEqualToString:@"home"]) {
9924 controller = [[[HomeController alloc] init] autorelease];
9927 if ([base isEqualToString:@"sections"]) {
9928 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9931 if ([base isEqualToString:@"search"]) {
9932 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9935 if ([base isEqualToString:@"changes"]) {
9936 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9939 if ([base isEqualToString:@"installed"]) {
9940 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9942 } else if ([components count] == 2) {
9943 NSString *argument = [components objectAtIndex:1];
9945 if ([base isEqualToString:@"package"]) {
9946 controller = [self pageForPackage:argument withReferrer:referrer];
9949 if (!external && [base isEqualToString:@"search"]) {
9950 controller = [[[SearchController alloc] initWithDatabase:database_ query:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9953 if (!external && [base isEqualToString:@"sections"]) {
9954 if ([argument isEqualToString:@"all"])
9956 controller = [[[SectionController alloc] initWithDatabase:database_ section:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9959 if (!external && [base isEqualToString:@"sources"]) {
9960 if ([argument isEqualToString:@"add"]) {
9961 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9962 [(SourcesController *)controller showAddSourcePrompt];
9964 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9965 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9969 if (!external && [base isEqualToString:@"launch"]) {
9970 [self launchApplicationWithIdentifier:argument suspended:NO];
9973 } else if (!external && [components count] == 3) {
9974 NSString *arg1 = [components objectAtIndex:1];
9975 NSString *arg2 = [components objectAtIndex:2];
9977 if ([base isEqualToString:@"package"]) {
9978 if ([arg2 isEqualToString:@"settings"]) {
9979 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9980 } else if ([arg2 isEqualToString:@"files"]) {
9981 if (Package *package = [database_ packageWithName:arg1]) {
9982 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9983 [(FileTable *)controller setPackage:package];
9989 [controller setDelegate:self];
9993 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9994 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9997 [tabbar_ setUnselectedViewController:page];
10002 - (void) applicationOpenURL:(NSURL *)url {
10003 [super applicationOpenURL:url];
10008 [self openCydiaURL:url forExternal:YES];
10011 - (void) applicationWillResignActive:(UIApplication *)application {
10012 // Stop refreshing if you get a phone call or lock the device.
10013 if ([tabbar_ updating])
10014 [tabbar_ cancelUpdate];
10016 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
10017 [super applicationWillResignActive:application];
10020 - (void) saveState {
10021 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
10022 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
10023 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
10026 [self _saveConfig];
10029 - (void) applicationWillTerminate:(UIApplication *)application {
10033 - (void) setConfigurationData:(NSString *)data {
10034 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
10036 if (!conffile_r(data)) {
10037 lprintf("E:invalid conffile\n");
10041 NSString *ofile = conffile_r[1];
10042 //NSString *nfile = conffile_r[2];
10044 UIAlertView *alert = [[[UIAlertView alloc]
10045 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
10046 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
10048 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
10050 UCLocalize("ACCEPT_NEW_COPY"),
10051 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
10055 [alert setContext:@"conffile"];
10056 [alert setNumberOfRows:2];
10060 - (void) addStashController {
10062 stash_ = [[[StashController alloc] init] autorelease];
10063 [window_ addSubview:[stash_ view]];
10066 - (void) removeStashController {
10067 [[stash_ view] removeFromSuperview];
10073 [self setIdleTimerDisabled:YES];
10075 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
10076 UpdateExternalStatus(1);
10077 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
10078 UpdateExternalStatus(0);
10080 [self removeStashController];
10082 pid_t pid(ExecFork());
10084 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
10085 perror("launchctl stop");
10092 - (void) setupViewControllers {
10093 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
10095 NSMutableArray *items([NSMutableArray arrayWithObjects:
10096 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
10097 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
10098 [[[UITabBarItem alloc] initWithTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES")) image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
10099 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
10103 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
10104 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10106 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10109 NSMutableArray *controllers([NSMutableArray array]);
10110 for (UITabBarItem *item in items) {
10111 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
10112 [controller setTabBarItem:item];
10113 [controllers addObject:controller];
10115 [tabbar_ setViewControllers:controllers];
10117 [tabbar_ setUpdateDelegate:self];
10120 - (void) _sendMemoryWarningNotification {
10121 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
10122 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
10124 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
10127 - (void) _sendMemoryWarningNotifications {
10129 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
10135 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
10137 [[NSURLCache sharedURLCache] removeAllCachedResponses];
10140 - (void) applicationDidFinishLaunching:(id)unused {
10141 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
10144 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
10145 [self setApplicationSupportsShakeToEdit:NO];
10147 @synchronized (HostConfig_) {
10148 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
10151 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
10152 initWithMemoryCapacity:524288
10153 diskCapacity:10485760
10154 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
10157 [CydiaWebViewController _initialize];
10159 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
10161 // this would disallow http{,s} URLs from accessing this data
10162 //[WebView registerURLSchemeAsLocal:@"cydia"];
10164 Font12_ = [UIFont systemFontOfSize:12];
10165 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
10166 Font14_ = [UIFont systemFontOfSize:14];
10167 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
10168 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
10170 essential_ = [NSMutableArray arrayWithCapacity:4];
10171 broken_ = [NSMutableArray arrayWithCapacity:4];
10173 // XXX: I really need this thing... like, seriously... I'm sorry
10174 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
10176 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
10177 [window_ orderFront:self];
10178 [window_ makeKey:self];
10179 [window_ setHidden:NO];
10182 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
10183 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
10184 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
10185 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
10186 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
10187 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
10188 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
10189 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
10190 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
10193 [self addStashController];
10194 // XXX: this would be much cleaner as a yieldToSelector:
10195 // that way the removeStashController could happen right here inline
10196 // we also could no longer require the useless stash_ field anymore
10197 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
10201 database_ = [Database sharedInstance];
10202 [database_ setDelegate:self];
10204 [window_ setUserInteractionEnabled:NO];
10205 [self setupViewControllers];
10207 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
10208 [window_ addSubview:[emulated_ view]];
10210 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
10214 - (NSArray *) defaultStartPages {
10215 NSMutableArray *standard = [NSMutableArray array];
10216 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
10217 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
10218 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
10220 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
10222 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
10223 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
10225 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10229 - (void) loadData {
10231 if (Role_ == nil) {
10232 [window_ setUserInteractionEnabled:YES];
10233 [self showSettings];
10236 if ([emulated_ modalViewController] != nil)
10237 [emulated_ dismissModalViewControllerAnimated:YES];
10238 [window_ setUserInteractionEnabled:NO];
10241 [self reloadDataWithInvocation:nil];
10242 [self refreshIfPossible];
10247 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
10248 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
10249 int standardIndex = 0;
10250 NSArray *standard = [self defaultStartPages];
10257 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
10258 if (valid && closed != nil) {
10259 NSTimeInterval interval([closed timeIntervalSinceNow]);
10260 // XXX: Is 30 minutes the optimal time here?
10261 if (interval <= -(30*60))
10265 if (valid && [saved count] != [standard count])
10269 for (unsigned int i = 0; i < [standard count]; i++) {
10270 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10271 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10272 // but it's good enough for now.
10273 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10280 NSArray *items = nil;
10282 [tabbar_ setSelectedIndex:savedIndex];
10285 [tabbar_ setSelectedIndex:standardIndex];
10289 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10290 NSArray *stack = [items objectAtIndex:tab];
10291 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10292 NSMutableArray *current = [NSMutableArray array];
10294 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10295 NSString *addr = [stack objectAtIndex:nav];
10296 NSURL *url = [NSURL URLWithString:addr];
10297 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10299 [current addObject:page];
10302 [navigation setViewControllers:current];
10305 // (Try to) show the startup URL.
10306 if (starturl_ != nil) {
10307 [self openCydiaURL:starturl_ forExternal:NO];
10312 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10313 if (item != nil && IsWildcat_) {
10314 [sheet showFromBarButtonItem:item animated:YES];
10316 [sheet showInView:window_];
10320 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10321 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10322 [progress setTitle:task];
10323 [progress addProgressEvent:event];
10326 - (void) addProgressEventForTask:(NSArray *)data {
10327 CydiaProgressEvent *event([data objectAtIndex:0]);
10328 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10329 [self addProgressEvent:event forTask:task];
10332 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10333 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10339 id Alloc_(id self, SEL selector) {
10340 id object = alloc_(self, selector);
10341 lprintf("[%s]A-%p\n", self->isa->name, object);
10346 id Dealloc_(id self, SEL selector) {
10347 id object = dealloc_(self, selector);
10348 lprintf("[%s]D-%p\n", self->isa->name, object);
10352 Class $WebDefaultUIKitDelegate;
10354 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
10355 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
10356 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
10357 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
10360 static NSSet *MobilizedFiles_;
10362 static NSURL *MobilizeURL(NSURL *url) {
10363 NSString *path([url path]);
10364 if ([path hasPrefix:@"/var/root/"]) {
10365 NSString *file([path substringFromIndex:10]);
10366 if ([MobilizedFiles_ containsObject:file])
10367 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10373 Class $CFXPreferencesPropertyListSource;
10374 @class CFXPreferencesPropertyListSource;
10376 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10377 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10378 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10379 url = MobilizeURL(url);
10380 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10381 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10387 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10388 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10389 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10390 url = MobilizeURL(url);
10391 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10392 //NSLog(@"%@ %@", [url absoluteString], value);
10398 Class $NSURLConnection;
10400 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10401 NSMutableURLRequest *copy([request mutableCopy]);
10403 NSURL *url([copy URL]);
10405 NSString *host([url host]);
10406 NSString *scheme([[url scheme] lowercaseString]);
10408 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10410 @synchronized (HostConfig_) {
10411 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10412 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10413 [copy setHTTPShouldUsePipelining:YES];
10415 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10416 if ([control isEqualToString:@"max-age=0"])
10417 if ([CachedURLs_ containsObject:url]) {
10419 NSLog(@"~~~: %@", url);
10422 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10424 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10425 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10426 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10430 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10436 static CGSize $WAKWindow$screenSize(WAKWindow self, SEL _cmd) {
10437 CGSize size([[UIScreen mainScreen] bounds].size);
10438 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10439 if ([$WAKWindow hasLandscapeOrientation])
10440 std::swap(size.width, size.height);*/
10444 int main(int argc, char *argv[]) {
10445 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10449 UpdateExternalStatus(0);
10451 if (Class $UIDevice = objc_getClass("UIDevice")) {
10452 UIDevice *device([$UIDevice currentDevice]);
10453 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10455 IsWildcat_ = false;
10457 UIScreen *screen([UIScreen mainScreen]);
10458 if ([screen respondsToSelector:@selector(scale)])
10459 ScreenScale_ = [screen scale];
10463 UIDevice *device([UIDevice currentDevice]);
10464 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10465 Idiom_ = @"iphone";
10467 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10468 if (idiom == UIUserInterfaceIdiomPhone)
10469 Idiom_ = @"iphone";
10470 else if (idiom == UIUserInterfaceIdiomPad)
10473 NSLog(@"unknown UIUserInterfaceIdiom!");
10476 Pcre pattern("^([0-9]+\\.[0-9]+)");
10478 if (pattern([device systemVersion]))
10479 Firmware_ = pattern[1];
10480 if (pattern(Cydia_))
10481 Major_ = pattern[1];
10483 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10485 HostConfig_ = [[[NSObject alloc] init] autorelease];
10486 @synchronized (HostConfig_) {
10487 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10488 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10489 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10490 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10491 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10494 NSString *ui(@"ui/ios");
10496 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10497 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10498 UI_ = CydiaURL(ui);
10500 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10502 MobilizedFiles_ = [NSMutableSet setWithObjects:
10503 @"Library/Preferences/com.apple.Accessibility.plist",
10504 @"Library/Preferences/com.apple.preferences.sounds.plist",
10507 /* Library Hacks {{{ */
10508 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10510 $WAKWindow = objc_getClass("WAKWindow");
10511 if ($WAKWindow != NULL)
10512 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10513 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10515 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10517 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10518 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10519 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10520 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10523 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10524 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10525 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10526 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10529 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10530 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10531 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10532 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10533 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10536 $NSURLConnection = objc_getClass("NSURLConnection");
10537 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10538 if (NSURLConnection$init$ != NULL) {
10539 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10540 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10543 /* Set Locale {{{ */
10544 Locale_ = CFLocaleCopyCurrent();
10545 Languages_ = [NSLocale preferredLanguages];
10547 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10548 //NSLog(@"%@", [Languages_ description]);
10551 if (Locale_ != NULL)
10552 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10553 else if (Languages_ != nil && [Languages_ count] != 0)
10554 lang = [[Languages_ objectAtIndex:0] UTF8String];
10556 // XXX: consider just setting to C and then falling through?
10559 if (lang != NULL) {
10560 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10561 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10564 NSLog(@"Setting Language: %s", lang);
10566 if (lang != NULL) {
10567 setenv("LANG", lang, true);
10568 std::setlocale(LC_ALL, lang);
10572 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10574 /* Parse Arguments {{{ */
10575 bool substrate(false);
10581 for (int argi(1); argi != argc; ++argi)
10582 if (strcmp(argv[argi], "--") == 0) {
10584 argv[argi] = argv[0];
10590 for (int argi(1); argi != arge; ++argi)
10591 if (strcmp(args[argi], "--substrate") == 0)
10594 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10598 App_ = [[NSBundle mainBundle] bundlePath];
10604 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10605 alloc_ = alloc->method_imp;
10606 alloc->method_imp = (IMP) &Alloc_;*/
10608 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10609 dealloc_ = dealloc->method_imp;
10610 dealloc->method_imp = (IMP) &Dealloc_;*/
10612 /* System Information {{{ */
10616 size = sizeof(maxproc);
10617 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10618 perror("sysctlbyname(\"kern.maxproc\", ?)");
10619 else if (maxproc < 64) {
10621 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10622 perror("sysctlbyname(\"kern.maxproc\", #)");
10625 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10626 char *osversion = new char[size];
10627 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10628 perror("sysctlbyname(\"kern.osversion\", ?)");
10630 System_ = [NSString stringWithUTF8String:osversion];
10632 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10633 char *machine = new char[size];
10634 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10635 perror("sysctlbyname(\"hw.machine\", ?)");
10637 Machine_ = machine;
10639 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10640 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10641 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10643 UniqueID_ = [device uniqueIdentifier];
10645 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10646 Product_ = [info objectForKey:@"SafariProductVersion"];
10647 Safari_ = [info objectForKey:@"CFBundleVersion"];
10650 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10652 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10653 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10654 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10655 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10656 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10657 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10659 UserAgent_ = agent;
10661 /* Load Database {{{ */
10663 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10665 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10667 if (Metadata_ == NULL)
10668 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10670 Settings_ = [Metadata_ objectForKey:@"Settings"];
10672 Packages_ = [Metadata_ objectForKey:@"Packages"];
10674 Values_ = [Metadata_ objectForKey:@"Values"];
10675 Sections_ = [Metadata_ objectForKey:@"Sections"];
10676 Sources_ = [Metadata_ objectForKey:@"Sources"];
10678 Token_ = [Metadata_ objectForKey:@"Token"];
10680 Version_ = [Metadata_ objectForKey:@"Version"];
10683 if (Settings_ != nil)
10684 Role_ = [Settings_ objectForKey:@"Role"];
10686 if (Values_ == nil) {
10687 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10688 [Metadata_ setObject:Values_ forKey:@"Values"];
10691 if (Sections_ == nil) {
10692 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10693 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10696 if (Sources_ == nil) {
10697 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10698 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10701 if (Version_ == nil) {
10702 Version_ = [NSNumber numberWithUnsignedInt:0];
10703 [Metadata_ setObject:Version_ forKey:@"Version"];
10706 if ([Version_ unsignedIntValue] == 0) {
10707 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10708 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10709 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10710 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10712 Version_ = [NSNumber numberWithUnsignedInt:1];
10713 [Metadata_ setObject:Version_ forKey:@"Version"];
10715 [Metadata_ removeObjectForKey:@"LastUpdate"];
10721 CydiaWriteSources();
10724 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10727 if (Packages_ != nil) {
10729 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10733 [Metadata_ removeObjectForKey:@"Packages"];
10739 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10741 #define MobileSubstrate_(name) \
10742 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10743 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10744 if (handle == NULL) \
10745 NSLog(@"%s", dlerror()); \
10748 MobileSubstrate_(Activator)
10749 MobileSubstrate_(libstatusbar)
10750 MobileSubstrate_(SimulatedKeyEvents)
10751 MobileSubstrate_(WinterBoard)
10753 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10754 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10756 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10758 if (access("/User", F_OK) != 0 || version != 5) {
10760 system("/usr/libexec/cydia/firmware.sh");
10764 _assert([[NSFileManager defaultManager]
10765 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10766 withIntermediateDirectories:YES
10771 if (access("/tmp/cydia.chk", F_OK) == 0) {
10772 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10773 _assert(errno == ENOENT);
10774 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10775 _assert(errno == ENOENT);
10778 /* APT Initialization {{{ */
10779 _assert(pkgInitConfig(*_config));
10780 _assert(pkgInitSystem(*_config, _system));
10783 _config->Set("APT::Acquire::Translation", lang);
10785 // XXX: this timeout might be important :(
10786 //_config->Set("Acquire::http::Timeout", 15);
10788 _config->Set("Acquire::http::MaxParallel", 3);
10790 /* Color Choices {{{ */
10791 space_ = CGColorSpaceCreateDeviceRGB();
10793 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10794 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10795 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10796 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10797 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10798 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10799 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10800 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10801 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10803 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10804 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10806 /* UIKit Configuration {{{ */
10807 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10808 if ($GSFontSetUseLegacyFontMetrics != NULL)
10809 $GSFontSetUseLegacyFontMetrics(YES);
10811 // XXX: I have a feeling this was important
10812 //UIKeyboardDisableAutomaticAppearance();
10815 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemHasCapability"));
10816 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10818 ShowPromoted_ = fast;
10819 PulseInterval_ = fast ? 50000 : 500000;
10821 Colon_ = UCLocalize("COLON_DELIMITED");
10822 Elision_ = UCLocalize("ELISION");
10823 Error_ = UCLocalize("ERROR");
10824 Warning_ = UCLocalize("WARNING");
10827 AprilFools_ = true;
10829 CFGregorianDate date(CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem()));
10830 AprilFools_ = date.month == 4 && date.day == 1;
10834 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10836 CGColorSpaceRelease(space_);
10837 CFRelease(Locale_);