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)
5337 system("su -c /usr/bin/uicache mobile");
5341 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5342 UpdateExternalStatus(1);
5344 [progress_ setRunning:true];
5345 [self setTitle:title];
5346 // implicit updateProgress
5348 SHA1SumValue notifyconf; {
5350 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5353 MMap mmap(file, MMap::ReadOnly);
5355 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5356 notifyconf = sha1.Result();
5360 SHA1SumValue springlist; {
5362 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5365 MMap mmap(file, MMap::ReadOnly);
5367 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5368 springlist = sha1.Result();
5372 if (invocation != nil) {
5373 [invocation yieldToSelector:@selector(invoke)];
5374 [self setTitle:@"COMPLETE"];
5379 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5382 MMap mmap(file, MMap::ReadOnly);
5384 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5385 if (!(notifyconf == sha1.Result()))
5392 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5395 MMap mmap(file, MMap::ReadOnly);
5397 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5398 if (!(springlist == sha1.Result()))
5404 if (RestartSubstrate_)
5408 RestartSubstrate_ = false;
5411 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5412 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5413 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5414 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5415 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5418 UIProgressHUD *hud([delegate_ addProgressHUD]);
5419 [hud setText:UCLocalize("LOADING")];
5420 [self yieldToSelector:@selector(uicache)];
5421 [delegate_ removeProgressHUD:hud];
5423 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5425 [progress_ setRunning:false];
5426 [self updateProgress];
5428 [self applyRightButton];
5431 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5432 [progress_ addEvent:event];
5433 [self updateProgress];
5436 - (bool) isProgressCancelled {
5437 return cancel_ == 2;
5442 [self updateCancel];
5445 - (void) setCancellable:(bool)cancellable {
5446 unsigned cancel(cancel_);
5450 else if (cancel_ == 0)
5453 if (cancel != cancel_)
5454 [self updateCancel];
5457 - (void) setProgressCancellable:(NSNumber *)cancellable {
5458 [self setCancellable:[cancellable boolValue]];
5461 - (void) setProgressPercent:(NSNumber *)percent {
5462 [progress_ setPercent:[percent floatValue]];
5463 [self updateProgress];
5466 - (void) setProgressStatus:(NSDictionary *)status {
5467 if (status == nil) {
5468 [progress_ setCurrent:0];
5469 [progress_ setTotal:0];
5470 [progress_ setSpeed:0];
5472 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5474 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5475 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5476 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5479 [self updateProgress];
5485 /* Package Cell {{{ */
5486 @interface PackageCell : CyteTableViewCell <
5487 CyteTableViewCellDelegate
5491 _H<NSString> description_;
5493 _H<NSString> source_;
5495 _H<UIImage> placard_;
5499 - (PackageCell *) init;
5500 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5502 - (void) drawContentRect:(CGRect)rect;
5506 @implementation PackageCell
5508 - (PackageCell *) init {
5509 CGRect frame(CGRectMake(0, 0, 320, 74));
5510 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5511 UIView *content([self contentView]);
5512 CGRect bounds([content bounds]);
5514 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5515 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5516 [content addSubview:content_];
5518 [content_ setDelegate:self];
5519 [content_ setOpaque:YES];
5523 - (NSString *) accessibilityLabel {
5524 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5527 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5528 summarized_ = summary;
5538 [content_ setBackgroundColor:[UIColor whiteColor]];
5542 Source *source = [package source];
5544 icon_ = [package icon];
5546 if (NSString *name = [package name])
5547 name_ = [NSString stringWithString:name];
5549 NSString *description(nil);
5551 if (description == nil && IsWildcat_)
5552 description = [package longDescription];
5553 if (description == nil)
5554 description = [package shortDescription];
5556 if (description != nil)
5557 description_ = [NSString stringWithString:description];
5559 commercial_ = [package isCommercial];
5561 NSString *label = nil;
5562 bool trusted = false;
5564 if (source != nil) {
5565 label = [source label];
5566 trusted = [source trusted];
5567 } else if ([[package id] isEqualToString:@"firmware"])
5568 label = UCLocalize("APPLE");
5570 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5572 NSString *from(label);
5574 NSString *section = [package simpleSection];
5575 if (section != nil && ![section isEqualToString:label]) {
5576 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5577 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5580 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5582 if (NSString *purpose = [package primaryPurpose])
5583 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5588 if (NSString *mode = [package mode]) {
5589 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5590 color = RemovingColor_;
5591 //placard = @"removing";
5593 color = InstallingColor_;
5594 //placard = @"installing";
5597 // XXX: the removing/installing placards are not @2x
5600 color = [UIColor whiteColor];
5602 if ([package installed] != nil)
5603 placard = @"installed";
5608 [content_ setBackgroundColor:color];
5611 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5614 [self setNeedsDisplay];
5615 [content_ setNeedsDisplay];
5618 - (void) drawSummaryContentRect:(CGRect)rect {
5619 bool highlighted(highlighted_);
5620 float width([self bounds].size.width);
5624 rect.size = [(UIImage *) icon_ size];
5626 while (rect.size.width > 16 || rect.size.height > 16) {
5627 rect.size.width /= 2;
5628 rect.size.height /= 2;
5631 rect.origin.x = 18 - rect.size.width / 2;
5632 rect.origin.y = 18 - rect.size.height / 2;
5634 [icon_ drawInRect:rect];
5637 if (badge_ != nil) {
5639 rect.size = [(UIImage *) badge_ size];
5641 rect.size.width /= 4;
5642 rect.size.height /= 4;
5644 rect.origin.x = 23 - rect.size.width / 2;
5645 rect.origin.y = 23 - rect.size.height / 2;
5647 [badge_ drawInRect:rect];
5654 UISetColor(commercial_ ? Purple_ : Black_);
5655 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5657 if (placard_ != nil)
5658 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5661 - (void) drawNormalContentRect:(CGRect)rect {
5662 bool highlighted(highlighted_);
5663 float width([self bounds].size.width);
5667 rect.size = [(UIImage *) icon_ size];
5669 while (rect.size.width > 32 || rect.size.height > 32) {
5670 rect.size.width /= 2;
5671 rect.size.height /= 2;
5674 rect.origin.x = 25 - rect.size.width / 2;
5675 rect.origin.y = 25 - rect.size.height / 2;
5677 [icon_ drawInRect:rect];
5680 if (badge_ != nil) {
5682 rect.size = [(UIImage *) badge_ size];
5684 rect.size.width /= 2;
5685 rect.size.height /= 2;
5687 rect.origin.x = 36 - rect.size.width / 2;
5688 rect.origin.y = 36 - rect.size.height / 2;
5690 [badge_ drawInRect:rect];
5697 UISetColor(commercial_ ? Purple_ : Black_);
5698 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5699 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5702 UISetColor(commercial_ ? Purplish_ : Gray_);
5703 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5705 if (placard_ != nil)
5706 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5709 - (void) drawContentRect:(CGRect)rect {
5711 [self drawSummaryContentRect:rect];
5713 [self drawNormalContentRect:rect];
5718 /* Section Cell {{{ */
5719 @interface SectionCell : CyteTableViewCell <
5720 CyteTableViewCellDelegate
5722 _H<NSString> basic_;
5723 _H<NSString> section_;
5725 _H<NSString> count_;
5727 _H<UISwitch> switch_;
5731 - (void) setSection:(Section *)section editing:(BOOL)editing;
5735 @implementation SectionCell
5737 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5738 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5739 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5740 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5741 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5743 UIView *content([self contentView]);
5744 CGRect bounds([content bounds]);
5746 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5747 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5748 [content addSubview:content_];
5749 [content_ setBackgroundColor:[UIColor whiteColor]];
5751 [content_ setDelegate:self];
5755 - (void) onSwitch:(id)sender {
5756 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5757 if (metadata == nil) {
5758 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5759 [Sections_ setObject:metadata forKey:basic_];
5762 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5766 - (void) setSection:(Section *)section editing:(BOOL)editing {
5767 if (editing != editing_) {
5769 [switch_ removeFromSuperview];
5771 [self addSubview:switch_];
5780 if (section == nil) {
5781 name_ = UCLocalize("ALL_PACKAGES");
5784 basic_ = [section name];
5785 section_ = [section localized];
5787 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5788 count_ = [NSString stringWithFormat:@"%d", [section count]];
5791 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5794 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5795 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5797 [content_ setNeedsDisplay];
5800 - (void) setFrame:(CGRect)frame {
5801 [super setFrame:frame];
5803 CGRect rect([switch_ frame]);
5804 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5807 - (NSString *) accessibilityLabel {
5811 - (void) drawContentRect:(CGRect)rect {
5812 bool highlighted(highlighted_ && !editing_);
5814 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5819 float width(rect.size.width);
5825 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5827 CGSize size = [count_ sizeWithFont:Font14_];
5831 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5837 /* File Table {{{ */
5838 @interface FileTable : CyteViewController <
5839 UITableViewDataSource,
5842 _transient Database *database_;
5843 _H<Package> package_;
5845 _H<NSMutableArray> files_;
5846 _H<UITableView, 2> list_;
5849 - (id) initWithDatabase:(Database *)database;
5850 - (void) setPackage:(Package *)package;
5854 @implementation FileTable
5856 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5857 return files_ == nil ? 0 : [files_ count];
5860 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5864 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5865 static NSString *reuseIdentifier = @"Cell";
5867 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5869 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5870 [cell setFont:[UIFont systemFontOfSize:16]];
5872 [cell setText:[files_ objectAtIndex:indexPath.row]];
5873 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5878 - (NSURL *) navigationURL {
5879 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5883 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5884 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5885 [list_ setRowHeight:24.0f];
5886 [(UITableView *) list_ setDataSource:self];
5887 [list_ setDelegate:self];
5888 [self setView:list_];
5891 - (void) viewDidLoad {
5892 [super viewDidLoad];
5894 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5897 - (void) releaseSubviews {
5903 [super releaseSubviews];
5906 - (id) initWithDatabase:(Database *)database {
5907 if ((self = [super init]) != nil) {
5908 database_ = database;
5912 - (void) setPackage:(Package *)package {
5916 files_ = [NSMutableArray arrayWithCapacity:32];
5918 if (package != nil) {
5920 name_ = [package id];
5922 if (NSArray *files = [package files])
5923 [files_ addObjectsFromArray:files];
5925 if ([files_ count] != 0) {
5926 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5927 [files_ removeObjectAtIndex:0];
5928 [files_ sortUsingSelector:@selector(compareByPath:)];
5930 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5931 [stack addObject:@"/"];
5933 for (int i(0), e([files_ count]); i != e; ++i) {
5934 NSString *file = [files_ objectAtIndex:i];
5935 while (![file hasPrefix:[stack lastObject]])
5936 [stack removeLastObject];
5937 NSString *directory = [stack lastObject];
5938 [stack addObject:[file stringByAppendingString:@"/"]];
5939 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5940 ([stack count] - 2) * 3, "",
5941 [file substringFromIndex:[directory length]]
5950 - (void) reloadData {
5953 [self setPackage:[database_ packageWithName:name_]];
5958 /* Package Controller {{{ */
5959 @interface CYPackageController : CydiaWebViewController <
5960 UIActionSheetDelegate
5962 _transient Database *database_;
5963 _H<Package> package_;
5966 _H<NSMutableArray> buttons_;
5967 _H<UIBarButtonItem> button_;
5970 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
5974 @implementation CYPackageController
5976 - (NSURL *) navigationURL {
5977 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5980 /* XXX: this is not safe at all... localization of /fail/ */
5981 - (void) _clickButtonWithName:(NSString *)name {
5982 if ([name isEqualToString:UCLocalize("CLEAR")])
5983 [delegate_ clearPackage:package_];
5984 else if ([name isEqualToString:UCLocalize("INSTALL")])
5985 [delegate_ installPackage:package_];
5986 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5987 [delegate_ installPackage:package_];
5988 else if ([name isEqualToString:UCLocalize("REMOVE")])
5989 [delegate_ removePackage:package_];
5990 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5991 [delegate_ installPackage:package_];
5992 else _assert(false);
5995 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5996 NSString *context([sheet context]);
5998 if ([context isEqualToString:@"modify"]) {
5999 if (button != [sheet cancelButtonIndex]) {
6000 NSString *buttonName = [buttons_ objectAtIndex:button];
6001 [self _clickButtonWithName:buttonName];
6004 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6008 - (bool) _allowJavaScriptPanel {
6013 - (void) _customButtonClicked {
6014 int count([buttons_ count]);
6019 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6021 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6022 [buttons addObjectsFromArray:buttons_];
6024 UIActionSheet *sheet = [[[UIActionSheet alloc]
6027 cancelButtonTitle:nil
6028 destructiveButtonTitle:nil
6029 otherButtonTitles:nil
6032 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6034 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6035 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6037 [sheet setContext:@"modify"];
6039 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6043 // We don't want to allow non-commercial packages to do custom things to the install button,
6044 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6045 - (void) customButtonClicked {
6047 [super customButtonClicked];
6049 [self _customButtonClicked];
6052 - (void) reloadButtonClicked {
6053 // Don't reload a commerical package by tapping the loading button,
6054 // but if it's not an Install button, we should forward it on.
6055 if (![package_ uninstalled])
6056 [self _customButtonClicked];
6059 - (void) applyLoadingTitle {
6060 // Don't show "Loading" as the title. Ever.
6063 - (UIBarButtonItem *) rightButton {
6068 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6069 if ((self = [super init]) != nil) {
6070 database_ = database;
6071 buttons_ = [NSMutableArray arrayWithCapacity:4];
6072 name_ = name == nil ? @"" : [NSString stringWithString:name];
6073 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6077 - (void) reloadData {
6080 package_ = [database_ packageWithName:name_];
6082 [buttons_ removeAllObjects];
6084 if (package_ != nil) {
6085 [(Package *) package_ parse];
6087 commercial_ = [package_ isCommercial];
6089 if ([package_ mode] != nil)
6090 [buttons_ addObject:UCLocalize("CLEAR")];
6091 if ([package_ source] == nil);
6092 else if ([package_ upgradableAndEssential:NO])
6093 [buttons_ addObject:UCLocalize("UPGRADE")];
6094 else if ([package_ uninstalled])
6095 [buttons_ addObject:UCLocalize("INSTALL")];
6097 [buttons_ addObject:UCLocalize("REINSTALL")];
6098 if (![package_ uninstalled])
6099 [buttons_ addObject:UCLocalize("REMOVE")];
6103 switch ([buttons_ count]) {
6104 case 0: title = nil; break;
6105 case 1: title = [buttons_ objectAtIndex:0]; break;
6106 default: title = UCLocalize("MODIFY"); break;
6109 button_ = [[[UIBarButtonItem alloc]
6111 style:UIBarButtonItemStylePlain
6113 action:@selector(customButtonClicked)
6117 - (bool) isLoading {
6118 return commercial_ ? [super isLoading] : false;
6124 /* Package List Controller {{{ */
6125 @interface PackageListController : CyteViewController <
6126 UITableViewDataSource,
6129 _transient Database *database_;
6131 _H<NSArray> packages_;
6132 _H<NSMutableArray> sections_;
6133 _H<UITableView, 2> list_;
6134 _H<NSMutableArray> index_;
6135 _H<NSMutableDictionary> indices_;
6136 _H<NSString> title_;
6137 unsigned reloading_;
6140 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6141 - (void) setDelegate:(id)delegate;
6142 - (void) resetCursor;
6147 @implementation PackageListController
6149 - (NSURL *) referrerURL {
6150 return [self navigationURL];
6153 - (bool) isSummarized {
6157 - (bool) showsSections {
6161 - (void) deselectWithAnimation:(BOOL)animated {
6162 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6165 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6166 CGRect base = [[self view] bounds];
6167 base.size.height -= bounds.size.height;
6168 base.origin = [list_ frame].origin;
6170 [UIView beginAnimations:nil context:NULL];
6171 [UIView setAnimationBeginsFromCurrentState:YES];
6172 [UIView setAnimationCurve:curve];
6173 [UIView setAnimationDuration:duration];
6174 [list_ setFrame:base];
6175 [UIView commitAnimations];
6178 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6179 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6182 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6183 [self resizeForKeyboardBounds:bounds duration:0];
6186 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6187 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6188 *curve = UIViewAnimationCurveEaseInOut;
6190 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6192 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6195 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6198 - (void) keyboardWillShow:(NSNotification *)notification {
6201 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6202 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6204 NSTimeInterval duration;
6205 UIViewAnimationCurve curve;
6206 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6208 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);
6209 UIViewController *base = self;
6210 while ([base parentViewController] != nil)
6211 base = [base parentViewController];
6212 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6213 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6215 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6216 intersection.size.height += CYStatusBarHeight();
6218 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6221 - (void) keyboardWillHide:(NSNotification *)notification {
6222 NSTimeInterval duration;
6223 UIViewAnimationCurve curve;
6224 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6226 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6229 - (void) viewWillAppear:(BOOL)animated {
6230 [super viewWillAppear:animated];
6232 [self resizeForKeyboardBounds:CGRectZero];
6233 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6234 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6237 - (void) viewWillDisappear:(BOOL)animated {
6238 [super viewWillDisappear:animated];
6240 [self resizeForKeyboardBounds:CGRectZero];
6241 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6242 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6245 - (void) viewDidAppear:(BOOL)animated {
6246 [super viewDidAppear:animated];
6247 [self deselectWithAnimation:animated];
6250 - (void) didSelectPackage:(Package *)package {
6251 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6252 [view setDelegate:delegate_];
6253 [[self navigationController] pushViewController:view animated:YES];
6256 #if TryIndexedCollation
6257 + (BOOL) hasIndexedCollation {
6258 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6262 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6263 NSInteger count([sections_ count]);
6264 return count == 0 ? 1 : count;
6267 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6268 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6270 return [[sections_ objectAtIndex:section] name];
6273 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6274 if ([sections_ count] == 0)
6276 return [[sections_ objectAtIndex:section] count];
6279 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6280 @synchronized (database_) {
6281 if ([database_ era] != era_)
6284 Section *section([sections_ objectAtIndex:[path section]]);
6285 NSInteger row([path row]);
6286 Package *package([packages_ objectAtIndex:([section row] + row)]);
6287 return [[package retain] autorelease];
6290 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6291 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6293 cell = [[[PackageCell alloc] init] autorelease];
6295 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6296 [cell setPackage:package asSummary:[self isSummarized]];
6300 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6301 Package *package([self packageAtIndexPath:path]);
6302 package = [database_ packageWithName:[package id]];
6303 [self didSelectPackage:package];
6306 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6307 if (![self showsSections])
6313 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6314 #if TryIndexedCollation
6315 if ([[self class] hasIndexedCollation]) {
6316 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6323 - (void) updateHeight {
6324 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6327 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6328 if ((self = [super init]) != nil) {
6329 database_ = database;
6330 title_ = [title copy];
6331 [[self navigationItem] setTitle:title_];
6336 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6337 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6338 [self setView:view];
6340 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6341 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6342 [view addSubview:list_];
6344 // XXX: is 20 the most optimal number here?
6345 [list_ setSectionIndexMinimumDisplayRowCount:20];
6347 [(UITableView *) list_ setDataSource:self];
6348 [list_ setDelegate:self];
6350 [self updateHeight];
6353 - (void) releaseSubviews {
6361 [super releaseSubviews];
6364 - (void) setDelegate:(id)delegate {
6365 delegate_ = delegate;
6368 - (bool) shouldYield {
6372 - (bool) shouldBlock {
6376 - (NSMutableArray *) _reloadPackages {
6377 @synchronized (database_) {
6378 era_ = [database_ era];
6379 NSArray *packages([database_ packages]);
6381 return [NSMutableArray arrayWithArray:packages];
6384 - (void) _reloadData {
6385 if (reloading_ != 0) {
6393 if ([self shouldYield]) {
6397 if (![self shouldBlock])
6400 hud = [delegate_ addProgressHUD];
6401 [hud setText:UCLocalize("LOADING")];
6405 packages = [self yieldToSelector:@selector(_reloadPackages)];
6408 [delegate_ removeProgressHUD:hud];
6409 } while (reloading_ == 2);
6411 packages = [self _reloadPackages];
6414 @synchronized (database_) {
6415 if (era_ != [database_ era])
6419 packages_ = packages;
6421 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6422 sections_ = [NSMutableArray arrayWithCapacity:16];
6424 Section *section = nil;
6426 #if TryIndexedCollation
6427 if ([[self class] hasIndexedCollation]) {
6428 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6430 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6431 NSArray *titles = [collation sectionIndexTitles];
6434 _profile(PackageTable$reloadData$Section)
6435 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6439 _profile(PackageTable$reloadData$Section$Package)
6440 package = [packages_ objectAtIndex:offset];
6441 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6444 while (secidx < index) {
6447 _profile(PackageTable$reloadData$Section$Allocate)
6448 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6451 _profile(PackageTable$reloadData$Section$Add)
6452 [sections_ addObject:section];
6456 [section addToCount];
6462 index_ = [NSMutableArray arrayWithCapacity:32];
6464 bool sectioned([self showsSections]);
6466 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6467 [sections_ addObject:section];
6470 _profile(PackageTable$reloadData$Section)
6471 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6475 _profile(PackageTable$reloadData$Section$Package)
6476 package = [packages_ objectAtIndex:offset];
6477 index = [package index];
6480 if (sectioned && (section == nil || [section index] != index)) {
6481 _profile(PackageTable$reloadData$Section$Allocate)
6482 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6485 [index_ addObject:[section name]];
6486 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6488 _profile(PackageTable$reloadData$Section$Add)
6489 [sections_ addObject:section];
6493 [section addToCount];
6498 [self updateHeight];
6500 _profile(PackageTable$reloadData$List)
6501 [(UITableView *) list_ setDataSource:self];
6506 - (void) reloadData {
6509 if ([self shouldYield])
6510 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6515 - (void) resetCursor {
6516 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6519 - (void) clearData {
6520 [self updateHeight];
6522 [list_ setDataSource:nil];
6530 /* Filtered Package List Controller {{{ */
6531 @interface FilteredPackageListController : PackageListController {
6534 _H<NSObject> object_;
6537 - (void) setObject:(id)object;
6538 - (void) setObject:(id)object forFilter:(SEL)filter;
6541 - (void) setFilter:(SEL)filter;
6543 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6547 @implementation FilteredPackageListController
6553 - (void) setFilter:(SEL)filter {
6554 @synchronized (self) {
6557 /* XXX: this is an unsafe optimization of doomy hell */
6558 Method method(class_getInstanceMethod([Package class], filter));
6559 _assert(method != NULL);
6560 imp_ = method_getImplementation(method);
6561 _assert(imp_ != NULL);
6564 - (void) setObject:(id)object {
6565 @synchronized (self) {
6569 - (void) setObject:(id)object forFilter:(SEL)filter {
6570 @synchronized (self) {
6571 [self setFilter:filter];
6572 [self setObject:object];
6575 - (NSMutableArray *) _reloadPackages {
6576 @synchronized (database_) {
6577 era_ = [database_ era];
6578 NSArray *packages([database_ packages]);
6580 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6584 _H<NSObject> object;
6586 @synchronized (self) {
6592 _profile(PackageTable$reloadData$Filter)
6593 for (Package *package in packages)
6594 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6595 [filtered addObject:package];
6601 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6602 if ((self = [super initWithDatabase:database title:title]) != nil) {
6603 [self setFilter:filter];
6604 [self setObject:object];
6611 /* Home Controller {{{ */
6612 @interface HomeController : CydiaWebViewController {
6613 CFRunLoopRef runloop_;
6614 SCNetworkReachabilityRef reachability_;
6619 @implementation HomeController
6621 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6622 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6626 if ((self = [super init]) != nil) {
6627 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6630 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6631 if (reachability_ != NULL) {
6632 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6633 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6635 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6636 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6643 if (reachability_ != NULL && runloop_ != NULL)
6644 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6648 - (NSURL *) navigationURL {
6649 return [NSURL URLWithString:@"cydia://home"];
6652 - (void) aboutButtonClicked {
6653 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6655 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6656 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6657 [alert setCancelButtonIndex:0];
6660 @"Copyright \u00a9 2008-2011\n"
6663 "Jay Freeman (saurik)\n"
6664 "saurik@saurik.com\n"
6665 "http://www.saurik.com/"
6671 - (UIBarButtonItem *) leftButton {
6672 return [[[UIBarButtonItem alloc]
6673 initWithTitle:UCLocalize("ABOUT")
6674 style:UIBarButtonItemStylePlain
6676 action:@selector(aboutButtonClicked)
6682 /* Manage Controller {{{ */
6683 @interface ManageController : CydiaWebViewController {
6686 - (void) queueStatusDidChange;
6690 @implementation ManageController
6693 if ((self = [super init]) != nil) {
6694 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6698 - (NSURL *) navigationURL {
6699 return [NSURL URLWithString:@"cydia://manage"];
6702 - (UIBarButtonItem *) leftButton {
6703 return [[[UIBarButtonItem alloc]
6704 initWithTitle:UCLocalize("SETTINGS")
6705 style:UIBarButtonItemStylePlain
6707 action:@selector(settingsButtonClicked)
6711 - (void) settingsButtonClicked {
6712 [delegate_ showSettings];
6715 - (void) queueButtonClicked {
6719 - (UIBarButtonItem *) rightButton {
6720 return Queuing_ ? [[[UIBarButtonItem alloc]
6721 initWithTitle:UCLocalize("QUEUE")
6722 style:UIBarButtonItemStyleDone
6724 action:@selector(queueButtonClicked)
6725 ] autorelease] : nil;
6728 - (void) queueStatusDidChange {
6729 [self applyRightButton];
6732 - (bool) isLoading {
6733 return !Queuing_ && [super isLoading];
6739 /* Refresh Bar {{{ */
6740 @interface RefreshBar : UINavigationBar {
6741 _H<UIProgressIndicator> indicator_;
6742 _H<UITextLabel> prompt_;
6743 _H<UIProgressBar> progress_;
6744 _H<UINavigationButton> cancel_;
6749 @implementation RefreshBar
6751 - (void) positionViews {
6752 CGRect frame = [cancel_ frame];
6753 frame.size = [cancel_ sizeThatFits:frame.size];
6754 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6755 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6756 [cancel_ setFrame:frame];
6758 CGSize prgsize = {75, 100};
6760 [self frame].size.width - prgsize.width - 10,
6761 ([self frame].size.height - prgsize.height) / 2
6763 [progress_ setFrame:prgrect];
6765 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6766 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6767 CGRect indrect = {{indoffset, indoffset}, indsize};
6768 [indicator_ setFrame:indrect];
6770 CGSize prmsize = {215, indsize.height + 4};
6772 indoffset * 2 + indsize.width,
6773 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6775 [prompt_ setFrame:prmrect];
6778 - (void) setFrame:(CGRect)frame {
6779 [super setFrame:frame];
6780 [self positionViews];
6783 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6784 if ((self = [super initWithFrame:frame]) != nil) {
6785 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6787 [self setBarStyle:UIBarStyleBlack];
6789 UIBarStyle barstyle([self _barStyle:NO]);
6790 bool ugly(barstyle == UIBarStyleDefault);
6792 UIProgressIndicatorStyle style = ugly ?
6793 UIProgressIndicatorStyleMediumBrown :
6794 UIProgressIndicatorStyleMediumWhite;
6796 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6797 [(UIProgressIndicator *) indicator_ setStyle:style];
6798 [indicator_ startAnimation];
6799 [self addSubview:indicator_];
6801 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6802 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6803 [prompt_ setBackgroundColor:[UIColor clearColor]];
6804 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6805 [self addSubview:prompt_];
6807 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6808 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6809 [(UIProgressBar *) progress_ setStyle:0];
6810 [self addSubview:progress_];
6812 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6813 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6814 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6815 [cancel_ setBarStyle:barstyle];
6817 [self positionViews];
6821 - (void) setCancellable:(bool)cancellable {
6823 [self addSubview:cancel_];
6825 [cancel_ removeFromSuperview];
6829 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6830 [progress_ setProgress:0];
6834 [self setCancellable:NO];
6837 - (void) setPrompt:(NSString *)prompt {
6838 [prompt_ setText:prompt];
6841 - (void) setProgress:(float)progress {
6842 [progress_ setProgress:progress];
6848 /* Cydia Navigation Controller Interface {{{ */
6849 @interface UINavigationController (Cydia)
6851 - (NSArray *) navigationURLCollection;
6852 - (void) unloadData;
6857 /* Cydia Tab Bar Controller {{{ */
6858 @interface CYTabBarController : UITabBarController <
6859 UITabBarControllerDelegate,
6862 _transient Database *database_;
6863 _H<RefreshBar, 1> refreshbar_;
6867 // XXX: ok, "updatedelegate_"?...
6868 _transient NSObject<CydiaDelegate> *updatedelegate_;
6870 _H<UIViewController> remembered_;
6871 _transient UIViewController *transient_;
6874 - (NSArray *) navigationURLCollection;
6875 - (void) dropBar:(BOOL)animated;
6876 - (void) beginUpdate;
6877 - (void) raiseBar:(BOOL)animated;
6879 - (void) unloadData;
6883 @implementation CYTabBarController
6885 - (void) didReceiveMemoryWarning {
6886 [super didReceiveMemoryWarning];
6888 // presenting a UINavigationController on 2.x does not update its transitionView
6889 // it thereby will not allow its topViewController to be unloaded by memory pressure
6890 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6891 UIViewController *selected([self selectedViewController]);
6892 for (UINavigationController *controller in [self viewControllers])
6893 if (controller != selected)
6894 if (UIViewController *top = [controller topViewController])
6899 - (void) setUnselectedViewController:(UIViewController *)transient {
6900 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6901 if (transient != nil) {
6902 [[[self viewControllers] objectAtIndex:0] pushViewController:transient animated:YES];
6903 [self setSelectedIndex:0];
6907 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6908 if (transient != nil) {
6909 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
6910 [navigation setViewControllers:[NSArray arrayWithObject:transient]];
6911 transient = navigation;
6913 if (transient_ == nil)
6914 remembered_ = [controllers objectAtIndex:0];
6915 transient_ = transient;
6916 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6917 [controllers replaceObjectAtIndex:0 withObject:transient_];
6918 [self setSelectedIndex:0];
6919 [self setViewControllers:controllers];
6920 [self concealTabBarSelection];
6921 } else if (remembered_ != nil) {
6922 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6923 transient_ = transient;
6924 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6926 [self setViewControllers:controllers];
6927 [self revealTabBarSelection];
6931 - (UIViewController *) unselectedViewController {
6935 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6936 if ([self unselectedViewController])
6937 [self setUnselectedViewController:nil];
6939 // presenting a UINavigationController on 2.x does not update its transitionView
6940 // if this view was unloaded, the tranitionView may currently be presenting nothing
6941 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6942 UINavigationController *navigation((UINavigationController *) viewController);
6943 [navigation pushViewController:[[[UIViewController alloc] init] autorelease] animated:NO];
6944 [navigation popViewControllerAnimated:NO];
6948 - (NSArray *) navigationURLCollection {
6949 NSMutableArray *items([NSMutableArray array]);
6951 // XXX: Should this deal with transient view controllers?
6952 for (id navigation in [self viewControllers]) {
6953 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6955 [items addObject:stack];
6961 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6962 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6963 [self setUnselectedViewController:nil];
6965 [super dismissModalViewControllerAnimated:YES];
6968 - (void) unloadData {
6971 for (UINavigationController *controller in [self viewControllers])
6972 [controller unloadData];
6974 if (UIViewController *selected = [self selectedViewController])
6975 [selected reloadData];
6977 if (UIViewController *unselected = [self unselectedViewController]) {
6978 [unselected unloadData];
6979 [unselected reloadData];
6984 [[NSNotificationCenter defaultCenter] removeObserver:self];
6989 - (id) initWithDatabase:(Database *)database {
6990 if ((self = [super init]) != nil) {
6991 database_ = database;
6992 [self setDelegate:self];
6994 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6995 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6997 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
7001 - (void) setUpdate:(NSDate *)date {
7005 - (void) beginUpdate {
7006 [(RefreshBar *) refreshbar_ start];
7009 [updatedelegate_ retainNetworkActivityIndicator];
7013 detachNewThreadSelector:@selector(performUpdate)
7019 - (void) performUpdate {
7020 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7023 status.setDelegate(self);
7024 [database_ updateWithStatus:status];
7027 performSelectorOnMainThread:@selector(completeUpdate)
7035 - (void) stopUpdateWithSelector:(SEL)selector {
7037 [updatedelegate_ releaseNetworkActivityIndicator];
7039 [self raiseBar:YES];
7042 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7045 - (void) completeUpdate {
7048 [self stopUpdateWithSelector:@selector(reloadData)];
7051 - (void) cancelUpdate {
7052 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7055 - (void) cancelPressed {
7056 [self cancelUpdate];
7063 - (void) addProgressEvent:(CydiaProgressEvent *)event {
7064 [refreshbar_ setPrompt:[event compoundMessage]];
7067 - (bool) isProgressCancelled {
7071 - (void) setProgressCancellable:(NSNumber *)cancellable {
7072 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
7075 - (void) setProgressPercent:(NSNumber *)percent {
7076 [refreshbar_ setProgress:[percent floatValue]];
7079 - (void) setProgressStatus:(NSDictionary *)status {
7081 [self setProgressPercent:[status objectForKey:@"Percent"]];
7084 - (void) setUpdateDelegate:(id)delegate {
7085 updatedelegate_ = delegate;
7088 - (UIView *) transitionView {
7089 if ([self respondsToSelector:@selector(_transitionView)])
7090 return [self _transitionView];
7092 return MSHookIvar<id>(self, "_viewControllerTransitionView");
7095 - (void) dropBar:(BOOL)animated {
7100 UIView *transition([self transitionView]);
7101 [[self view] addSubview:refreshbar_];
7103 CGRect barframe([refreshbar_ frame]);
7105 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
7106 barframe.origin.y = CYStatusBarHeight();
7108 barframe.origin.y = 0;
7110 [refreshbar_ setFrame:barframe];
7113 [UIView beginAnimations:nil context:NULL];
7115 CGRect viewframe = [transition frame];
7116 viewframe.origin.y += barframe.size.height;
7117 viewframe.size.height -= barframe.size.height;
7118 [transition setFrame:viewframe];
7121 [UIView commitAnimations];
7123 // Ensure bar has the proper width for our view, it might have changed
7124 barframe.size.width = viewframe.size.width;
7125 [refreshbar_ setFrame:barframe];
7128 - (void) raiseBar:(BOOL)animated {
7133 UIView *transition([self transitionView]);
7134 [refreshbar_ removeFromSuperview];
7136 CGRect barframe([refreshbar_ frame]);
7139 [UIView beginAnimations:nil context:NULL];
7141 CGRect viewframe = [transition frame];
7142 viewframe.origin.y -= barframe.size.height;
7143 viewframe.size.height += barframe.size.height;
7144 [transition setFrame:viewframe];
7147 [UIView commitAnimations];
7150 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7151 bool dropped(dropped_);
7156 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7162 - (void) statusBarFrameChanged:(NSNotification *)notification {
7172 /* Cydia Navigation Controller Implementation {{{ */
7173 @implementation UINavigationController (Cydia)
7175 - (NSArray *) navigationURLCollection {
7176 NSMutableArray *stack([NSMutableArray array]);
7178 for (CyteViewController *controller in [self viewControllers]) {
7179 NSString *url = [[controller navigationURL] absoluteString];
7181 [stack addObject:url];
7187 - (void) reloadData {
7190 UIViewController *visible([self visibleViewController]);
7192 [visible reloadData];
7194 // on the iPad, this view controller is ALSO visible. :(
7196 if (UIViewController *top = [self topViewController])
7201 - (void) unloadData {
7202 for (CyteViewController *page in [self viewControllers])
7211 /* Cydia:// Protocol {{{ */
7212 @interface CydiaURLProtocol : NSURLProtocol {
7217 @implementation CydiaURLProtocol
7219 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7220 NSURL *url([request URL]);
7224 NSString *scheme([[url scheme] lowercaseString]);
7225 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7227 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7233 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7237 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7238 id<NSURLProtocolClient> client([self client]);
7240 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7242 NSData *data(UIImagePNGRepresentation(icon));
7244 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7245 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7246 [client URLProtocol:self didLoadData:data];
7247 [client URLProtocolDidFinishLoading:self];
7251 - (void) startLoading {
7252 id<NSURLProtocolClient> client([self client]);
7253 NSURLRequest *request([self request]);
7255 NSURL *url([request URL]);
7256 NSString *href([url absoluteString]);
7257 NSString *scheme([[url scheme] lowercaseString]);
7261 if ([scheme isEqualToString:@"cydia"])
7262 path = [href substringFromIndex:8];
7263 else if ([scheme isEqualToString:@"about"])
7264 path = [href substringFromIndex:12];
7265 else _assert(false);
7267 NSRange slash([path rangeOfString:@"/"]);
7270 if (slash.location == NSNotFound) {
7274 command = [path substringToIndex:slash.location];
7275 path = [path substringFromIndex:(slash.location + 1)];
7278 Database *database([Database sharedInstance]);
7280 if ([command isEqualToString:@"package-icon"]) {
7283 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7284 Package *package([database packageWithName:path]);
7288 UIImage *icon([package icon]);
7289 [self _returnPNGWithImage:icon forRequest:request];
7290 } else if ([command isEqualToString:@"uikit-image"]) {
7293 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7294 UIImage *icon(_UIImageWithName(path));
7295 [self _returnPNGWithImage:icon forRequest:request];
7296 } else if ([command isEqualToString:@"section-icon"]) {
7299 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7300 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7302 icon = [UIImage applicationImageNamed:@"unknown.png"];
7303 [self _returnPNGWithImage:icon forRequest:request];
7305 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7309 - (void) stopLoading {
7315 /* Section Controller {{{ */
7316 @interface SectionController : FilteredPackageListController {
7317 _H<IndirectDelegate, 1> indirect_;
7318 _H<CydiaObject> cydia_;
7319 _H<NSString> section_;
7320 std::vector< _H<CyteWebViewTableViewCell, 1> > promoted_;
7323 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7327 @implementation SectionController
7329 - (NSURL *) referrerURL {
7330 NSString *name = section_;
7334 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@", UI_, [name stringByAddingPercentEscapesIncludingReserved]]];
7337 - (NSURL *) navigationURL {
7338 NSString *name = section_;
7342 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", [name stringByAddingPercentEscapesIncludingReserved]]];
7345 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7348 title = UCLocalize("ALL_PACKAGES");
7349 else if (![name isEqual:@""])
7350 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7352 title = UCLocalize("NO_SECTION");
7354 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7355 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7356 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7361 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7362 return [super numberOfSectionsInTableView:list] + 1;
7365 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7366 return section == 0 ? nil : [super tableView:list titleForHeaderInSection:(section - 1)];
7369 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7370 return section == 0 ? promoted_.size() : [super tableView:list numberOfRowsInSection:(section - 1)];
7373 + (NSIndexPath *) adjustedIndexPath:(NSIndexPath *)path {
7374 return [NSIndexPath indexPathForRow:[path row] inSection:([path section] - 1)];
7377 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7378 if ([path section] != 0)
7379 return [super tableView:table cellForRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7381 return promoted_[[path row]];
7384 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
7385 if ([path section] != 0)
7386 return [super tableView:table didSelectRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7389 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
7390 NSInteger section([super tableView:tableView sectionForSectionIndexTitle:title atIndex:index]);
7391 return section == 0 ? 0 : section + 1;
7394 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7395 NSURL *url([request URL]);
7399 if ([frame isEqualToString:@"_open"])
7400 [delegate_ openURL:url];
7402 WebFrame *frame(nil);
7403 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7404 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7406 frame = [view mainFrame];
7408 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7410 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7411 [controller setDelegate:delegate_];
7412 [[self navigationController] pushViewController:controller animated:YES];
7418 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7419 return [CydiaWebViewController requestWithHeaders:request];
7422 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7423 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7429 // XXX: this code is horrible. I mean, wtf Jay?
7430 if (ShowPromoted_ && [[Metadata_ objectForKey:@"ShowPromoted"] boolValue]) {
7431 promoted_.resize(1);
7433 for (unsigned i(0); i != promoted_.size(); ++i) {
7434 CyteWebViewTableViewCell *promoted([CyteWebViewTableViewCell cellWithRequest:[NSURLRequest
7435 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sectionhead/%u/%@",
7436 UI_, i, section_ == nil ? @"" : [section_ stringByAddingPercentEscapesIncludingReserved]]
7439 cachePolicy:NSURLRequestUseProtocolCachePolicy
7443 [promoted setDelegate:self];
7444 promoted_[i] = promoted;
7449 - (void) setDelegate:(id)delegate {
7450 [super setDelegate:delegate];
7451 [cydia_ setDelegate:delegate];
7454 - (void) releaseSubviews {
7456 [super releaseSubviews];
7461 /* Sections Controller {{{ */
7462 @interface SectionsController : CyteViewController <
7463 UITableViewDataSource,
7466 _transient Database *database_;
7467 _H<NSMutableArray> sections_;
7468 _H<NSMutableArray> filtered_;
7469 _H<UITableView, 2> list_;
7472 - (id) initWithDatabase:(Database *)database;
7473 - (void) editButtonClicked;
7477 @implementation SectionsController
7479 - (NSURL *) navigationURL {
7480 return [NSURL URLWithString:@"cydia://sections"];
7483 - (void) updateNavigationItem {
7484 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7485 if ([sections_ count] == 0) {
7486 [[self navigationItem] setRightBarButtonItem:nil];
7488 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7489 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7491 action:@selector(editButtonClicked)
7492 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7496 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7497 [super setEditing:editing animated:animated];
7502 [delegate_ updateData];
7504 [self updateNavigationItem];
7507 - (void) viewDidAppear:(BOOL)animated {
7508 [super viewDidAppear:animated];
7509 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7512 - (void) viewWillDisappear:(BOOL)animated {
7513 [super viewWillDisappear:animated];
7514 [self setEditing:NO];
7517 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7518 Section *section = nil;
7519 int index = [indexPath row];
7520 if (![self isEditing]) {
7523 section = [filtered_ objectAtIndex:index];
7525 section = [sections_ objectAtIndex:index];
7530 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7531 if ([self isEditing])
7532 return [sections_ count];
7534 return [filtered_ count] + 1;
7537 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7541 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7542 static NSString *reuseIdentifier = @"SectionCell";
7544 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7546 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7548 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7553 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7554 if ([self isEditing])
7557 Section *section = [self sectionAtIndexPath:indexPath];
7559 SectionController *controller = [[[SectionController alloc]
7560 initWithDatabase:database_
7561 section:[section name]
7563 [controller setDelegate:delegate_];
7565 [[self navigationController] pushViewController:controller animated:YES];
7569 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7570 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7571 [list_ setRowHeight:45.0f];
7572 [(UITableView *) list_ setDataSource:self];
7573 [list_ setDelegate:self];
7574 [self setView:list_];
7577 - (void) viewDidLoad {
7578 [super viewDidLoad];
7580 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7583 - (void) releaseSubviews {
7589 [super releaseSubviews];
7592 - (id) initWithDatabase:(Database *)database {
7593 if ((self = [super init]) != nil) {
7594 database_ = database;
7598 - (void) reloadData {
7601 NSArray *packages = [database_ packages];
7603 sections_ = [NSMutableArray arrayWithCapacity:16];
7604 filtered_ = [NSMutableArray arrayWithCapacity:16];
7606 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7609 for (Package *package in packages) {
7610 NSString *name([package section]);
7611 NSString *key(name == nil ? @"" : name);
7615 _profile(SectionsView$reloadData$Section)
7616 section = [sections objectForKey:key];
7617 if (section == nil) {
7618 _profile(SectionsView$reloadData$Section$Allocate)
7619 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7620 [sections setObject:section forKey:key];
7625 [section addToCount];
7627 _profile(SectionsView$reloadData$Filter)
7628 if (![package valid] || ![package visible])
7636 [sections_ addObjectsFromArray:[sections allValues]];
7638 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7640 for (Section *section in (id) sections_) {
7641 size_t count([section row]);
7645 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7646 [section setCount:count];
7647 [filtered_ addObject:section];
7650 [self updateNavigationItem];
7655 - (void) editButtonClicked {
7656 [self setEditing:![self isEditing] animated:YES];
7662 /* Changes Controller {{{ */
7663 @interface ChangesController : CyteViewController <
7664 UITableViewDataSource,
7667 _transient Database *database_;
7669 _H<NSArray> packages_;
7670 _H<NSMutableArray> sections_;
7671 _H<UITableView, 2> list_;
7672 _H<CyteWebView, 1> dickbar_;
7674 _H<IndirectDelegate, 1> indirect_;
7675 _H<CydiaObject> cydia_;
7678 - (id) initWithDatabase:(Database *)database;
7682 @implementation ChangesController
7684 - (NSURL *) navigationURL {
7685 return [NSURL URLWithString:@"cydia://changes"];
7688 - (void) viewDidAppear:(BOOL)animated {
7689 [super viewDidAppear:animated];
7690 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7693 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7694 NSInteger count([sections_ count]);
7695 return count == 0 ? 1 : count;
7698 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7699 if ([sections_ count] == 0)
7701 return [[sections_ objectAtIndex:section] name];
7704 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7705 if ([sections_ count] == 0)
7707 return [[sections_ objectAtIndex:section] count];
7710 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7711 @synchronized (database_) {
7712 if ([database_ era] != era_)
7715 NSUInteger sectionIndex([path section]);
7716 if (sectionIndex >= [sections_ count])
7718 Section *section([sections_ objectAtIndex:sectionIndex]);
7719 NSInteger row([path row]);
7720 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7723 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7724 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7726 cell = [[[PackageCell alloc] init] autorelease];
7728 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7729 [cell setPackage:package asSummary:false];
7733 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7734 Package *package([self packageAtIndexPath:path]);
7735 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[NSString stringWithFormat:@"%@/#!/changes/", UI_]] autorelease]);
7736 [view setDelegate:delegate_];
7737 [[self navigationController] pushViewController:view animated:YES];
7741 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7742 NSString *context([alert context]);
7744 if ([context isEqualToString:@"norefresh"])
7745 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7748 - (void) refreshButtonClicked {
7749 if (IsReachable("cydia.saurik.com")) {
7750 [delegate_ beginUpdate];
7751 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7753 UIAlertView *alert = [[[UIAlertView alloc]
7754 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
7755 message:@"Host Unreachable" // XXX: Localize
7757 cancelButtonTitle:UCLocalize("OK")
7758 otherButtonTitles:nil
7761 [alert setContext:@"norefresh"];
7766 - (void) upgradeButtonClicked {
7767 [delegate_ distUpgrade];
7768 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7772 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7773 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7774 [self setView:view];
7776 list_ = [[[UITableView alloc] initWithFrame:[view bounds] style:UITableViewStylePlain] autorelease];
7777 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7778 [list_ setRowHeight:73];
7779 [(UITableView *) list_ setDataSource:self];
7780 [list_ setDelegate:self];
7781 [view addSubview:list_];
7783 if (AprilFools_ && kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
7784 CGRect dickframe([view bounds]);
7785 dickframe.size.height = 44;
7787 dickbar_ = [[[CyteWebView alloc] initWithFrame:dickframe] autorelease];
7788 [dickbar_ setDelegate:self];
7789 [view addSubview:dickbar_];
7791 [dickbar_ setBackgroundColor:[UIColor clearColor]];
7792 [dickbar_ setScalesPageToFit:YES];
7794 UIWebDocumentView *document([dickbar_ _documentView]);
7795 [document setBackgroundColor:[UIColor clearColor]];
7796 [document setDrawsBackground:NO];
7798 WebView *webview([document webView]);
7799 [webview setShouldUpdateWhileOffscreen:NO];
7801 UIScrollView *scroller([dickbar_ scrollView]);
7802 [scroller setScrollingEnabled:NO];
7803 [scroller setFixedBackgroundPattern:YES];
7804 [scroller setBackgroundColor:[UIColor clearColor]];
7806 WebPreferences *preferences([webview preferences]);
7807 [preferences setCacheModel:WebCacheModelDocumentBrowser];
7808 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
7809 [preferences setOfflineWebApplicationCacheEnabled:YES];
7811 [dickbar_ loadRequest:[NSURLRequest
7812 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/dickbar/", UI_]]]
7813 cachePolicy:NSURLRequestUseProtocolCachePolicy
7817 UIEdgeInsets inset = {44, 0, 0, 0};
7818 [list_ setContentInset:inset];
7820 [dickbar_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7824 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7825 NSURL *url([request URL]);
7829 if ([frame isEqualToString:@"_open"])
7830 [delegate_ openURL:url];
7832 WebFrame *frame(nil);
7833 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7834 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7836 frame = [view mainFrame];
7838 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7840 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7841 [controller setDelegate:delegate_];
7842 [[self navigationController] pushViewController:controller animated:YES];
7848 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7849 return [CydiaWebViewController requestWithHeaders:request];
7852 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7853 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7856 - (void) setDelegate:(id)delegate {
7857 [super setDelegate:delegate];
7858 [cydia_ setDelegate:delegate];
7861 - (void) viewDidLoad {
7862 [super viewDidLoad];
7864 [[self navigationItem] setTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES"))];
7867 - (void) releaseSubviews {
7874 [super releaseSubviews];
7877 - (id) initWithDatabase:(Database *)database {
7878 if ((self = [super init]) != nil) {
7879 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7880 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7881 database_ = database;
7885 - (NSMutableArray *) _reloadPackages {
7886 @synchronized (database_) {
7887 era_ = [database_ era];
7888 NSArray *packages([database_ packages]);
7890 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7893 _profile(ChangesController$_reloadPackages$Filter)
7894 for (Package *package in packages)
7895 if ([package upgradableAndEssential:YES] || [package visible])
7896 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7899 _profile(ChangesController$_reloadPackages$radixSort)
7900 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7907 - (void) _reloadData {
7912 UIProgressHUD *hud([delegate_ addProgressHUD]);
7913 [hud setText:UCLocalize("LOADING")];
7914 //NSLog(@"HUD:%@::%@", delegate_, hud);
7915 packages = [self yieldToSelector:@selector(_reloadPackages)];
7916 [delegate_ removeProgressHUD:hud];
7918 packages = [self _reloadPackages];
7921 @synchronized (database_) {
7922 if (era_ != [database_ era])
7925 packages_ = packages;
7926 sections_ = [NSMutableArray arrayWithCapacity:16];
7928 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7929 Section *ignored = nil;
7930 Section *section = nil;
7934 bool unseens = false;
7936 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7938 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7939 Package *package = [packages_ objectAtIndex:offset];
7941 BOOL uae = [package upgradableAndEssential:YES];
7945 time_t seen([package seen]);
7947 if (section == nil || last != seen) {
7951 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7954 _profile(ChangesController$reloadData$Allocate)
7955 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7956 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7957 [sections_ addObject:section];
7961 [section addToCount];
7962 } else if ([package ignored]) {
7963 if (ignored == nil) {
7964 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7966 [ignored addToCount];
7969 [upgradable addToCount];
7974 CFRelease(formatter);
7977 Section *last = [sections_ lastObject];
7978 size_t count = [last count];
7979 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7980 [sections_ removeLastObject];
7983 if ([ignored count] != 0)
7984 [sections_ insertObject:ignored atIndex:0];
7986 [sections_ insertObject:upgradable atIndex:0];
7990 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7991 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7992 style:UIBarButtonItemStylePlain
7994 action:@selector(upgradeButtonClicked)
7995 ] autorelease]) animated:YES];
7997 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7998 initWithTitle:UCLocalize("REFRESH")
7999 style:UIBarButtonItemStylePlain
8001 action:@selector(refreshButtonClicked)
8002 ] autorelease]) animated:YES];
8007 - (void) reloadData {
8009 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
8014 /* Search Controller {{{ */
8015 @interface SearchController : FilteredPackageListController <
8018 _H<UISearchBar, 1> search_;
8022 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
8023 - (void) reloadData;
8027 @implementation SearchController
8029 - (NSURL *) referrerURL {
8030 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
8033 - (NSURL *) navigationURL {
8034 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
8035 return [NSURL URLWithString:@"cydia://search"];
8037 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
8040 - (NSArray *) termsForQuery:(NSString *)query {
8041 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
8042 for (NSString *component in [query componentsSeparatedByString:@" "])
8043 if ([component length] != 0)
8044 [terms addObject:component];
8049 - (void) useSearch {
8050 [self setObject:[self termsForQuery:[search_ text]] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
8055 - (void) viewWillAppear:(BOOL)animated {
8056 [super viewWillAppear:animated];
8058 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
8062 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
8063 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8068 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
8069 [search_ resignFirstResponder];
8073 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
8074 [search_ setText:@""];
8075 [self searchBarButtonClicked:searchBar];
8078 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
8079 [self searchBarButtonClicked:searchBar];
8082 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
8083 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8087 - (bool) shouldYield {
8091 - (bool) shouldBlock {
8092 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
8095 - (bool) isSummarized {
8096 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
8099 - (bool) showsSections {
8103 - (NSMutableArray *) _reloadPackages {
8104 NSMutableArray *packages([super _reloadPackages]);
8105 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8106 [packages radixSortUsingSelector:@selector(rank)];
8110 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
8111 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[self termsForQuery:query]])) {
8112 search_ = [[[UISearchBar alloc] init] autorelease];
8113 [search_ setDelegate:self];
8116 [search_ setText:query];
8120 - (void) viewDidAppear:(BOOL)animated {
8121 [super viewDidAppear:animated];
8123 if (!searchloaded_) {
8124 searchloaded_ = YES;
8125 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
8126 [search_ layoutSubviews];
8127 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
8129 UITextField *textField;
8130 if ([search_ respondsToSelector:@selector(searchField)])
8131 textField = [search_ searchField];
8133 textField = MSHookIvar<UITextField *>(search_, "_searchField");
8135 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8136 [textField setEnablesReturnKeyAutomatically:NO];
8137 [[self navigationItem] setTitleView:textField];
8141 - (void) reloadData {
8142 id object([search_ text]);
8143 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8144 object = [self termsForQuery:object];
8146 [self setObject:object];
8152 - (void) didSelectPackage:(Package *)package {
8153 [search_ resignFirstResponder];
8154 [super didSelectPackage:package];
8159 /* Package Settings Controller {{{ */
8160 @interface PackageSettingsController : CyteViewController <
8161 UITableViewDataSource,
8164 _transient Database *database_;
8166 _H<Package> package_;
8167 _H<UITableView, 2> table_;
8168 _H<UISwitch> subscribedSwitch_;
8169 _H<UISwitch> ignoredSwitch_;
8170 _H<UITableViewCell> subscribedCell_;
8171 _H<UITableViewCell> ignoredCell_;
8174 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
8178 @implementation PackageSettingsController
8180 - (NSURL *) navigationURL {
8181 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
8184 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8185 if (package_ == nil)
8188 if ([package_ installed] == nil)
8194 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8195 if (package_ == nil)
8198 // both sections contain just one item right now.
8202 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8206 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8208 return UCLocalize("SHOW_ALL_CHANGES_EX");
8210 return UCLocalize("IGNORE_UPGRADES_EX");
8213 - (void) onSubscribed:(id)control {
8214 bool value([control isOn]);
8215 if (package_ == nil)
8217 if ([package_ setSubscribed:value])
8218 [delegate_ updateData];
8221 - (void) _updateIgnored {
8222 const char *package([name_ UTF8String]);
8223 bool on([ignoredSwitch_ isOn]);
8225 pid_t pid(ExecFork());
8227 FILE *dpkg(popen("dpkg --set-selections", "w"));
8228 fwrite(package, strlen(package), 1, dpkg);
8231 fwrite(" hold\n", 6, 1, dpkg);
8233 fwrite(" install\n", 9, 1, dpkg);
8244 - (void) onIgnored:(id)control {
8245 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8246 [invocation setTarget:self];
8247 [invocation setSelector:@selector(_updateIgnored)];
8249 [delegate_ reloadDataWithInvocation:invocation];
8252 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8253 if (package_ == nil)
8256 switch ([indexPath section]) {
8257 case 0: return subscribedCell_;
8258 case 1: return ignoredCell_;
8267 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8268 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8269 [self setView:view];
8271 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8272 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8273 [(UITableView *) table_ setDataSource:self];
8274 [table_ setDelegate:self];
8275 [view addSubview:table_];
8277 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8278 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8279 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8281 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8282 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8283 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8285 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8286 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8287 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8288 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8290 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8291 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8292 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8293 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8296 - (void) viewDidLoad {
8297 [super viewDidLoad];
8299 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8302 - (void) releaseSubviews {
8304 subscribedCell_ = nil;
8306 ignoredSwitch_ = nil;
8307 subscribedSwitch_ = nil;
8309 [super releaseSubviews];
8312 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8313 if ((self = [super init]) != nil) {
8314 database_ = database;
8319 - (void) reloadData {
8322 package_ = [database_ packageWithName:name_];
8324 if (package_ != nil) {
8325 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8326 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8327 } // XXX: what now, G?
8329 [table_ reloadData];
8335 /* Installed Controller {{{ */
8336 @interface InstalledController : FilteredPackageListController {
8340 - (id) initWithDatabase:(Database *)database;
8342 - (void) updateRoleButton;
8343 - (void) queueStatusDidChange;
8347 @implementation InstalledController
8349 - (NSURL *) referrerURL {
8350 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8353 - (NSURL *) navigationURL {
8354 return [NSURL URLWithString:@"cydia://installed"];
8357 - (id) initWithDatabase:(Database *)database {
8358 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8359 [self updateRoleButton];
8360 [self queueStatusDidChange];
8365 - (void) queueButtonClicked {
8370 - (void) queueStatusDidChange {
8374 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8375 initWithTitle:UCLocalize("QUEUE")
8376 style:UIBarButtonItemStyleDone
8378 action:@selector(queueButtonClicked)
8381 [[self navigationItem] setLeftBarButtonItem:nil];
8387 - (void) updateRoleButton {
8388 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8389 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8390 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8391 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8393 action:@selector(roleButtonClicked)
8397 - (void) roleButtonClicked {
8398 [self setObject:[NSNumber numberWithBool:expert_]];
8402 [self updateRoleButton];
8408 /* Source Cell {{{ */
8409 @interface SourceCell : CyteTableViewCell <
8410 CyteTableViewCellDelegate
8414 _H<NSString> origin_;
8415 _H<NSString> label_;
8418 - (void) setSource:(Source *)source;
8422 @implementation SourceCell
8424 - (void) _setImage:(NSArray *)data {
8425 if ([url_ isEqual:[data objectAtIndex:0]]) {
8426 icon_ = [data objectAtIndex:1];
8427 [content_ setNeedsDisplay];
8431 - (void) _setSource:(NSURL *) url {
8432 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8434 if (NSData *data = [NSURLConnection
8435 sendSynchronousRequest:[NSURLRequest
8437 cachePolicy:NSURLRequestUseProtocolCachePolicy
8441 returningResponse:NULL
8444 if (UIImage *image = [UIImage imageWithData:data])
8445 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8450 - (void) setSource:(Source *)source {
8451 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8453 origin_ = [source name];
8454 label_ = [source rooturi];
8456 [content_ setNeedsDisplay];
8458 url_ = [source iconURL];
8459 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8462 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8463 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8464 UIView *content([self contentView]);
8465 CGRect bounds([content bounds]);
8467 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8468 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8469 [content_ setBackgroundColor:[UIColor whiteColor]];
8470 [content addSubview:content_];
8472 [content_ setDelegate:self];
8473 [content_ setOpaque:YES];
8475 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8479 - (NSString *) accessibilityLabel {
8483 - (void) drawContentRect:(CGRect)rect {
8484 bool highlighted(highlighted_);
8485 float width(rect.size.width);
8489 rect.size = [(UIImage *) icon_ size];
8491 while (rect.size.width > 32 || rect.size.height > 32) {
8492 rect.size.width /= 2;
8493 rect.size.height /= 2;
8496 rect.origin.x = 25 - rect.size.width / 2;
8497 rect.origin.y = 25 - rect.size.height / 2;
8499 [icon_ drawInRect:rect];
8507 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 65) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8511 [label_ drawAtPoint:CGPointMake(48, 29) forWidth:(width - 65) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8516 /* Source Controller {{{ */
8517 @interface SourceController : FilteredPackageListController {
8518 _transient Source *source_;
8522 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8526 @implementation SourceController
8528 - (NSURL *) referrerURL {
8529 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sources/%@", UI_, [key_ stringByAddingPercentEscapesIncludingReserved]]];
8532 - (NSURL *) navigationURL {
8533 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8536 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8537 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8539 key_ = [source key];
8543 - (void) reloadData {
8544 source_ = [database_ sourceWithKey:key_];
8545 key_ = [source_ key];
8546 [self setObject:source_];
8548 [[self navigationItem] setTitle:[source_ label]];
8555 /* Sources Controller {{{ */
8556 @interface SourcesController : CyteViewController <
8557 UITableViewDataSource,
8560 _transient Database *database_;
8563 _H<UITableView, 2> list_;
8564 _H<NSMutableArray> sources_;
8568 _H<UIProgressHUD> hud_;
8571 //NSURLConnection *installer_;
8572 NSURLConnection *trivial_;
8573 NSURLConnection *trivial_bz2_;
8574 NSURLConnection *trivial_gz_;
8575 //NSURLConnection *automatic_;
8580 - (id) initWithDatabase:(Database *)database;
8581 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8585 @implementation SourcesController
8587 - (void) _releaseConnection:(NSURLConnection *)connection {
8588 if (connection != nil) {
8589 [connection cancel];
8590 //[connection setDelegate:nil];
8591 [connection release];
8596 //[self _releaseConnection:installer_];
8597 [self _releaseConnection:trivial_];
8598 [self _releaseConnection:trivial_gz_];
8599 [self _releaseConnection:trivial_bz2_];
8600 //[self _releaseConnection:automatic_];
8605 - (NSURL *) navigationURL {
8606 return [NSURL URLWithString:@"cydia://sources"];
8609 - (void) viewDidAppear:(BOOL)animated {
8610 [super viewDidAppear:animated];
8611 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8614 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8618 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8622 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8623 return [sources_ count];
8626 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8627 @synchronized (database_) {
8628 if ([database_ era] != era_)
8631 NSUInteger index([indexPath row]);
8632 return index < [sources_ count] ? [sources_ objectAtIndex:index] : nil;
8635 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8636 static NSString *cellIdentifier = @"SourceCell";
8638 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8639 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8640 [cell setSource:[self sourceAtIndexPath:indexPath]];
8641 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8646 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8647 Source *source = [self sourceAtIndexPath:indexPath];
8648 if (source == nil) return;
8650 SourceController *controller = [[[SourceController alloc]
8651 initWithDatabase:database_
8655 [controller setDelegate:delegate_];
8657 [[self navigationController] pushViewController:controller animated:YES];
8660 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8661 Source *source = [self sourceAtIndexPath:indexPath];
8662 return [source record] != nil;
8665 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8666 if (editingStyle == UITableViewCellEditingStyleDelete) {
8667 Source *source = [self sourceAtIndexPath:indexPath];
8668 if (source == nil) return;
8670 [Sources_ removeObjectForKey:[source key]];
8671 [delegate_ _saveConfig];
8672 [delegate_ reloadDataWithInvocation:nil];
8677 [delegate_ addTrivialSource:href_];
8680 [delegate_ syncData];
8683 - (NSString *) getWarning {
8684 NSString *href(href_);
8685 NSRange colon([href rangeOfString:@"://"]);
8686 if (colon.location != NSNotFound)
8687 href = [href substringFromIndex:(colon.location + 3)];
8688 href = [href stringByAddingPercentEscapes];
8689 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8691 NSURL *url([NSURL URLWithString:href]);
8693 NSStringEncoding encoding;
8694 NSError *error(nil);
8696 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8697 return [warning length] == 0 ? nil : warning;
8701 - (void) _endConnection:(NSURLConnection *)connection {
8702 // XXX: the memory management in this method is horribly awkward
8704 NSURLConnection **field = NULL;
8705 if (connection == trivial_)
8707 else if (connection == trivial_bz2_)
8708 field = &trivial_bz2_;
8709 else if (connection == trivial_gz_)
8710 field = &trivial_gz_;
8711 _assert(field != NULL);
8712 [connection release];
8717 trivial_bz2_ == nil &&
8720 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8722 [delegate_ releaseNetworkActivityIndicator];
8724 [delegate_ removeProgressHUD:hud_];
8728 if (warning != nil) {
8729 UIAlertView *alert = [[[UIAlertView alloc]
8730 initWithTitle:UCLocalize("SOURCE_WARNING")
8733 cancelButtonTitle:UCLocalize("CANCEL")
8735 UCLocalize("ADD_ANYWAY"),
8739 [alert setContext:@"warning"];
8740 [alert setNumberOfRows:1];
8743 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8749 } else if (error_ != nil) {
8750 UIAlertView *alert = [[[UIAlertView alloc]
8751 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8752 message:[error_ localizedDescription]
8754 cancelButtonTitle:UCLocalize("OK")
8755 otherButtonTitles:nil
8758 [alert setContext:@"urlerror"];
8763 UIAlertView *alert = [[[UIAlertView alloc]
8764 initWithTitle:UCLocalize("NOT_REPOSITORY")
8765 message:UCLocalize("NOT_REPOSITORY_EX")
8767 cancelButtonTitle:UCLocalize("OK")
8768 otherButtonTitles:nil
8771 [alert setContext:@"trivial"];
8781 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8782 switch ([response statusCode]) {
8788 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8789 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8791 [self _endConnection:connection];
8794 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8795 [self _endConnection:connection];
8798 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8799 NSURL *url([NSURL URLWithString:href]);
8801 NSMutableURLRequest *request = [NSMutableURLRequest
8803 cachePolicy:NSURLRequestUseProtocolCachePolicy
8807 [request setHTTPMethod:method];
8809 if (Machine_ != NULL)
8810 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8812 if (UniqueID_ != nil)
8813 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8815 if ([url isCydiaSecure]) {
8816 if (UniqueID_ != nil)
8817 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8820 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8823 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8824 NSString *context([alert context]);
8826 if ([context isEqualToString:@"source"]) {
8829 NSString *href = [[alert textField] text];
8831 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8833 if (![href hasSuffix:@"/"])
8834 href_ = [href stringByAppendingString:@"/"];
8838 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8839 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8840 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8841 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8845 // XXX: this is stupid
8846 hud_ = [delegate_ addProgressHUD];
8847 [hud_ setText:UCLocalize("VERIFYING_URL")];
8848 [delegate_ retainNetworkActivityIndicator];
8857 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8858 } else if ([context isEqualToString:@"trivial"])
8859 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8860 else if ([context isEqualToString:@"urlerror"])
8861 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8862 else if ([context isEqualToString:@"warning"]) {
8865 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8874 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8879 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8880 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8881 [list_ setRowHeight:53];
8882 [(UITableView *) list_ setDataSource:self];
8883 [list_ setDelegate:self];
8884 [self setView:list_];
8887 - (void) viewDidLoad {
8888 [super viewDidLoad];
8890 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8891 [self updateButtonsForEditingStatusAnimated:NO];
8894 - (void) viewWillDisappear:(BOOL)animated {
8895 [super viewWillAppear:animated];
8897 [list_ setEditing:NO];
8898 [self updateButtonsForEditingStatusAnimated:NO];
8901 - (void) releaseSubviews {
8906 [super releaseSubviews];
8909 - (id) initWithDatabase:(Database *)database {
8910 if ((self = [super init]) != nil) {
8911 database_ = database;
8915 - (void) reloadData {
8918 @synchronized (database_) {
8919 era_ = [database_ era];
8921 sources_ = [NSMutableArray arrayWithCapacity:16];
8922 [sources_ addObjectsFromArray:[database_ sources]];
8924 [sources_ sortUsingSelector:@selector(compareByName:)];
8927 int count([sources_ count]);
8929 for (int i = 0; i != count; i++) {
8930 if ([[sources_ objectAtIndex:i] record] == nil)
8938 - (void) showAddSourcePrompt {
8939 UIAlertView *alert = [[[UIAlertView alloc]
8940 initWithTitle:UCLocalize("ENTER_APT_URL")
8943 cancelButtonTitle:UCLocalize("CANCEL")
8945 UCLocalize("ADD_SOURCE"),
8949 [alert setContext:@"source"];
8951 [alert setNumberOfRows:1];
8952 [alert addTextFieldWithValue:@"http://" label:@""];
8954 UITextInputTraits *traits = [[alert textField] textInputTraits];
8955 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8956 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8957 [traits setKeyboardType:UIKeyboardTypeURL];
8958 // XXX: UIReturnKeyDone
8959 [traits setReturnKeyType:UIReturnKeyNext];
8964 - (void) addButtonClicked {
8965 [self showAddSourcePrompt];
8968 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8969 BOOL editing([list_ isEditing]);
8971 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8972 initWithTitle:UCLocalize("ADD")
8973 style:UIBarButtonItemStylePlain
8975 action:@selector(addButtonClicked)
8976 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8978 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8979 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8980 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8982 action:@selector(editButtonClicked)
8983 ] autorelease] animated:animated];
8985 if (IsWildcat_ && !editing)
8986 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8987 initWithTitle:UCLocalize("SETTINGS")
8988 style:UIBarButtonItemStylePlain
8990 action:@selector(settingsButtonClicked)
8994 - (void) settingsButtonClicked {
8995 [delegate_ showSettings];
8998 - (void) editButtonClicked {
8999 [list_ setEditing:![list_ isEditing] animated:YES];
9000 [self updateButtonsForEditingStatusAnimated:YES];
9006 /* Settings Controller {{{ */
9007 @interface SettingsController : CyteViewController <
9008 UITableViewDataSource,
9011 _transient Database *database_;
9012 // XXX: ok, "roledelegate_"?...
9013 _transient id roledelegate_;
9014 _H<UITableView, 2> table_;
9015 _H<UISegmentedControl> segment_;
9016 _H<UIView> container_;
9019 - (void) showDoneButton;
9020 - (void) resizeSegmentedControl;
9024 @implementation SettingsController
9027 table_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
9028 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9029 [table_ setDelegate:self];
9030 [(UITableView *) table_ setDataSource:self];
9031 [self setView:table_];
9033 NSArray *items = [NSArray arrayWithObjects:
9035 UCLocalize("HACKER"),
9036 UCLocalize("DEVELOPER"),
9038 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
9039 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
9040 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
9041 [container_ addSubview:segment_];
9044 - (void) viewDidLoad {
9045 [super viewDidLoad];
9047 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
9050 if ([Role_ isEqualToString:@"User"]) index = 0;
9051 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
9052 if ([Role_ isEqualToString:@"Developer"]) index = 2;
9054 [segment_ setSelectedSegmentIndex:index];
9055 [self showDoneButton];
9058 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
9059 [self resizeSegmentedControl];
9062 - (void) releaseSubviews {
9067 [super releaseSubviews];
9070 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
9071 if ((self = [super init]) != nil) {
9072 database_ = database;
9073 roledelegate_ = delegate;
9077 - (void) resizeSegmentedControl {
9078 CGFloat width = [[self view] frame].size.width;
9079 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
9082 - (void) viewWillAppear:(BOOL)animated {
9083 [super viewWillAppear:animated];
9085 [self resizeSegmentedControl];
9088 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
9089 [self resizeSegmentedControl];
9092 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
9093 [self resizeSegmentedControl];
9097 NSString *role(nil);
9099 switch ([segment_ selectedSegmentIndex]) {
9100 case 0: role = @"User"; break;
9101 case 1: role = @"Hacker"; break;
9102 case 2: role = @"Developer"; break;
9107 if (![role isEqualToString:Role_]) {
9108 bool rolling(Role_ == nil);
9111 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
9115 [Metadata_ setObject:Settings_ forKey:@"Settings"];
9119 [roledelegate_ loadData];
9121 [roledelegate_ updateData];
9125 - (void) segmentChanged:(UISegmentedControl *)control {
9126 [self showDoneButton];
9129 - (void) saveAndClose {
9132 [[self navigationItem] setRightBarButtonItem:nil];
9133 [[self navigationController] dismissModalViewControllerAnimated:YES];
9136 - (void) doneButtonClicked {
9137 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
9138 [spinner startAnimating];
9139 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
9140 [[self navigationItem] setRightBarButtonItem:spinItem];
9142 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
9145 - (void) showDoneButton {
9146 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
9147 initWithTitle:UCLocalize("DONE")
9148 style:UIBarButtonItemStyleDone
9150 action:@selector(doneButtonClicked)
9151 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
9154 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
9155 // XXX: For not having a single cell in the table, this sure is a lot of sections.
9159 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
9163 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
9164 return nil; // This method is required by the protocol.
9167 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
9169 return UCLocalize("ROLE_EX");
9171 return [NSString stringWithFormat:
9172 @"%@: %@\n%@: %@\n%@: %@",
9173 UCLocalize("USER"), UCLocalize("USER_EX"),
9174 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
9175 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
9180 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
9181 return section == 3 ? 44.0f : 0;
9184 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
9185 return section == 3 ? container_ : nil;
9188 - (void) reloadData {
9191 [table_ reloadData];
9196 /* Stash Controller {{{ */
9197 @interface StashController : CyteViewController {
9198 _H<UIActivityIndicatorView> spinner_;
9199 _H<UILabel> status_;
9200 _H<UILabel> caption_;
9205 @implementation StashController
9208 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
9209 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
9210 [self setView:view];
9212 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
9214 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
9215 CGRect spinrect = [spinner_ frame];
9216 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
9217 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
9218 [spinner_ setFrame:spinrect];
9219 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
9220 [view addSubview:spinner_];
9221 [spinner_ startAnimating];
9224 captrect.size.width = [[self view] frame].size.width;
9225 captrect.size.height = 40.0f;
9226 captrect.origin.x = 0;
9227 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
9228 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
9229 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
9230 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9231 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
9232 [caption_ setTextColor:[UIColor whiteColor]];
9233 [caption_ setBackgroundColor:[UIColor clearColor]];
9234 [caption_ setShadowColor:[UIColor blackColor]];
9235 [caption_ setTextAlignment:UITextAlignmentCenter];
9236 [view addSubview:caption_];
9239 statusrect.size.width = [[self view] frame].size.width;
9240 statusrect.size.height = 30.0f;
9241 statusrect.origin.x = 0;
9242 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
9243 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
9244 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9245 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
9246 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
9247 [status_ setTextColor:[UIColor whiteColor]];
9248 [status_ setBackgroundColor:[UIColor clearColor]];
9249 [status_ setShadowColor:[UIColor blackColor]];
9250 [status_ setTextAlignment:UITextAlignmentCenter];
9251 [view addSubview:status_];
9254 - (void) releaseSubviews {
9259 [super releaseSubviews];
9265 @interface CYURLCache : SDURLCache {
9270 @implementation CYURLCache
9272 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
9275 else if ([event isEqualToString:@"no-cache"])
9277 else if ([event isEqualToString:@"store"])
9279 else if ([event isEqualToString:@"invalid"])
9281 else if ([event isEqualToString:@"memory"])
9283 else if ([event isEqualToString:@"disk"])
9285 else if ([event isEqualToString:@"miss"])
9288 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
9292 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
9293 if (NSURLResponse *response = [cached response])
9294 if (NSString *mime = [response MIMEType])
9295 if ([mime isEqualToString:@"text/cache-manifest"]) {
9296 NSURL *url([response URL]);
9299 NSLog(@"###: %@", [url absoluteString]);
9302 @synchronized (HostConfig_) {
9303 [CachedURLs_ addObject:url];
9307 [super storeCachedResponse:cached forRequest:request];
9312 @interface Cydia : UIApplication <
9313 ConfirmationControllerDelegate,
9316 UINavigationControllerDelegate,
9317 UITabBarControllerDelegate
9319 _H<UIWindow> window_;
9320 _H<CYTabBarController> tabbar_;
9321 _H<CydiaLoadingViewController> emulated_;
9323 _H<NSMutableArray> essential_;
9324 _H<NSMutableArray> broken_;
9326 Database *database_;
9328 _H<NSURL> starturl_;
9333 _H<StashController> stash_;
9342 @implementation Cydia
9344 - (void) beginUpdate {
9345 [tabbar_ beginUpdate];
9349 return [tabbar_ updating];
9353 if ([broken_ count] != 0) {
9354 int count = [broken_ count];
9356 UIAlertView *alert = [[[UIAlertView alloc]
9357 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9358 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9360 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
9362 UCLocalize("TEMPORARY_IGNORE"),
9366 [alert setContext:@"fixhalf"];
9367 [alert setNumberOfRows:2];
9369 } else if (!Ignored_ && [essential_ count] != 0) {
9370 int count = [essential_ count];
9372 UIAlertView *alert = [[[UIAlertView alloc]
9373 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9374 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9376 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9378 UCLocalize("UPGRADE_ESSENTIAL"),
9379 UCLocalize("COMPLETE_UPGRADE"),
9383 [alert setContext:@"upgrade"];
9388 - (void) returnToCydia {
9392 - (void) _saveConfig {
9393 @synchronized (database_) {
9400 NSString *error(nil);
9402 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9404 NSError *error(nil);
9405 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9406 NSLog(@"failure to save metadata data: %@", error);
9411 NSLog(@"failure to serialize metadata: %@", error);
9415 CydiaWriteSources();
9418 // Navigation controller for the queuing badge.
9419 - (UINavigationController *) queueNavigationController {
9420 NSArray *controllers = [tabbar_ viewControllers];
9421 return [controllers objectAtIndex:3];
9424 - (void) unloadData {
9425 [tabbar_ unloadData];
9428 - (void) _updateData {
9432 UINavigationController *navigation = [self queueNavigationController];
9434 id queuedelegate = nil;
9435 if ([[navigation viewControllers] count] > 0)
9436 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9438 [queuedelegate queueStatusDidChange];
9439 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9442 - (void) _refreshIfPossible:(NSDate *)update {
9443 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9445 bool recently = false;
9446 if (update != nil) {
9447 NSTimeInterval interval([update timeIntervalSinceNow]);
9448 if (interval <= 0 && interval > -(15*60))
9452 // Don't automatic refresh if:
9453 // - We already refreshed recently.
9454 // - We already auto-refreshed this launch.
9455 // - Auto-refresh is disabled.
9456 if (recently || loaded_ || ManualRefresh) {
9457 // If we are cancelling, we need to make sure it knows it's already loaded.
9460 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9462 // We are going to load, so remember that.
9465 // If we can reach the server, auto-refresh!
9466 if (IsReachable("cydia.saurik.com"))
9467 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9473 - (void) refreshIfPossible {
9474 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9477 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9478 @synchronized (self) {
9479 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9480 [hud setText:UCLocalize("RELOADING_DATA")];
9482 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9486 [essential_ removeAllObjects];
9487 [broken_ removeAllObjects];
9489 NSArray *packages([database_ packages]);
9490 for (Package *package in packages) {
9492 [broken_ addObject:package];
9493 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9494 if ([package essential] && [package installed] != nil)
9495 [essential_ addObject:package];
9500 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9503 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9504 [changesItem setBadgeValue:badge];
9505 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9506 [self setApplicationIconBadgeNumber:changes];
9509 [changesItem setBadgeValue:nil];
9510 [changesItem setAnimatedBadge:NO];
9511 [self setApplicationIconBadgeNumber:0];
9517 [self removeProgressHUD:hud];
9520 - (void) updateData {
9524 - (void) updateDataAndLoad {
9526 if ([database_ progressDelegate] == nil)
9532 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9535 - (void) disemulate {
9536 if (emulated_ == nil)
9539 [window_ addSubview:[tabbar_ view]];
9540 [[emulated_ view] removeFromSuperview];
9542 [window_ setUserInteractionEnabled:YES];
9545 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9546 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9548 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9550 UIViewController *parent;
9551 if (emulated_ == nil)
9560 [parent presentModalViewController:navigation animated:YES];
9563 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9564 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9566 if (navigation != nil)
9567 [navigation pushViewController:progress animated:YES];
9569 [self presentModalViewController:progress force:YES];
9571 [progress invoke:invocation withTitle:title];
9575 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9576 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9579 - (void) repairWithInvocation:(NSInvocation *)invocation {
9581 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9585 - (void) repairWithSelector:(SEL)selector {
9586 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9589 - (void) reloadData {
9590 [self reloadDataWithInvocation:nil];
9591 if ([database_ progressDelegate] == nil)
9597 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9600 - (void) addSource:(NSDictionary *) source {
9601 CydiaAddSource(source);
9604 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9605 CydiaAddSource(href, distribution, sections);
9608 - (void) addTrivialSource:(NSString *)href {
9609 CydiaAddSource(href, @"./");
9612 - (void) updateValues {
9617 pkgProblemResolver *resolver = [database_ resolver];
9619 resolver->InstallProtect();
9620 if (!resolver->Resolve(true))
9625 // XXX: this is a really crappy way of doing this.
9626 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9627 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9628 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9629 if ([tabbar_ updating])
9630 [tabbar_ cancelUpdate];
9632 if (![database_ prepare])
9635 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9636 [page setDelegate:self];
9637 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9640 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9641 [tabbar_ presentModalViewController:confirm_ animated:YES];
9647 @synchronized (self) {
9652 - (void) clearPackage:(Package *)package {
9653 @synchronized (self) {
9660 - (void) installPackages:(NSArray *)packages {
9661 @synchronized (self) {
9662 for (Package *package in packages)
9669 - (void) installPackage:(Package *)package {
9670 @synchronized (self) {
9677 - (void) removePackage:(Package *)package {
9678 @synchronized (self) {
9685 - (void) distUpgrade {
9686 @synchronized (self) {
9687 if (![database_ upgrade])
9694 [database_ perform];
9695 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9698 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9701 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9705 - (void) showSettings {
9706 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9709 - (void) retainNetworkActivityIndicator {
9710 if (activity_++ == 0)
9711 [self setNetworkActivityIndicatorVisible:YES];
9714 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9718 - (void) releaseNetworkActivityIndicator {
9719 if (--activity_ == 0)
9720 [self setNetworkActivityIndicatorVisible:NO];
9723 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9728 - (void) cancelAndClear:(bool)clear {
9729 @synchronized (self) {
9741 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9742 NSString *context([alert context]);
9744 if ([context isEqualToString:@"conffile"]) {
9745 FILE *input = [database_ input];
9746 if (button == [alert cancelButtonIndex])
9747 fprintf(input, "N\n");
9748 else if (button == [alert firstOtherButtonIndex])
9749 fprintf(input, "Y\n");
9752 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9753 } else if ([context isEqualToString:@"fixhalf"]) {
9754 if (button == [alert cancelButtonIndex]) {
9755 @synchronized (self) {
9756 for (Package *broken in (id) broken_) {
9759 NSString *id = [broken id];
9760 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9761 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9762 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9763 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9769 } else if (button == [alert firstOtherButtonIndex]) {
9770 [broken_ removeAllObjects];
9774 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9775 } else if ([context isEqualToString:@"upgrade"]) {
9776 if (button == [alert firstOtherButtonIndex]) {
9777 @synchronized (self) {
9778 for (Package *essential in (id) essential_)
9779 [essential install];
9784 } else if (button == [alert firstOtherButtonIndex] + 1) {
9786 } else if (button == [alert cancelButtonIndex]) {
9790 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9794 - (void) system:(NSString *)command {
9795 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9798 system([command UTF8String]);
9804 - (void) applicationWillSuspend {
9806 [super applicationWillSuspend];
9809 - (BOOL) isSafeToSuspend {
9812 NSLog(@"isSafeToSuspend: locked_ != 0");
9817 // Use external process status API internally.
9818 // This is probably a really bad idea.
9819 // XXX: what is the point of this? does this solve anything at all?
9820 uint64_t status = 0;
9822 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9823 notify_get_state(notify_token, &status);
9824 notify_cancel(notify_token);
9829 NSLog(@"isSafeToSuspend: status != 0");
9835 NSLog(@"isSafeToSuspend: -> true");
9840 - (void) applicationSuspend:(__GSEvent *)event {
9841 if ([self isSafeToSuspend])
9842 [super applicationSuspend:event];
9845 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9846 if ([self isSafeToSuspend])
9847 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9850 - (void) _setSuspended:(BOOL)value {
9851 if ([self isSafeToSuspend])
9852 [super _setSuspended:value];
9855 - (UIProgressHUD *) addProgressHUD {
9856 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9857 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9859 [window_ setUserInteractionEnabled:NO];
9861 UIViewController *target(tabbar_);
9862 if (UIViewController *modal = [target modalViewController])
9865 [hud showInView:[target view]];
9871 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9874 [hud removeFromSuperview];
9875 [window_ setUserInteractionEnabled:YES];
9878 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9879 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9882 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9883 NSString *scheme([[url scheme] lowercaseString]);
9884 if ([[url absoluteString] length] <= [scheme length] + 3)
9886 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9887 NSArray *components([path componentsSeparatedByString:@"/"]);
9889 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9890 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9891 if (controller != nil)
9892 [controller setDelegate:self];
9896 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9899 NSString *base([components objectAtIndex:0]);
9901 CyteViewController *controller = nil;
9903 if ([base isEqualToString:@"url"]) {
9904 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9905 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9906 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9907 } else if (!external && [components count] == 1) {
9908 if ([base isEqualToString:@"manage"]) {
9909 controller = [[[ManageController alloc] init] autorelease];
9912 if ([base isEqualToString:@"storage"]) {
9913 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9916 if ([base isEqualToString:@"sources"]) {
9917 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9920 if ([base isEqualToString:@"home"]) {
9921 controller = [[[HomeController alloc] init] autorelease];
9924 if ([base isEqualToString:@"sections"]) {
9925 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9928 if ([base isEqualToString:@"search"]) {
9929 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9932 if ([base isEqualToString:@"changes"]) {
9933 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9936 if ([base isEqualToString:@"installed"]) {
9937 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9939 } else if ([components count] == 2) {
9940 NSString *argument = [components objectAtIndex:1];
9942 if ([base isEqualToString:@"package"]) {
9943 controller = [self pageForPackage:argument withReferrer:referrer];
9946 if (!external && [base isEqualToString:@"search"]) {
9947 controller = [[[SearchController alloc] initWithDatabase:database_ query:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9950 if (!external && [base isEqualToString:@"sections"]) {
9951 if ([argument isEqualToString:@"all"])
9953 controller = [[[SectionController alloc] initWithDatabase:database_ section:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9956 if (!external && [base isEqualToString:@"sources"]) {
9957 if ([argument isEqualToString:@"add"]) {
9958 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9959 [(SourcesController *)controller showAddSourcePrompt];
9961 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9962 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9966 if (!external && [base isEqualToString:@"launch"]) {
9967 [self launchApplicationWithIdentifier:argument suspended:NO];
9970 } else if (!external && [components count] == 3) {
9971 NSString *arg1 = [components objectAtIndex:1];
9972 NSString *arg2 = [components objectAtIndex:2];
9974 if ([base isEqualToString:@"package"]) {
9975 if ([arg2 isEqualToString:@"settings"]) {
9976 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9977 } else if ([arg2 isEqualToString:@"files"]) {
9978 if (Package *package = [database_ packageWithName:arg1]) {
9979 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9980 [(FileTable *)controller setPackage:package];
9986 [controller setDelegate:self];
9990 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9991 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9994 [tabbar_ setUnselectedViewController:page];
9999 - (void) applicationOpenURL:(NSURL *)url {
10000 [super applicationOpenURL:url];
10005 [self openCydiaURL:url forExternal:YES];
10008 - (void) applicationWillResignActive:(UIApplication *)application {
10009 // Stop refreshing if you get a phone call or lock the device.
10010 if ([tabbar_ updating])
10011 [tabbar_ cancelUpdate];
10013 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
10014 [super applicationWillResignActive:application];
10017 - (void) saveState {
10018 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
10019 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
10020 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
10023 [self _saveConfig];
10026 - (void) applicationWillTerminate:(UIApplication *)application {
10030 - (void) setConfigurationData:(NSString *)data {
10031 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
10033 if (!conffile_r(data)) {
10034 lprintf("E:invalid conffile\n");
10038 NSString *ofile = conffile_r[1];
10039 //NSString *nfile = conffile_r[2];
10041 UIAlertView *alert = [[[UIAlertView alloc]
10042 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
10043 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
10045 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
10047 UCLocalize("ACCEPT_NEW_COPY"),
10048 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
10052 [alert setContext:@"conffile"];
10053 [alert setNumberOfRows:2];
10057 - (void) addStashController {
10059 stash_ = [[[StashController alloc] init] autorelease];
10060 [window_ addSubview:[stash_ view]];
10063 - (void) removeStashController {
10064 [[stash_ view] removeFromSuperview];
10070 [self setIdleTimerDisabled:YES];
10072 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
10073 UpdateExternalStatus(1);
10074 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
10075 UpdateExternalStatus(0);
10077 [self removeStashController];
10079 pid_t pid(ExecFork());
10081 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
10082 perror("launchctl stop");
10089 - (void) setupViewControllers {
10090 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
10092 NSMutableArray *items([NSMutableArray arrayWithObjects:
10093 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
10094 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
10095 [[[UITabBarItem alloc] initWithTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES")) image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
10096 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
10100 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
10101 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10103 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10106 NSMutableArray *controllers([NSMutableArray array]);
10107 for (UITabBarItem *item in items) {
10108 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
10109 [controller setTabBarItem:item];
10110 [controllers addObject:controller];
10112 [tabbar_ setViewControllers:controllers];
10114 [tabbar_ setUpdateDelegate:self];
10117 - (void) _sendMemoryWarningNotification {
10118 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
10119 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
10121 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
10124 - (void) _sendMemoryWarningNotifications {
10126 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
10132 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
10134 [[NSURLCache sharedURLCache] removeAllCachedResponses];
10137 - (void) applicationDidFinishLaunching:(id)unused {
10138 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
10141 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
10142 [self setApplicationSupportsShakeToEdit:NO];
10144 @synchronized (HostConfig_) {
10145 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
10148 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
10149 initWithMemoryCapacity:524288
10150 diskCapacity:10485760
10151 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
10154 [CydiaWebViewController _initialize];
10156 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
10158 // this would disallow http{,s} URLs from accessing this data
10159 //[WebView registerURLSchemeAsLocal:@"cydia"];
10161 Font12_ = [UIFont systemFontOfSize:12];
10162 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
10163 Font14_ = [UIFont systemFontOfSize:14];
10164 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
10165 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
10167 essential_ = [NSMutableArray arrayWithCapacity:4];
10168 broken_ = [NSMutableArray arrayWithCapacity:4];
10170 // XXX: I really need this thing... like, seriously... I'm sorry
10171 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
10173 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
10174 [window_ orderFront:self];
10175 [window_ makeKey:self];
10176 [window_ setHidden:NO];
10179 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
10180 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
10181 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
10182 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
10183 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
10184 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
10185 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
10186 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
10187 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
10190 [self addStashController];
10191 // XXX: this would be much cleaner as a yieldToSelector:
10192 // that way the removeStashController could happen right here inline
10193 // we also could no longer require the useless stash_ field anymore
10194 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
10198 database_ = [Database sharedInstance];
10199 [database_ setDelegate:self];
10201 [window_ setUserInteractionEnabled:NO];
10202 [self setupViewControllers];
10204 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
10205 [window_ addSubview:[emulated_ view]];
10207 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
10211 - (NSArray *) defaultStartPages {
10212 NSMutableArray *standard = [NSMutableArray array];
10213 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
10214 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
10215 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
10217 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
10219 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
10220 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
10222 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10226 - (void) loadData {
10228 if (Role_ == nil) {
10229 [window_ setUserInteractionEnabled:YES];
10230 [self showSettings];
10233 if ([emulated_ modalViewController] != nil)
10234 [emulated_ dismissModalViewControllerAnimated:YES];
10235 [window_ setUserInteractionEnabled:NO];
10238 [self reloadDataWithInvocation:nil];
10239 [self refreshIfPossible];
10244 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
10245 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
10246 int standardIndex = 0;
10247 NSArray *standard = [self defaultStartPages];
10254 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
10255 if (valid && closed != nil) {
10256 NSTimeInterval interval([closed timeIntervalSinceNow]);
10257 // XXX: Is 30 minutes the optimal time here?
10258 if (interval <= -(30*60))
10262 if (valid && [saved count] != [standard count])
10266 for (unsigned int i = 0; i < [standard count]; i++) {
10267 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10268 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10269 // but it's good enough for now.
10270 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10277 NSArray *items = nil;
10279 [tabbar_ setSelectedIndex:savedIndex];
10282 [tabbar_ setSelectedIndex:standardIndex];
10286 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10287 NSArray *stack = [items objectAtIndex:tab];
10288 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10289 NSMutableArray *current = [NSMutableArray array];
10291 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10292 NSString *addr = [stack objectAtIndex:nav];
10293 NSURL *url = [NSURL URLWithString:addr];
10294 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10296 [current addObject:page];
10299 [navigation setViewControllers:current];
10302 // (Try to) show the startup URL.
10303 if (starturl_ != nil) {
10304 [self openCydiaURL:starturl_ forExternal:NO];
10309 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10310 if (item != nil && IsWildcat_) {
10311 [sheet showFromBarButtonItem:item animated:YES];
10313 [sheet showInView:window_];
10317 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10318 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10319 [progress setTitle:task];
10320 [progress addProgressEvent:event];
10323 - (void) addProgressEventForTask:(NSArray *)data {
10324 CydiaProgressEvent *event([data objectAtIndex:0]);
10325 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10326 [self addProgressEvent:event forTask:task];
10329 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10330 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10336 id Alloc_(id self, SEL selector) {
10337 id object = alloc_(self, selector);
10338 lprintf("[%s]A-%p\n", self->isa->name, object);
10343 id Dealloc_(id self, SEL selector) {
10344 id object = dealloc_(self, selector);
10345 lprintf("[%s]D-%p\n", self->isa->name, object);
10349 Class $WebDefaultUIKitDelegate;
10351 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
10352 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
10353 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
10354 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
10357 static NSSet *MobilizedFiles_;
10359 static NSURL *MobilizeURL(NSURL *url) {
10360 NSString *path([url path]);
10361 if ([path hasPrefix:@"/var/root/"]) {
10362 NSString *file([path substringFromIndex:10]);
10363 if ([MobilizedFiles_ containsObject:file])
10364 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10370 Class $CFXPreferencesPropertyListSource;
10371 @class CFXPreferencesPropertyListSource;
10373 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10374 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10375 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10376 url = MobilizeURL(url);
10377 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10378 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10384 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10385 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10386 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10387 url = MobilizeURL(url);
10388 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10389 //NSLog(@"%@ %@", [url absoluteString], value);
10395 Class $NSURLConnection;
10397 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10398 NSMutableURLRequest *copy([request mutableCopy]);
10400 NSURL *url([copy URL]);
10402 NSString *host([url host]);
10403 NSString *scheme([[url scheme] lowercaseString]);
10405 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10407 @synchronized (HostConfig_) {
10408 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10409 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10410 [copy setHTTPShouldUsePipelining:YES];
10412 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10413 if ([control isEqualToString:@"max-age=0"])
10414 if ([CachedURLs_ containsObject:url]) {
10416 NSLog(@"~~~: %@", url);
10419 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10421 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10422 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10423 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10427 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10433 static CGSize $WAKWindow$screenSize(WAKWindow self, SEL _cmd) {
10434 CGSize size([[UIScreen mainScreen] bounds].size);
10435 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10436 if ([$WAKWindow hasLandscapeOrientation])
10437 std::swap(size.width, size.height);*/
10441 int main(int argc, char *argv[]) {
10442 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10446 UpdateExternalStatus(0);
10448 if (Class $UIDevice = objc_getClass("UIDevice")) {
10449 UIDevice *device([$UIDevice currentDevice]);
10450 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10452 IsWildcat_ = false;
10454 UIScreen *screen([UIScreen mainScreen]);
10455 if ([screen respondsToSelector:@selector(scale)])
10456 ScreenScale_ = [screen scale];
10460 UIDevice *device([UIDevice currentDevice]);
10461 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10462 Idiom_ = @"iphone";
10464 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10465 if (idiom == UIUserInterfaceIdiomPhone)
10466 Idiom_ = @"iphone";
10467 else if (idiom == UIUserInterfaceIdiomPad)
10470 NSLog(@"unknown UIUserInterfaceIdiom!");
10473 Pcre pattern("^([0-9]+\\.[0-9]+)");
10475 if (pattern([device systemVersion]))
10476 Firmware_ = pattern[1];
10477 if (pattern(Cydia_))
10478 Major_ = pattern[1];
10480 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10482 HostConfig_ = [[[NSObject alloc] init] autorelease];
10483 @synchronized (HostConfig_) {
10484 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10485 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10486 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10487 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10488 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10491 NSString *ui(@"ui/ios");
10493 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10494 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10495 UI_ = CydiaURL(ui);
10497 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10499 MobilizedFiles_ = [NSMutableSet setWithObjects:
10500 @"Library/Preferences/com.apple.Accessibility.plist",
10501 @"Library/Preferences/com.apple.preferences.sounds.plist",
10504 /* Library Hacks {{{ */
10505 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10507 $WAKWindow = objc_getClass("WAKWindow");
10508 if ($WAKWindow != NULL)
10509 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10510 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10512 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10514 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10515 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10516 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10517 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10520 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10521 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10522 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10523 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10526 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10527 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10528 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10529 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10530 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10533 $NSURLConnection = objc_getClass("NSURLConnection");
10534 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10535 if (NSURLConnection$init$ != NULL) {
10536 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10537 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10540 /* Set Locale {{{ */
10541 Locale_ = CFLocaleCopyCurrent();
10542 Languages_ = [NSLocale preferredLanguages];
10544 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10545 //NSLog(@"%@", [Languages_ description]);
10548 if (Locale_ != NULL)
10549 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10550 else if (Languages_ != nil && [Languages_ count] != 0)
10551 lang = [[Languages_ objectAtIndex:0] UTF8String];
10553 // XXX: consider just setting to C and then falling through?
10556 if (lang != NULL) {
10557 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10558 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10561 NSLog(@"Setting Language: %s", lang);
10563 if (lang != NULL) {
10564 setenv("LANG", lang, true);
10565 std::setlocale(LC_ALL, lang);
10569 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10571 /* Parse Arguments {{{ */
10572 bool substrate(false);
10578 for (int argi(1); argi != argc; ++argi)
10579 if (strcmp(argv[argi], "--") == 0) {
10581 argv[argi] = argv[0];
10587 for (int argi(1); argi != arge; ++argi)
10588 if (strcmp(args[argi], "--substrate") == 0)
10591 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10595 App_ = [[NSBundle mainBundle] bundlePath];
10601 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10602 alloc_ = alloc->method_imp;
10603 alloc->method_imp = (IMP) &Alloc_;*/
10605 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10606 dealloc_ = dealloc->method_imp;
10607 dealloc->method_imp = (IMP) &Dealloc_;*/
10609 /* System Information {{{ */
10613 size = sizeof(maxproc);
10614 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10615 perror("sysctlbyname(\"kern.maxproc\", ?)");
10616 else if (maxproc < 64) {
10618 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10619 perror("sysctlbyname(\"kern.maxproc\", #)");
10622 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10623 char *osversion = new char[size];
10624 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10625 perror("sysctlbyname(\"kern.osversion\", ?)");
10627 System_ = [NSString stringWithUTF8String:osversion];
10629 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10630 char *machine = new char[size];
10631 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10632 perror("sysctlbyname(\"hw.machine\", ?)");
10634 Machine_ = machine;
10636 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10637 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10638 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10640 UniqueID_ = [device uniqueIdentifier];
10642 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10643 Product_ = [info objectForKey:@"SafariProductVersion"];
10644 Safari_ = [info objectForKey:@"CFBundleVersion"];
10647 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10649 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10650 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10651 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10652 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10653 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10654 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10656 UserAgent_ = agent;
10658 /* Load Database {{{ */
10660 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10662 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10664 if (Metadata_ == NULL)
10665 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10667 Settings_ = [Metadata_ objectForKey:@"Settings"];
10669 Packages_ = [Metadata_ objectForKey:@"Packages"];
10671 Values_ = [Metadata_ objectForKey:@"Values"];
10672 Sections_ = [Metadata_ objectForKey:@"Sections"];
10673 Sources_ = [Metadata_ objectForKey:@"Sources"];
10675 Token_ = [Metadata_ objectForKey:@"Token"];
10677 Version_ = [Metadata_ objectForKey:@"Version"];
10680 if (Settings_ != nil)
10681 Role_ = [Settings_ objectForKey:@"Role"];
10683 if (Values_ == nil) {
10684 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10685 [Metadata_ setObject:Values_ forKey:@"Values"];
10688 if (Sections_ == nil) {
10689 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10690 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10693 if (Sources_ == nil) {
10694 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10695 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10698 if (Version_ == nil) {
10699 Version_ = [NSNumber numberWithUnsignedInt:0];
10700 [Metadata_ setObject:Version_ forKey:@"Version"];
10703 if ([Version_ unsignedIntValue] == 0) {
10704 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10705 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10706 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10707 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10709 Version_ = [NSNumber numberWithUnsignedInt:1];
10710 [Metadata_ setObject:Version_ forKey:@"Version"];
10712 [Metadata_ removeObjectForKey:@"LastUpdate"];
10718 CydiaWriteSources();
10721 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10724 if (Packages_ != nil) {
10726 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10730 [Metadata_ removeObjectForKey:@"Packages"];
10736 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10738 #define MobileSubstrate_(name) \
10739 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10740 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10741 if (handle == NULL) \
10742 NSLog(@"%s", dlerror()); \
10745 MobileSubstrate_(Activator)
10746 MobileSubstrate_(libstatusbar)
10747 MobileSubstrate_(SimulatedKeyEvents)
10748 MobileSubstrate_(WinterBoard)
10750 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10751 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10753 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10755 if (access("/User", F_OK) != 0 || version != 5) {
10757 system("/usr/libexec/cydia/firmware.sh");
10761 _assert([[NSFileManager defaultManager]
10762 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10763 withIntermediateDirectories:YES
10768 if (access("/tmp/cydia.chk", F_OK) == 0) {
10769 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10770 _assert(errno == ENOENT);
10771 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10772 _assert(errno == ENOENT);
10775 /* APT Initialization {{{ */
10776 _assert(pkgInitConfig(*_config));
10777 _assert(pkgInitSystem(*_config, _system));
10780 _config->Set("APT::Acquire::Translation", lang);
10782 // XXX: this timeout might be important :(
10783 //_config->Set("Acquire::http::Timeout", 15);
10785 _config->Set("Acquire::http::MaxParallel", 3);
10787 /* Color Choices {{{ */
10788 space_ = CGColorSpaceCreateDeviceRGB();
10790 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10791 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10792 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10793 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10794 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10795 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10796 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10797 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10798 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10800 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10801 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10803 /* UIKit Configuration {{{ */
10804 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10805 if ($GSFontSetUseLegacyFontMetrics != NULL)
10806 $GSFontSetUseLegacyFontMetrics(YES);
10808 // XXX: I have a feeling this was important
10809 //UIKeyboardDisableAutomaticAppearance();
10812 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemHasCapability"));
10813 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10815 ShowPromoted_ = fast;
10816 PulseInterval_ = fast ? 50000 : 500000;
10818 Colon_ = UCLocalize("COLON_DELIMITED");
10819 Elision_ = UCLocalize("ELISION");
10820 Error_ = UCLocalize("ERROR");
10821 Warning_ = UCLocalize("WARNING");
10824 AprilFools_ = true;
10826 CFGregorianDate date(CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem()));
10827 AprilFools_ = date.month == 4 && date.day == 1;
10831 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10833 CGColorSpaceRelease(space_);
10834 CFRelease(Locale_);