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>
70 #include <QuartzCore/CAAnimation.h>
71 #include <QuartzCore/CAMediaTimingFunction.h>
73 #include <WebCore/WebCoreThread.h>
80 #include <ext/stdio_filebuf.h>
84 #include <apt-pkg/acquire.h>
85 #include <apt-pkg/acquire-item.h>
86 #include <apt-pkg/algorithms.h>
87 #include <apt-pkg/cachefile.h>
88 #include <apt-pkg/clean.h>
89 #include <apt-pkg/configuration.h>
90 #include <apt-pkg/debindexfile.h>
91 #include <apt-pkg/debmetaindex.h>
92 #include <apt-pkg/error.h>
93 #include <apt-pkg/init.h>
94 #include <apt-pkg/mmap.h>
95 #include <apt-pkg/pkgrecords.h>
96 #include <apt-pkg/sha1.h>
97 #include <apt-pkg/sourcelist.h>
98 #include <apt-pkg/sptr.h>
99 #include <apt-pkg/strutl.h>
100 #include <apt-pkg/tagfile.h>
102 #include <apr-1/apr_pools.h>
104 #include <sys/types.h>
105 #include <sys/stat.h>
106 #include <sys/sysctl.h>
107 #include <sys/param.h>
108 #include <sys/mount.h>
109 #include <sys/reboot.h>
116 #include <mach-o/nlist.h>
125 #include <Cytore.hpp>
128 #include <CydiaSubstrate/CydiaSubstrate.h>
129 #include "Menes/Menes.h"
131 #include "CyteKit/IndirectDelegate.h"
132 #include "CyteKit/PerlCompatibleRegEx.hpp"
133 #include "CyteKit/TableViewCell.h"
134 #include "CyteKit/WebScriptObject-Cyte.h"
135 #include "CyteKit/WebViewController.h"
136 #include "CyteKit/WebViewTableViewCell.h"
137 #include "CyteKit/stringWithUTF8Bytes.h"
139 #include "Cydia/MIMEAddress.h"
140 #include "Cydia/LoadingViewController.h"
141 #include "Cydia/ProgressEvent.h"
143 #include "SDURLCache/SDURLCache.h"
150 #define _timestamp ({ \
152 gettimeofday(&tv, NULL); \
153 tv.tv_sec * 1000000 + tv.tv_usec; \
156 typedef std::vector<class ProfileTime *> TimeList;
166 ProfileTime(const char *name) :
170 times_.push_back(this);
173 void AddTime(uint64_t time) {
180 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
192 ProfileTimer(ProfileTime &time) :
199 time_.AddTime(_timestamp - start_);
204 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
206 std::cerr << "========" << std::endl;
209 #define _profile(name) { \
210 static ProfileTime name(#name); \
211 ProfileTimer _ ## name(name);
216 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
217 #define synchronized(lock) \
218 synchronized(static_cast<NSObject *>(lock))
220 extern NSString *Cydia_;
222 #define lprintf(args...) fprintf(stderr, args)
225 #define TraceLogging (1 && !ForRelease)
226 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
227 #define ProfileTimes (0 && !ForRelease)
228 #define ForSaurik (0 && !ForRelease)
229 #define LogBrowser (0 && !ForRelease)
230 #define TrackResize (0 && !ForRelease)
231 #define ManualRefresh (1 && !ForRelease)
232 #define ShowInternals (0 && !ForRelease)
233 #define AlwaysReload (0 && !ForRelease)
237 #define _trace(args...)
242 #define _profile(name) {
245 #define PrintTimes() do {} while (false)
248 // Hash Functions/Structures {{{
249 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
257 static bool ShowPromoted_;
259 static NSString *Colon_;
261 static NSString *Error_;
262 static NSString *Warning_;
264 static bool AprilFools_;
266 static bool IsReachable(const char *name) {
267 SCNetworkReachabilityFlags flags; {
268 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
269 SCNetworkReachabilityGetFlags(reachability, &flags);
270 CFRelease(reachability);
273 // XXX: this elaborate mess is what Apple is using to determine this? :(
274 // XXX: do we care if the user has to intervene? maybe that's ok?
276 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
277 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
278 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
279 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
280 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
281 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
286 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
288 static _finline NSString *CydiaURL(NSString *path) {
290 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
291 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
292 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
293 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
294 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
296 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
299 static void ReapZombie(pid_t pid) {
302 if (waitpid(pid, &status, 0) == -1)
308 static _finline void UpdateExternalStatus(uint64_t newStatus) {
310 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
311 notify_set_state(notify_token, newStatus);
312 notify_cancel(notify_token);
314 notify_post("com.saurik.Cydia.status");
317 static CGFloat CYStatusBarHeight() {
318 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
319 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
322 /* NSForcedOrderingSearch doesn't work on the iPhone */
323 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
324 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
325 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
327 /* Insertion Sort {{{ */
329 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
330 const char *ptr = (const char *)list;
332 CFIndex half = count / 2;
333 const char *probe = ptr + elementSize * half;
334 CFComparisonResult cr = comparator(element, probe, context);
335 if (0 == cr) return (probe - (const char *)list) / elementSize;
336 ptr = (cr < 0) ? ptr : probe + elementSize;
337 count = (cr < 0) ? half : (half + (count & 1) - 1);
339 return (ptr - (const char *)list) / elementSize;
342 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
343 const char *ptr = (const char *)list;
345 CFIndex half = count / 2;
346 const char *probe = ptr + elementSize * half;
347 CFComparisonResult cr = comparator(element, probe, context);
348 if (0 == cr) return (probe - (const char *)list) / elementSize;
349 ptr = (cr < 0) ? ptr : probe + elementSize;
350 count = (cr < 0) ? half : (half + (count & 1) - 1);
352 return (ptr - (const char *)list) / elementSize;
355 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
356 if (range.length == 0)
358 const void **values(new const void *[range.length]);
359 CFArrayGetValues(array, range, values);
361 #if HistogramInsertionSort > 0
362 uint32_t total(0), *offsets(new uint32_t[range.length]);
365 for (CFIndex index(1); index != range.length; ++index) {
366 const void *value(values[index]);
367 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
368 CFIndex correct(index);
369 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
370 #if HistogramInsertionSort > 1
371 NSLog(@"%@ < %@", value, values[correct - 1]);
376 if (correct != index) {
377 size_t offset(index - correct);
378 #if HistogramInsertionSort
382 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
384 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
385 values[correct] = value;
389 CFArrayReplaceValues(array, range, values, range.length);
392 #if HistogramInsertionSort > 0
393 for (CFIndex index(0); index != range.length; ++index)
394 if (offsets[index] != 0)
395 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
396 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
403 /* Apple Bug Fixes {{{ */
404 @implementation UIWebDocumentView (Cydia)
406 - (void) _setScrollerOffset:(CGPoint)offset {
407 UIScroller *scroller([self _scroller]);
409 CGSize size([scroller contentSize]);
410 CGSize bounds([scroller bounds].size);
413 max.x = size.width - bounds.width;
414 max.y = size.height - bounds.height;
422 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
423 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
425 [scroller setOffset:offset];
431 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
432 size_t length([self length] - state->state);
435 else if (length > count)
437 for (size_t i(0); i != length; ++i)
438 objects[i] = [self item:state->state++];
439 state->itemsPtr = objects;
440 state->mutationsPtr = (unsigned long *) self;
444 /* Cydia NSString Additions {{{ */
445 @interface NSString (Cydia)
446 - (NSComparisonResult) compareByPath:(NSString *)other;
447 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
450 @implementation NSString (Cydia)
452 - (NSComparisonResult) compareByPath:(NSString *)other {
453 NSString *prefix = [self commonPrefixWithString:other options:0];
454 size_t length = [prefix length];
456 NSRange lrange = NSMakeRange(length, [self length] - length);
457 NSRange rrange = NSMakeRange(length, [other length] - length);
459 lrange = [self rangeOfString:@"/" options:0 range:lrange];
460 rrange = [other rangeOfString:@"/" options:0 range:rrange];
462 NSComparisonResult value;
464 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
465 value = NSOrderedSame;
466 else if (lrange.location == NSNotFound)
467 value = NSOrderedAscending;
468 else if (rrange.location == NSNotFound)
469 value = NSOrderedDescending;
471 value = NSOrderedSame;
473 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
474 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
475 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
476 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
478 NSComparisonResult result = [lpath compare:rpath];
479 return result == NSOrderedSame ? value : result;
482 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
483 return [(id)CFURLCreateStringByAddingPercentEscapes(
488 kCFStringEncodingUTF8
495 /* C++ NSString Wrapper Cache {{{ */
496 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
497 return size == 0 ? NULL :
498 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
499 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
502 static _finline CFStringRef CYStringCreate(const char *data) {
503 return CYStringCreate(data, strlen(data));
512 _finline void clear_() {
513 if (cache_ != NULL) {
520 _finline bool empty() const {
524 _finline size_t size() const {
528 _finline char *data() const {
532 _finline void clear() {
537 _finline CYString() :
544 _finline ~CYString() {
548 void operator =(const CYString &rhs) {
552 if (rhs.cache_ == nil)
555 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
558 void copy(apr_pool_t *pool) {
559 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
560 memcpy(temp, data_, size_);
565 void set(apr_pool_t *pool, const char *data, size_t size) {
571 data_ = const_cast<char *>(data);
579 _finline void set(apr_pool_t *pool, const char *data) {
580 set(pool, data, data == NULL ? 0 : strlen(data));
583 _finline void set(apr_pool_t *pool, const std::string &rhs) {
584 set(pool, rhs.data(), rhs.size());
587 bool operator ==(const CYString &rhs) const {
588 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
591 _finline operator CFStringRef() {
593 cache_ = CYStringCreate(data_, size_);
597 _finline operator id() {
598 return (NSString *) static_cast<CFStringRef>(*this);
601 _finline operator const char *() {
602 return reinterpret_cast<const char *>(data_);
606 /* C++ NSString Algorithm Adapters {{{ */
608 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
611 struct NSStringMapHash :
612 std::unary_function<NSString *, size_t>
614 _finline size_t operator ()(NSString *value) const {
615 return CFStringHashNSString((CFStringRef) value);
619 struct NSStringMapLess :
620 std::binary_function<NSString *, NSString *, bool>
622 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
623 return [lhs compare:rhs] == NSOrderedAscending;
627 struct NSStringMapEqual :
628 std::binary_function<NSString *, NSString *, bool>
630 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
631 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
632 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
633 //[lhs isEqualToString:rhs];
638 /* CoreGraphics Primitives {{{ */
643 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
644 CGFloat color[] = {red, green, blue, alpha};
645 return CGColorCreate(space, color);
654 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
655 color_(Create_(space, red, green, blue, alpha))
657 Set(space, red, green, blue, alpha);
662 CGColorRelease(color_);
669 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
671 color_ = Create_(space, red, green, blue, alpha);
674 operator CGColorRef() {
680 /* Random Global Variables {{{ */
681 static int PulseInterval_ = 500000;
683 static const NSString *UI_;
686 static bool RestartSubstrate_;
687 static NSArray *Finishes_;
689 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
690 #define NotifyConfig_ "/etc/notify.conf"
692 static CYColor Blue_;
693 static CYColor Blueish_;
694 static CYColor Black_;
696 static CYColor White_;
697 static CYColor Gray_;
698 static CYColor Green_;
699 static CYColor Purple_;
700 static CYColor Purplish_;
702 static UIColor *InstallingColor_;
703 static UIColor *RemovingColor_;
705 static NSString *App_;
707 static BOOL Advanced_;
708 static BOOL Ignored_;
710 static _H<UIFont> Font12_;
711 static _H<UIFont> Font12Bold_;
712 static _H<UIFont> Font14_;
713 static _H<UIFont> Font18Bold_;
714 static _H<UIFont> Font22Bold_;
716 static const char *Machine_ = NULL;
717 static _H<NSString> System_;
718 static NSString *SerialNumber_ = nil;
719 static NSString *ChipID_ = nil;
720 static NSString *BBSNum_ = nil;
721 static _H<NSString> Token_;
722 static NSString *UniqueID_ = nil;
723 static _H<NSString> UserAgent_;
724 static _H<NSString> Product_;
725 static _H<NSString> Safari_;
727 static CFLocaleRef Locale_;
728 static NSArray *Languages_;
729 static CGColorSpaceRef space_;
731 static NSDictionary *SectionMap_;
732 static NSMutableDictionary *Metadata_;
733 static _transient NSMutableDictionary *Settings_;
734 static _transient NSString *Role_;
735 static _transient NSMutableDictionary *Packages_;
736 static _transient NSMutableDictionary *Values_;
737 static _transient NSMutableDictionary *Sections_;
738 _H<NSMutableDictionary> Sources_;
739 static _transient NSNumber *Version_;
744 static CGFloat ScreenScale_;
745 static NSString *Idiom_;
746 static _H<NSString> Firmware_;
747 static NSString *Major_;
749 static _H<NSMutableDictionary> SessionData_;
750 static _H<NSObject> HostConfig_;
751 static _H<NSMutableSet> BridgedHosts_;
752 static _H<NSMutableSet> TokenHosts_;
753 static _H<NSMutableSet> InsecureHosts_;
754 static _H<NSMutableSet> PipelinedHosts_;
755 static _H<NSMutableSet> CachedURLs_;
757 static NSString *kCydiaProgressEventTypeError = @"Error";
758 static NSString *kCydiaProgressEventTypeInformation = @"Information";
759 static NSString *kCydiaProgressEventTypeStatus = @"Status";
760 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
763 /* Display Helpers {{{ */
764 inline float Interpolate(float begin, float end, float fraction) {
765 return (end - begin) * fraction + begin;
768 static _finline const char *StripVersion_(const char *version) {
769 const char *colon(strchr(version, ':'));
770 return colon == NULL ? version : colon + 1;
773 NSString *LocalizeSection(NSString *section) {
774 static Pcre title_r("^(.*?) \\((.*)\\)$");
775 if (title_r(section)) {
776 NSString *parent(title_r[1]);
777 NSString *child(title_r[2]);
779 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
780 LocalizeSection(parent),
781 LocalizeSection(child)
785 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
788 NSString *Simplify(NSString *title) {
789 const char *data = [title UTF8String];
790 size_t size = [title length];
792 static Pcre square_r("^\\[(.*)\\]$");
793 if (square_r(data, size))
794 return Simplify(square_r[1]);
796 static Pcre paren_r("^\\((.*)\\)$");
797 if (paren_r(data, size))
798 return Simplify(paren_r[1]);
800 static Pcre title_r("^(.*?) \\((.*)\\)$");
801 if (title_r(data, size))
802 return Simplify(title_r[1]);
808 NSString *GetLastUpdate() {
809 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
812 return UCLocalize("NEVER_OR_UNKNOWN");
814 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
815 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
817 CFRelease(formatter);
819 return [(NSString *) formatted autorelease];
822 bool isSectionVisible(NSString *section) {
823 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
824 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
825 return hidden == nil || ![hidden boolValue];
828 static NSObject *CYIOGetValue(const char *path, NSString *property) {
829 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
830 if (entry == MACH_PORT_NULL)
833 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
834 IOObjectRelease(entry);
838 return [(id) value autorelease];
841 static NSString *CYHex(NSData *data, bool reverse = false) {
845 size_t length([data length]);
846 uint8_t bytes[length];
847 [data getBytes:bytes];
849 char string[length * 2 + 1];
850 for (size_t i(0); i != length; ++i)
851 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
853 return [NSString stringWithUTF8String:string];
858 /* Delegate Prototypes {{{ */
861 @class CydiaProgressEvent;
863 @protocol DatabaseDelegate
864 - (void) repairWithSelector:(SEL)selector;
865 - (void) setConfigurationData:(NSString *)data;
866 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
869 @class CYPackageController;
871 @protocol CydiaDelegate
872 - (void) returnToCydia;
874 - (void) retainNetworkActivityIndicator;
875 - (void) releaseNetworkActivityIndicator;
876 - (void) clearPackage:(Package *)package;
877 - (void) installPackage:(Package *)package;
878 - (void) installPackages:(NSArray *)packages;
879 - (void) removePackage:(Package *)package;
880 - (void) beginUpdate;
882 - (void) distUpgrade;
885 - (void) _saveConfig;
887 - (void) addSource:(NSDictionary *)source;
888 - (void) addTrivialSource:(NSString *)href;
889 - (void) showSettings;
890 - (UIProgressHUD *) addProgressHUD;
891 - (void) removeProgressHUD:(UIProgressHUD *)hud;
892 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
893 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
897 /* Status Delegation {{{ */
899 public pkgAcquireStatus
902 _transient NSObject<ProgressDelegate> *delegate_;
912 void setDelegate(NSObject<ProgressDelegate> *delegate) {
913 delegate_ = delegate;
916 NSObject<ProgressDelegate> *getDelegate() const {
920 virtual bool MediaChange(std::string media, std::string drive) {
924 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
928 virtual void Fetch(pkgAcquire::ItemDesc &item) {
929 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
930 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
931 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
934 virtual void Done(pkgAcquire::ItemDesc &item) {
935 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
936 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
937 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
940 virtual void Fail(pkgAcquire::ItemDesc &item) {
942 item.Owner->Status == pkgAcquire::Item::StatIdle ||
943 item.Owner->Status == pkgAcquire::Item::StatDone
947 std::string &error(item.Owner->ErrorText);
951 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
952 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
955 virtual bool Pulse(pkgAcquire *Owner) {
956 bool value = pkgAcquireStatus::Pulse(Owner);
959 double(CurrentBytes + CurrentItems) /
960 double(TotalBytes + TotalItems)
963 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
964 [NSNumber numberWithDouble:percent], @"Percent",
966 [NSNumber numberWithDouble:CurrentBytes], @"Current",
967 [NSNumber numberWithDouble:TotalBytes], @"Total",
968 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
969 nil] waitUntilDone:YES];
971 if (value && ![delegate_ isProgressCancelled])
979 _finline bool WasCancelled() const {
983 virtual void Start() {
984 pkgAcquireStatus::Start();
985 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
988 virtual void Stop() {
989 pkgAcquireStatus::Stop();
990 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
991 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
995 /* Database Interface {{{ */
996 typedef std::map< unsigned long, _H<Source> > SourceMap;
998 @interface Database : NSObject {
1004 pkgCacheFile cache_;
1005 pkgDepCache::Policy *policy_;
1006 pkgRecords *records_;
1007 pkgProblemResolver *resolver_;
1008 pkgAcquire *fetcher_;
1010 SPtr<pkgPackageManager> manager_;
1011 pkgSourceList *list_;
1013 SourceMap sourceMap_;
1014 _H<NSMutableArray> sourceList_;
1016 CFMutableArrayRef packages_;
1018 _transient NSObject<DatabaseDelegate> *delegate_;
1019 _transient NSObject<ProgressDelegate> *progress_;
1027 std::map<const char *, _H<NSString> > sections_;
1030 + (Database *) sharedInstance;
1033 - (void) _readCydia:(NSNumber *)fd;
1034 - (void) _readStatus:(NSNumber *)fd;
1035 - (void) _readOutput:(NSNumber *)fd;
1039 - (Package *) packageWithName:(NSString *)name;
1041 - (pkgCacheFile &) cache;
1042 - (pkgDepCache::Policy *) policy;
1043 - (pkgRecords *) records;
1044 - (pkgProblemResolver *) resolver;
1045 - (pkgAcquire &) fetcher;
1046 - (pkgSourceList &) list;
1047 - (NSArray *) packages;
1048 - (NSArray *) sources;
1049 - (Source *) sourceWithKey:(NSString *)key;
1050 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1058 - (void) updateWithStatus:(Status &)status;
1060 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1062 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1063 - (NSObject<ProgressDelegate> *) progressDelegate;
1065 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1067 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1071 /* ProgressEvent Implementation {{{ */
1072 @implementation CydiaProgressEvent
1074 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1075 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1078 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1079 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1080 [event setPackage:package];
1084 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1085 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1087 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1088 NSArray *fields([description componentsSeparatedByString:@" "]);
1089 [event setItem:fields];
1091 if ([fields count] > 3) {
1092 [event setPackage:[fields objectAtIndex:2]];
1093 [event setVersion:[fields objectAtIndex:3]];
1096 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1101 + (NSArray *) _attributeKeys {
1102 return [NSArray arrayWithObjects:
1112 - (NSArray *) attributeKeys {
1113 return [[self class] _attributeKeys];
1116 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1117 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1120 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1121 if ((self = [super init]) != nil) {
1127 - (NSString *) message {
1131 - (NSString *) type {
1135 - (NSArray *) item {
1136 return (id) item_ ?: [NSNull null];
1139 - (void) setItem:(NSArray *)item {
1143 - (NSString *) package {
1144 return (id) package_ ?: [NSNull null];
1147 - (void) setPackage:(NSString *)package {
1151 - (NSString *) url {
1152 return (id) url_ ?: [NSNull null];
1155 - (void) setURL:(NSString *)url {
1159 - (void) setVersion:(NSString *)version {
1163 - (NSString *) version {
1164 return (id) version_ ?: [NSNull null];
1167 - (NSString *) compound:(NSString *)value {
1169 NSString *mode(nil); {
1170 NSString *type([self type]);
1171 if ([type isEqualToString:kCydiaProgressEventTypeError])
1172 mode = UCLocalize("ERROR");
1173 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1174 mode = UCLocalize("WARNING");
1178 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1184 - (NSString *) compoundMessage {
1185 return [self compound:[self message]];
1188 - (NSString *) compoundTitle {
1191 if (package_ == nil)
1193 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1194 title = [package name];
1198 return [self compound:title];
1204 // Cytore Definitions {{{
1205 struct PackageValue :
1208 Cytore::Offset<PackageValue> next_;
1210 uint32_t index_ : 23;
1211 uint32_t subscribed_ : 1;
1228 Cytore::Offset<PackageValue> packages_[1 << 16];
1231 static Cytore::File<MetaValue> MetaFile_;
1233 // Cytore Helper Functions {{{
1234 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1235 SplitHash nhash = { hashlittle(name, length) };
1237 PackageValue *metadata;
1239 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1240 offset: if (offset->IsNull()) {
1241 *offset = MetaFile_.New<PackageValue>(length + 1);
1242 metadata = &MetaFile_.Get(*offset);
1244 if (metadata == NULL) {
1248 metadata = new PackageValue();
1249 memset(metadata, 0, sizeof(*metadata));
1252 memcpy(metadata->name_, name, length + 1);
1253 metadata->nhash_ = nhash.u16[1];
1255 metadata = &MetaFile_.Get(*offset);
1257 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1258 offset = &metadata->next_;
1266 static void PackageImport(const void *key, const void *value, void *context) {
1267 bool &fail(*reinterpret_cast<bool *>(context));
1270 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1271 NSLog(@"failed to import package %@", key);
1275 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1276 NSDictionary *package((NSDictionary *) value);
1278 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1279 if ([subscribed boolValue] && !metadata->subscribed_)
1280 metadata->subscribed_ = true;
1282 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1283 time_t time([date timeIntervalSince1970]);
1284 if (metadata->first_ > time || metadata->first_ == 0)
1285 metadata->first_ = time;
1288 NSDate *date([package objectForKey:@"LastSeen"]);
1289 NSString *version([package objectForKey:@"LastVersion"]);
1291 if (date != nil && version != nil) {
1292 time_t time([date timeIntervalSince1970]);
1293 if (metadata->last_ < time || metadata->last_ == 0)
1294 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1295 size_t length(strlen(buffer));
1296 uint16_t vhash(hashlittle(buffer, length));
1298 size_t capped(std::min<size_t>(8, length));
1299 char *latest(buffer + length - capped);
1301 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1302 metadata->vhash_ = vhash;
1304 metadata->last_ = time;
1310 /* Source Class {{{ */
1311 @interface Source : NSObject {
1313 Database *database_;
1316 CYString depiction_;
1317 CYString description_;
1323 CYString distribution_;
1329 _H<NSString> authority_;
1331 CYString defaultIcon_;
1333 _H<NSMutableDictionary> record_;
1337 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1339 - (NSComparisonResult) compareByName:(Source *)source;
1341 - (NSString *) depictionForPackage:(NSString *)package;
1342 - (NSString *) supportForPackage:(NSString *)package;
1344 - (metaIndex *) metaIndex;
1345 - (NSDictionary *) record;
1348 - (NSString *) rooturi;
1349 - (NSString *) distribution;
1350 - (NSString *) type;
1353 - (NSString *) host;
1355 - (NSString *) name;
1356 - (NSString *) shortDescription;
1357 - (NSString *) label;
1358 - (NSString *) origin;
1359 - (NSString *) version;
1361 - (NSString *) defaultIcon;
1362 - (NSURL *) iconURL;
1366 @implementation Source
1370 distribution_.clear();
1375 description_.clear();
1381 defaultIcon_.clear();
1388 + (NSString *) webScriptNameForSelector:(SEL)selector {
1390 else if (selector == @selector(addSection:))
1391 return @"addSection";
1392 else if (selector == @selector(getField:))
1394 else if (selector == @selector(removeSection:))
1395 return @"removeSection";
1396 else if (selector == @selector(remove))
1402 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1403 return [self webScriptNameForSelector:selector] == nil;
1406 + (NSArray *) _attributeKeys {
1407 return [NSArray arrayWithObjects:
1418 @"shortDescription",
1425 - (NSArray *) attributeKeys {
1426 return [[self class] _attributeKeys];
1429 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1430 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1433 - (metaIndex *) metaIndex {
1437 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1440 trusted_ = index->IsTrusted();
1442 uri_.set(pool, index->GetURI());
1443 distribution_.set(pool, index->GetDist());
1444 type_.set(pool, index->GetType());
1446 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1447 if (dindex != NULL) {
1448 base_.set(pool, dindex->MetaIndexURI(""));
1451 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1454 pkgTagFile tags(&fd);
1456 pkgTagSection section;
1463 {"default-icon", &defaultIcon_},
1464 {"depiction", &depiction_},
1465 {"description", &description_},
1467 {"origin", &origin_},
1468 {"support", &support_},
1469 {"version", &version_},
1472 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1473 const char *start, *end;
1475 if (section.Find(names[i].name_, start, end)) {
1476 CYString &value(*names[i].value_);
1477 value.set(pool, start, end - start);
1483 record_ = [Sources_ objectForKey:[self key]];
1485 NSURL *url([NSURL URLWithString:uri_]);
1489 host_ = [host_ lowercaseString];
1494 authority_ = [url path];
1497 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1498 if ((self = [super init]) != nil) {
1499 era_ = [database era];
1500 database_ = database;
1503 [self setMetaIndex:index inPool:pool];
1507 - (NSString *) getField:(NSString *)name {
1508 @synchronized (database_) {
1509 if ([database_ era] != era_ || index_ == NULL)
1512 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1517 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1522 pkgTagFile tags(&fd);
1524 pkgTagSection section;
1527 const char *start, *end;
1528 if (!section.Find([name UTF8String], start, end))
1529 return (NSString *) [NSNull null];
1531 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1534 - (NSComparisonResult) compareByName:(Source *)source {
1535 NSString *lhs = [self name];
1536 NSString *rhs = [source name];
1538 if ([lhs length] != 0 && [rhs length] != 0) {
1539 unichar lhc = [lhs characterAtIndex:0];
1540 unichar rhc = [rhs characterAtIndex:0];
1542 if (isalpha(lhc) && !isalpha(rhc))
1543 return NSOrderedAscending;
1544 else if (!isalpha(lhc) && isalpha(rhc))
1545 return NSOrderedDescending;
1548 return [lhs compare:rhs options:LaxCompareOptions_];
1551 - (NSString *) depictionForPackage:(NSString *)package {
1552 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1555 - (NSString *) supportForPackage:(NSString *)package {
1556 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1559 - (NSArray *) sections {
1560 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1563 - (void) _addSection:(NSString *)section {
1566 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1567 if (![sections containsObject:section]) {
1568 [sections addObject:section];
1572 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1577 - (bool) addSection:(NSString *)section {
1581 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1585 - (void) _removeSection:(NSString *)section {
1589 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1590 if ([sections containsObject:section]) {
1591 [sections removeObject:section];
1596 - (bool) removeSection:(NSString *)section {
1600 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1605 [Sources_ removeObjectForKey:[self key]];
1610 bool value(record_ != nil);
1611 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1615 - (NSDictionary *) record {
1623 - (NSString *) rooturi {
1627 - (NSString *) distribution {
1628 return distribution_;
1631 - (NSString *) type {
1635 - (NSString *) baseuri {
1636 return base_.empty() ? nil : (id) base_;
1639 - (NSString *) iconuri {
1640 if (NSString *base = [self baseuri])
1641 return [base stringByAppendingString:@"CydiaIcon.png"];
1646 - (NSURL *) iconURL {
1647 if (NSString *uri = [self iconuri])
1648 return [NSURL URLWithString:uri];
1652 - (NSString *) key {
1653 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1656 - (NSString *) host {
1660 - (NSString *) name {
1661 return origin_.empty() ? (id) authority_ : origin_;
1664 - (NSString *) shortDescription {
1665 return description_;
1668 - (NSString *) label {
1669 return label_.empty() ? (id) authority_ : label_;
1672 - (NSString *) origin {
1676 - (NSString *) version {
1680 - (NSString *) defaultIcon {
1681 return defaultIcon_;
1686 /* CydiaOperation Class {{{ */
1687 @interface CydiaOperation : NSObject {
1688 _H<NSString> operator_;
1689 _H<NSString> value_;
1692 - (NSString *) operator;
1693 - (NSString *) value;
1697 @implementation CydiaOperation
1699 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1700 if ((self = [super init]) != nil) {
1701 operator_ = [NSString stringWithUTF8String:_operator];
1702 value_ = [NSString stringWithUTF8String:value];
1706 + (NSArray *) _attributeKeys {
1707 return [NSArray arrayWithObjects:
1713 - (NSArray *) attributeKeys {
1714 return [[self class] _attributeKeys];
1717 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1718 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1721 - (NSString *) operator {
1725 - (NSString *) value {
1731 /* CydiaClause Class {{{ */
1732 @interface CydiaClause : NSObject {
1733 _H<NSString> package_;
1734 _H<CydiaOperation> version_;
1737 - (NSString *) package;
1738 - (CydiaOperation *) version;
1742 @implementation CydiaClause
1744 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1745 if ((self = [super init]) != nil) {
1746 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1748 if (const char *version = dep.TargetVer())
1749 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1751 version_ = (id) [NSNull null];
1755 + (NSArray *) _attributeKeys {
1756 return [NSArray arrayWithObjects:
1762 - (NSArray *) attributeKeys {
1763 return [[self class] _attributeKeys];
1766 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1767 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1770 - (NSString *) package {
1774 - (CydiaOperation *) version {
1780 /* CydiaRelation Class {{{ */
1781 @interface CydiaRelation : NSObject {
1782 _H<NSString> relationship_;
1783 _H<NSMutableArray> clauses_;
1786 - (NSString *) relationship;
1787 - (NSArray *) clauses;
1791 @implementation CydiaRelation
1793 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1794 if ((self = [super init]) != nil) {
1795 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1796 clauses_ = [NSMutableArray arrayWithCapacity:8];
1798 pkgCache::DepIterator start;
1799 pkgCache::DepIterator end;
1800 dep.GlobOr(start, end); // ++dep
1803 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1805 // yes, seriously. (wtf?)
1813 + (NSArray *) _attributeKeys {
1814 return [NSArray arrayWithObjects:
1820 - (NSArray *) attributeKeys {
1821 return [[self class] _attributeKeys];
1824 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1825 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1828 - (NSString *) relationship {
1829 return relationship_;
1832 - (NSArray *) clauses {
1836 - (void) addClause:(CydiaClause *)clause {
1837 [clauses_ addObject:clause];
1842 /* Package Class {{{ */
1843 struct ParsedPackage {
1847 CYString architecture_;
1850 CYString depiction_;
1860 @interface Package : NSObject {
1863 uint32_t essential_ : 1;
1864 uint32_t obsolete_ : 1;
1865 uint32_t ignored_ : 1;
1866 uint32_t pooled_ : 1;
1872 _transient Database *database_;
1874 pkgCache::VerIterator version_;
1875 pkgCache::PkgIterator iterator_;
1876 pkgCache::VerFileIterator file_;
1882 CYString installed_;
1884 const char *section_;
1885 _transient NSString *section$_;
1889 PackageValue *metadata_;
1890 ParsedPackage *parsed_;
1892 _H<NSMutableArray> tags_;
1895 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1896 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1898 - (pkgCache::PkgIterator) iterator;
1901 - (NSString *) section;
1902 - (NSString *) simpleSection;
1904 - (NSString *) longSection;
1905 - (NSString *) shortSection;
1909 - (MIMEAddress *) maintainer;
1911 - (NSString *) longDescription;
1912 - (NSString *) shortDescription;
1915 - (PackageValue *) metadata;
1918 - (bool) subscribed;
1919 - (bool) setSubscribed:(bool)subscribed;
1923 - (NSString *) latest;
1924 - (NSString *) installed;
1925 - (BOOL) uninstalled;
1928 - (BOOL) upgradableAndEssential:(BOOL)essential;
1931 - (BOOL) unfiltered;
1935 - (BOOL) halfConfigured;
1936 - (BOOL) halfInstalled;
1938 - (NSString *) mode;
1941 - (NSString *) name;
1943 - (NSString *) homepage;
1944 - (NSString *) depiction;
1945 - (MIMEAddress *) author;
1947 - (NSString *) support;
1949 - (NSArray *) files;
1950 - (NSArray *) warnings;
1951 - (NSArray *) applications;
1953 - (Source *) source;
1956 - (BOOL) matches:(NSArray *)query;
1958 - (bool) hasSupportingRole;
1959 - (BOOL) hasTag:(NSString *)tag;
1960 - (NSString *) primaryPurpose;
1961 - (NSArray *) purposes;
1962 - (bool) isCommercial;
1964 - (void) setIndex:(size_t)index;
1966 - (CYString &) cyname;
1968 - (uint32_t) compareBySection:(NSArray *)sections;
1973 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1974 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1975 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1976 - (bool) isVisibleInSection:(NSString *)section;
1977 - (bool) isVisibleInSource:(Source *)source;
1981 uint32_t PackageChangesRadix(Package *self, void *) {
1986 uint32_t timestamp : 30;
1987 uint32_t ignored : 1;
1988 uint32_t upgradable : 1;
1992 bool upgradable([self upgradableAndEssential:YES]);
1993 value.bits.upgradable = upgradable ? 1 : 0;
1996 value.bits.timestamp = 0;
1997 value.bits.ignored = [self ignored] ? 0 : 1;
1998 value.bits.upgradable = 1;
2000 value.bits.timestamp = [self seen] >> 2;
2001 value.bits.ignored = 0;
2002 value.bits.upgradable = 0;
2005 return _not(uint32_t) - value.key;
2008 uint32_t PackagePrefixRadix(Package *self, void *context) {
2009 size_t offset(reinterpret_cast<size_t>(context));
2010 CYString &name([self cyname]);
2012 size_t size(name.size());
2015 char *text(name.data());
2018 if (!isdigit(text[0]))
2022 while (size != digits && isdigit(text[digits]))
2030 if (offset == 0 && zeros != 0) {
2031 memset(data, '0', zeros);
2032 memcpy(data + zeros, text, 4 - zeros);
2034 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2035 if (size <= offset - zeros)
2038 text += offset - zeros;
2039 size -= offset - zeros;
2042 memcpy(data, text, 4);
2044 memcpy(data, text, size);
2045 memset(data + size, 0, 4 - size);
2048 for (size_t i(0); i != 4; ++i)
2049 if (isalpha(data[i]))
2057 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2059 /* XXX: ntohl may be more honest */
2060 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2063 CYString &(*PackageName)(Package *self, SEL sel);
2065 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2066 _profile(PackageNameCompare)
2067 CYString &lhi(PackageName(lhs, @selector(cyname)));
2068 CYString &rhi(PackageName(rhs, @selector(cyname)));
2069 CFStringRef lhn(lhi), rhn(rhi);
2072 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2073 else if (rhn == NULL)
2074 return NSOrderedDescending;
2076 _profile(PackageNameCompare$NumbersLast)
2077 if (!lhi.empty() && !rhi.empty()) {
2078 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2079 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2080 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2081 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2082 return lha ? NSOrderedAscending : NSOrderedDescending;
2086 CFIndex length = CFStringGetLength(lhn);
2088 _profile(PackageNameCompare$Compare)
2089 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2094 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2095 return PackageNameCompare(*lhs, *rhs, context);
2098 struct PackageNameOrdering :
2099 std::binary_function<Package *, Package *, bool>
2101 _finline bool operator ()(Package *lhs, Package *rhs) const {
2102 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2106 @implementation Package
2108 - (NSString *) description {
2109 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2114 apr_pool_destroy(pool_);
2115 if (parsed_ != NULL)
2120 + (NSString *) webScriptNameForSelector:(SEL)selector {
2122 else if (selector == @selector(clear))
2124 else if (selector == @selector(getField:))
2126 else if (selector == @selector(hasTag:))
2128 else if (selector == @selector(install))
2130 else if (selector == @selector(remove))
2136 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2137 return [self webScriptNameForSelector:selector] == nil;
2140 + (NSArray *) _attributeKeys {
2141 return [NSArray arrayWithObjects:
2162 @"shortDescription",
2175 - (NSArray *) attributeKeys {
2176 return [[self class] _attributeKeys];
2179 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2180 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2183 - (NSArray *) relations {
2184 @synchronized (database_) {
2185 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2186 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2187 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2191 - (NSString *) architecture {
2193 @synchronized (database_) {
2194 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2197 - (NSString *) getField:(NSString *)name {
2198 @synchronized (database_) {
2199 if ([database_ era] != era_ || file_.end())
2202 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2204 const char *start, *end;
2205 if (!parser.Find([name UTF8String], start, end))
2206 return (NSString *) [NSNull null];
2208 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2212 if (parsed_ != NULL)
2214 @synchronized (database_) {
2215 if ([database_ era] != era_ || file_.end())
2218 ParsedPackage *parsed(new ParsedPackage);
2221 _profile(Package$parse)
2222 pkgRecords::Parser *parser;
2224 _profile(Package$parse$Lookup)
2225 parser = &[database_ records]->Lookup(file_);
2230 _profile(Package$parse$Find)
2235 {"architecture", &parsed->architecture_},
2236 {"icon", &parsed->icon_},
2237 {"depiction", &parsed->depiction_},
2238 {"homepage", &parsed->homepage_},
2239 {"website", &website},
2240 {"bugs", &parsed->bugs_},
2241 {"support", &parsed->support_},
2242 {"sponsor", &parsed->sponsor_},
2243 {"author", &parsed->author_},
2244 {"md5sum", &parsed->md5sum_},
2247 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2248 const char *start, *end;
2250 if (parser->Find(names[i].name_, start, end)) {
2251 CYString &value(*names[i].value_);
2252 _profile(Package$parse$Value)
2253 value.set(pool_, start, end - start);
2259 _profile(Package$parse$Tagline)
2260 const char *start, *end;
2261 if (parser->ShortDesc(start, end)) {
2262 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2265 while (stop != start && stop[-1] == '\r')
2267 parsed->tagline_.set(pool_, start, stop - start);
2271 _profile(Package$parse$Retain)
2272 if (parsed->homepage_.empty())
2273 parsed->homepage_ = website;
2274 if (parsed->homepage_ == parsed->depiction_)
2275 parsed->homepage_.clear();
2280 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2281 if ((self = [super init]) != nil) {
2282 _profile(Package$initWithVersion)
2284 apr_pool_create(&pool_, NULL);
2290 database_ = database;
2291 era_ = [database era];
2295 pkgCache::PkgIterator iterator(version.ParentPkg());
2296 iterator_ = iterator;
2298 _profile(Package$initWithVersion$Version)
2299 if (!version_.end())
2300 file_ = version_.FileList();
2302 pkgCache &cache([database_ cache]);
2303 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2307 _profile(Package$initWithVersion$Cache)
2308 name_.set(NULL, iterator.Display());
2310 latest_.set(NULL, StripVersion_(version_.VerStr()));
2312 pkgCache::VerIterator current(iterator.CurrentVer());
2314 installed_.set(NULL, StripVersion_(current.VerStr()));
2317 _profile(Package$initWithVersion$Tags)
2318 pkgCache::TagIterator tag(iterator.TagList());
2320 tags_ = [NSMutableArray arrayWithCapacity:8];
2322 const char *name(tag.Name());
2323 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2325 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2326 if (strcmp(name + 6, "enduser") == 0)
2328 else if (strcmp(name + 6, "hacker") == 0)
2330 else if (strcmp(name + 6, "developer") == 0)
2332 else if (strcmp(name + 6, "cydia") == 0)
2338 if (strncmp(name, "cydia::", 7) == 0) {
2339 if (strcmp(name + 7, "essential") == 0)
2341 else if (strcmp(name + 7, "obsolete") == 0)
2346 } while (!tag.end());
2350 _profile(Package$initWithVersion$Metadata)
2351 const char *mixed(iterator.Name());
2352 size_t size(strlen(mixed));
2353 char lower[size + 1];
2355 for (size_t i(0); i != size; ++i)
2356 lower[i] = mixed[i] | 0x20;
2359 PackageValue *metadata(PackageFind(lower, size));
2360 metadata_ = metadata;
2362 id_.set(NULL, metadata->name_, size);
2364 const char *latest(version_.VerStr());
2365 size_t length(strlen(latest));
2367 uint16_t vhash(hashlittle(latest, length));
2369 size_t capped(std::min<size_t>(8, length));
2370 latest = latest + length - capped;
2372 if (metadata->first_ == 0)
2373 metadata->first_ = now_;
2375 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2376 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2377 metadata->vhash_ = vhash;
2378 metadata->last_ = now_;
2379 } else if (metadata->last_ == 0)
2380 metadata->last_ = metadata->first_;
2383 _profile(Package$initWithVersion$Section)
2384 section_ = version_.Section();
2387 _profile(Package$initWithVersion$Flags)
2388 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2389 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2394 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2395 pkgCache::VerIterator version;
2397 _profile(Package$packageWithIterator$GetCandidateVer)
2398 version = [database policy]->GetCandidateVer(iterator);
2406 _profile(Package$packageWithIterator$Allocate)
2407 package = [Package allocWithZone:zone];
2410 _profile(Package$packageWithIterator$Initialize)
2412 initWithVersion:version
2419 _profile(Package$packageWithIterator$Autorelease)
2420 package = [package autorelease];
2426 - (pkgCache::PkgIterator) iterator {
2430 - (NSString *) section {
2431 if (section$_ == nil) {
2432 if (section_ == NULL)
2435 _profile(Package$section$mappedSectionForPointer)
2436 section$_ = [database_ mappedSectionForPointer:section_];
2441 - (NSString *) simpleSection {
2442 if (NSString *section = [self section])
2443 return Simplify(section);
2448 - (NSString *) longSection {
2449 return LocalizeSection([self section]);
2452 - (NSString *) shortSection {
2453 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2456 - (NSString *) uri {
2459 pkgIndexFile *index;
2460 pkgCache::PkgFileIterator file(file_.File());
2461 if (![database_ list].FindIndex(file, index))
2463 return [NSString stringWithUTF8String:iterator_->Path];
2464 //return [NSString stringWithUTF8String:file.Site()];
2465 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2469 - (MIMEAddress *) maintainer {
2470 @synchronized (database_) {
2471 if ([database_ era] != era_ || file_.end())
2474 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2475 const std::string &maintainer(parser->Maintainer());
2476 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2479 - (NSString *) md5sum {
2480 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2484 @synchronized (database_) {
2485 if ([database_ era] != era_ || version_.end())
2488 return version_->InstalledSize;
2491 - (NSString *) longDescription {
2492 @synchronized (database_) {
2493 if ([database_ era] != era_ || file_.end())
2496 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2497 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2499 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2500 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2501 if ([lines count] < 2)
2504 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2505 for (size_t i(1), e([lines count]); i != e; ++i) {
2506 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2507 [trimmed addObject:trim];
2510 return [trimmed componentsJoinedByString:@"\n"];
2513 - (NSString *) shortDescription {
2514 if (parsed_ != NULL)
2515 return static_cast<NSString *>(parsed_->tagline_);
2517 @synchronized (database_) {
2518 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2520 const char *start, *end;
2521 if (!parser.ShortDesc(start, end))
2524 if (end - start > 200)
2528 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2531 while (end != start && end[-1] == '\r')
2535 return [(id) CYStringCreate(start, end - start) autorelease];
2539 _profile(Package$index)
2540 CFStringRef name((CFStringRef) [self name]);
2541 if (CFStringGetLength(name) == 0)
2543 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2544 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2546 return toupper(character);
2550 - (PackageValue *) metadata {
2555 PackageValue *metadata([self metadata]);
2556 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2559 - (bool) subscribed {
2560 return [self metadata]->subscribed_;
2563 - (bool) setSubscribed:(bool)subscribed {
2564 PackageValue *metadata([self metadata]);
2565 if (metadata->subscribed_ == subscribed)
2567 metadata->subscribed_ = subscribed;
2575 - (NSString *) latest {
2579 - (NSString *) installed {
2583 - (BOOL) uninstalled {
2584 return installed_.empty();
2588 return !version_.end();
2591 - (BOOL) upgradableAndEssential:(BOOL)essential {
2592 _profile(Package$upgradableAndEssential)
2593 pkgCache::VerIterator current(iterator_.CurrentVer());
2595 return essential && essential_;
2597 return !version_.end() && version_ != current;
2601 - (BOOL) essential {
2606 return [database_ cache][iterator_].InstBroken();
2609 - (BOOL) unfiltered {
2610 _profile(Package$unfiltered$obsolete)
2611 if (_unlikely(obsolete_))
2615 _profile(Package$unfiltered$hasSupportingRole)
2616 if (_unlikely(![self hasSupportingRole]))
2624 if (![self unfiltered])
2629 _profile(Package$visible$section)
2630 section = [self section];
2633 _profile(Package$visible$isSectionVisible)
2634 if (!isSectionVisible(section))
2642 unsigned char current(iterator_->CurrentState);
2643 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2646 - (BOOL) halfConfigured {
2647 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2650 - (BOOL) halfInstalled {
2651 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2655 @synchronized (database_) {
2656 if ([database_ era] != era_ || iterator_.end())
2659 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2660 return state.Mode != pkgDepCache::ModeKeep;
2663 - (NSString *) mode {
2664 @synchronized (database_) {
2665 if ([database_ era] != era_ || iterator_.end())
2668 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2670 switch (state.Mode) {
2671 case pkgDepCache::ModeDelete:
2672 if ((state.iFlags & pkgDepCache::Purge) != 0)
2676 case pkgDepCache::ModeKeep:
2677 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2678 return @"REINSTALL";
2679 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2683 case pkgDepCache::ModeInstall:
2684 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2685 return @"REINSTALL";
2686 else*/ switch (state.Status) {
2688 return @"DOWNGRADE";
2694 return @"NEW_INSTALL";
2705 - (NSString *) name {
2706 return name_.empty() ? id_ : name_;
2709 - (UIImage *) icon {
2710 NSString *section = [self simpleSection];
2713 if (parsed_ != NULL)
2714 if (NSString *href = parsed_->icon_)
2715 if ([href hasPrefix:@"file:///"])
2716 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2717 if (icon == nil) if (section != nil)
2718 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2719 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2720 if ([dicon hasPrefix:@"file:///"])
2721 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2723 icon = [UIImage applicationImageNamed:@"unknown.png"];
2727 - (NSString *) homepage {
2728 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2731 - (NSString *) depiction {
2732 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2735 - (MIMEAddress *) sponsor {
2736 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2739 - (MIMEAddress *) author {
2740 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2743 - (NSString *) support {
2744 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2747 - (NSArray *) files {
2748 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2749 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2752 fin.open([path UTF8String]);
2757 while (std::getline(fin, line))
2758 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2763 - (NSString *) state {
2764 @synchronized (database_) {
2765 if ([database_ era] != era_ || file_.end())
2768 switch (iterator_->CurrentState) {
2769 case pkgCache::State::NotInstalled:
2770 return @"NotInstalled";
2771 case pkgCache::State::UnPacked:
2773 case pkgCache::State::HalfConfigured:
2774 return @"HalfConfigured";
2775 case pkgCache::State::HalfInstalled:
2776 return @"HalfInstalled";
2777 case pkgCache::State::ConfigFiles:
2778 return @"ConfigFiles";
2779 case pkgCache::State::Installed:
2780 return @"Installed";
2781 case pkgCache::State::TriggersAwaited:
2782 return @"TriggersAwaited";
2783 case pkgCache::State::TriggersPending:
2784 return @"TriggersPending";
2787 return (NSString *) [NSNull null];
2790 - (NSString *) selection {
2791 @synchronized (database_) {
2792 if ([database_ era] != era_ || file_.end())
2795 switch (iterator_->SelectedState) {
2796 case pkgCache::State::Unknown:
2798 case pkgCache::State::Install:
2800 case pkgCache::State::Hold:
2802 case pkgCache::State::DeInstall:
2803 return @"DeInstall";
2804 case pkgCache::State::Purge:
2808 return (NSString *) [NSNull null];
2811 - (NSArray *) warnings {
2812 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2813 const char *name(iterator_.Name());
2815 size_t length(strlen(name));
2816 if (length < 2) invalid:
2817 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2818 else for (size_t i(0); i != length; ++i)
2820 /* XXX: technically this is not allowed */
2821 (name[i] < 'A' || name[i] > 'Z') &&
2822 (name[i] < 'a' || name[i] > 'z') &&
2823 (name[i] < '0' || name[i] > '9') &&
2824 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2827 if (strcmp(name, "cydia") != 0) {
2830 bool _private = false;
2833 bool repository = [[self section] isEqualToString:@"Repositories"];
2835 if (NSArray *files = [self files])
2836 for (NSString *file in files)
2837 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2839 else if (!user && [file isEqualToString:@"/User"])
2841 else if (!_private && [file isEqualToString:@"/private"])
2843 else if (!stash && [file isEqualToString:@"/var/stash"])
2846 /* XXX: this is not sensitive enough. only some folders are valid. */
2847 if (cydia && !repository)
2848 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2850 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2852 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2854 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2857 return [warnings count] == 0 ? nil : warnings;
2860 - (NSArray *) applications {
2861 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2863 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2865 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2866 if (NSArray *files = [self files])
2867 for (NSString *file in files)
2868 if (application_r(file)) {
2869 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2870 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2871 if ([id isEqualToString:me])
2874 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2876 display = application_r[1];
2878 NSString *bundle([file stringByDeletingLastPathComponent]);
2879 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2880 if (icon == nil || [icon length] == 0)
2882 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2884 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2885 [applications addObject:application];
2887 [application addObject:id];
2888 [application addObject:display];
2889 [application addObject:url];
2892 return [applications count] == 0 ? nil : applications;
2895 - (Source *) source {
2896 if (source_ == nil) {
2897 @synchronized (database_) {
2898 if ([database_ era] != era_ || file_.end())
2899 source_ = (Source *) [NSNull null];
2901 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2905 return source_ == (Source *) [NSNull null] ? nil : source_;
2912 - (BOOL) matches:(NSArray *)query {
2913 if (query == nil || [query count] == 0)
2922 string = [self name];
2923 length = [string length];
2925 for (NSString *term in query) {
2926 range = [string rangeOfString:term options:MatchCompareOptions_];
2927 if (range.location != NSNotFound)
2928 rank_ -= 6 * 1000000 / length;
2933 length = [string length];
2935 for (NSString *term in query) {
2936 range = [string rangeOfString:term options:MatchCompareOptions_];
2937 if (range.location != NSNotFound)
2938 rank_ -= 6 * 1000000 / length;
2942 string = [self shortDescription];
2943 length = [string length];
2944 NSUInteger stop(std::min<NSUInteger>(length, 200));
2946 for (NSString *term in query) {
2947 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2948 if (range.location != NSNotFound)
2949 rank_ -= 2 * 100000;
2955 - (bool) hasSupportingRole {
2960 if ([Role_ isEqualToString:@"User"])
2964 if ([Role_ isEqualToString:@"Hacker"])
2968 if ([Role_ isEqualToString:@"Developer"])
2973 - (NSArray *) tags {
2977 - (BOOL) hasTag:(NSString *)tag {
2978 return tags_ == nil ? NO : [tags_ containsObject:tag];
2981 - (NSString *) primaryPurpose {
2982 for (NSString *tag in (NSArray *) tags_)
2983 if ([tag hasPrefix:@"purpose::"])
2984 return [tag substringFromIndex:9];
2988 - (NSArray *) purposes {
2989 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2990 for (NSString *tag in (NSArray *) tags_)
2991 if ([tag hasPrefix:@"purpose::"])
2992 [purposes addObject:[tag substringFromIndex:9]];
2993 return [purposes count] == 0 ? nil : purposes;
2996 - (bool) isCommercial {
2997 return [self hasTag:@"cydia::commercial"];
3000 - (void) setIndex:(size_t)index {
3001 if (metadata_->index_ != index)
3002 metadata_->index_ = index;
3005 - (CYString &) cyname {
3006 return name_.empty() ? id_ : name_;
3009 - (uint32_t) compareBySection:(NSArray *)sections {
3010 NSString *section([self section]);
3011 for (size_t i(0), e([sections count]); i != e; ++i) {
3012 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3016 return _not(uint32_t);
3020 @synchronized (database_) {
3021 pkgProblemResolver *resolver = [database_ resolver];
3022 resolver->Clear(iterator_);
3024 pkgCacheFile &cache([database_ cache]);
3025 cache->SetReInstall(iterator_, false);
3026 cache->MarkKeep(iterator_, false);
3030 @synchronized (database_) {
3031 pkgProblemResolver *resolver = [database_ resolver];
3032 resolver->Clear(iterator_);
3033 resolver->Protect(iterator_);
3035 pkgCacheFile &cache([database_ cache]);
3036 cache->SetReInstall(iterator_, false);
3037 cache->MarkInstall(iterator_, false);
3039 pkgDepCache::StateCache &state((*cache)[iterator_]);
3040 if (!state.Install())
3041 cache->SetReInstall(iterator_, true);
3045 @synchronized (database_) {
3046 pkgProblemResolver *resolver = [database_ resolver];
3047 resolver->Clear(iterator_);
3048 resolver->Remove(iterator_);
3049 resolver->Protect(iterator_);
3051 pkgCacheFile &cache([database_ cache]);
3052 cache->SetReInstall(iterator_, false);
3053 cache->MarkDelete(iterator_, true);
3056 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3057 _profile(Package$isUnfilteredAndSearchedForBy)
3060 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3061 value &= [self unfiltered];
3064 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3065 value &= [self matches:query];
3072 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3073 if ([search length] == 0)
3076 _profile(Package$isUnfilteredAndSelectedForBy)
3079 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3080 value &= [self unfiltered];
3083 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3084 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3091 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3092 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3095 - (bool) isVisibleInSection:(NSString *)name {
3096 NSString *section([self section]);
3100 section == nil && [name length] == 0 ||
3101 [name isEqualToString:section]
3102 ) && [self visible];
3105 - (bool) isVisibleInSource:(Source *)source {
3106 return [self source] == source && [self visible];
3111 /* Section Class {{{ */
3112 @interface Section : NSObject {
3117 _H<NSString> localized_;
3120 - (NSComparisonResult) compareByLocalized:(Section *)section;
3121 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3122 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3123 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3124 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3125 - (NSString *) name;
3132 - (void) addToCount;
3134 - (void) setCount:(size_t)count;
3135 - (NSString *) localized;
3139 @implementation Section
3141 - (NSComparisonResult) compareByLocalized:(Section *)section {
3142 NSString *lhs(localized_);
3143 NSString *rhs([section localized]);
3145 /*if ([lhs length] != 0 && [rhs length] != 0) {
3146 unichar lhc = [lhs characterAtIndex:0];
3147 unichar rhc = [rhs characterAtIndex:0];
3149 if (isalpha(lhc) && !isalpha(rhc))
3150 return NSOrderedAscending;
3151 else if (!isalpha(lhc) && isalpha(rhc))
3152 return NSOrderedDescending;
3155 return [lhs compare:rhs options:LaxCompareOptions_];
3158 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3159 if ((self = [self initWithName:name localize:NO]) != nil) {
3160 if (localized != nil)
3161 localized_ = localized;
3165 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3166 return [self initWithName:name row:0 localize:localize];
3169 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3170 if ((self = [super init]) != nil) {
3175 localized_ = LocalizeSection(name_);
3179 /* XXX: localize the index thingees */
3180 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3181 if ((self = [super init]) != nil) {
3182 name_ = [NSString stringWithCharacters:&index length:1];
3188 - (NSString *) name {
3208 - (void) addToCount {
3212 - (void) setCount:(size_t)count {
3216 - (NSString *) localized {
3223 class CydiaLogCleaner :
3224 public pkgArchiveCleaner
3227 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3232 /* Database Implementation {{{ */
3233 @implementation Database
3235 + (Database *) sharedInstance {
3236 static _H<Database> instance;
3237 if (instance == nil)
3238 instance = [[[Database alloc] init] autorelease];
3246 - (void) releasePackages {
3247 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3248 CFArrayRemoveAllValues(packages_);
3252 // XXX: actually implement this thing
3254 [self releasePackages];
3255 apr_pool_destroy(pool_);
3256 NSRecycleZone(zone_);
3260 - (void) _readCydia:(NSNumber *)fd {
3261 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3262 std::istream is(&ib);
3265 static Pcre finish_r("^finish:([^:]*)$");
3267 while (std::getline(is, line)) {
3268 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3270 const char *data(line.c_str());
3271 size_t size = line.size();
3272 lprintf("C:%s\n", data);
3274 if (finish_r(data, size)) {
3275 NSString *finish = finish_r[1];
3276 int index = [Finishes_ indexOfObject:finish];
3277 if (index != INT_MAX && index > Finish_)
3287 - (void) _readStatus:(NSNumber *)fd {
3288 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3289 std::istream is(&ib);
3292 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3293 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3295 while (std::getline(is, line)) {
3296 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3298 const char *data(line.c_str());
3299 size_t size(line.size());
3300 lprintf("S:%s\n", data);
3302 if (conffile_r(data, size)) {
3303 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3304 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3305 } else if (strncmp(data, "status: ", 8) == 0) {
3306 // status: <package>: {unpacked,half-configured,installed}
3307 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3308 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3309 } else if (strncmp(data, "processing: ", 12) == 0) {
3310 // processing: configure: config-test
3311 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3312 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3313 } else if (pmstatus_r(data, size)) {
3314 std::string type([pmstatus_r[1] UTF8String]);
3316 NSString *package = pmstatus_r[2];
3317 if ([package isEqualToString:@"dpkg-exec"])
3320 float percent([pmstatus_r[3] floatValue]);
3321 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3323 NSString *string = pmstatus_r[4];
3325 if (type == "pmerror") {
3326 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3327 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3328 } else if (type == "pmstatus") {
3329 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3330 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3331 } else if (type == "pmconffile")
3332 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3334 lprintf("E:unknown pmstatus\n");
3336 lprintf("E:unknown status\n");
3344 - (void) _readOutput:(NSNumber *)fd {
3345 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3346 std::istream is(&ib);
3349 while (std::getline(is, line)) {
3350 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3352 lprintf("O:%s\n", line.c_str());
3354 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3355 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3367 - (Package *) packageWithName:(NSString *)name {
3370 @synchronized (self) {
3371 if (static_cast<pkgDepCache *>(cache_) == NULL)
3373 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3374 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3378 if ((self = [super init]) != nil) {
3385 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3386 apr_pool_create(&pool_, NULL);
3388 size_t capacity(MetaFile_->active_);
3394 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3395 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3399 _assert(pipe(fds) != -1);
3402 _config->Set("APT::Keep-Fds::", cydiafd_);
3403 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3406 detachNewThreadSelector:@selector(_readCydia:)
3408 withObject:[NSNumber numberWithInt:fds[0]]
3411 _assert(pipe(fds) != -1);
3415 detachNewThreadSelector:@selector(_readStatus:)
3417 withObject:[NSNumber numberWithInt:fds[0]]
3420 _assert(pipe(fds) != -1);
3421 _assert(dup2(fds[0], 0) != -1);
3422 _assert(close(fds[0]) != -1);
3424 input_ = fdopen(fds[1], "a");
3426 _assert(pipe(fds) != -1);
3427 _assert(dup2(fds[1], 1) != -1);
3428 _assert(close(fds[1]) != -1);
3431 detachNewThreadSelector:@selector(_readOutput:)
3433 withObject:[NSNumber numberWithInt:fds[0]]
3438 - (pkgCacheFile &) cache {
3442 - (pkgDepCache::Policy *) policy {
3446 - (pkgRecords *) records {
3450 - (pkgProblemResolver *) resolver {
3454 - (pkgAcquire &) fetcher {
3458 - (pkgSourceList &) list {
3462 - (NSArray *) packages {
3463 return (NSArray *) packages_;
3466 - (NSArray *) sources {
3470 - (Source *) sourceWithKey:(NSString *)key {
3471 for (Source *source in [self sources]) {
3472 if ([[source key] isEqualToString:key])
3477 - (bool) popErrorWithTitle:(NSString *)title {
3480 while (!_error->empty()) {
3482 bool warning(!_error->PopMessage(error));
3487 size_t size(error.size());
3488 if (size == 0 || error[size - 1] != '\n')
3490 error.resize(size - 1);
3493 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3495 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3496 if (warning && no_pubkey(error.c_str()))
3499 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3505 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3506 return [self popErrorWithTitle:title] || !success;
3509 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3510 @synchronized (self) {
3513 [self releasePackages];
3516 [sourceList_ removeAllObjects];
3536 apr_pool_clear(pool_);
3538 NSRecycleZone(zone_);
3539 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3541 int chk(creat("/tmp/cydia.chk", 0644));
3545 if (invocation != nil)
3546 [invocation invoke];
3548 NSString *title(UCLocalize("DATABASE"));
3550 list_ = new pkgSourceList();
3551 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3554 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3555 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3556 [sourceList_ addObject:object];
3560 OpProgress progress;
3562 if (!cache_.Open(progress, true)) {
3563 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3564 while (!_error->empty()) {
3566 bool warning(!_error->PopMessage(error));
3568 lprintf("cache_.Open():[%s]\n", error.c_str());
3570 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3574 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3575 repair = @selector(configure);
3576 //else if (error == "The package lists or status file could not be parsed or opened.")
3577 // repair = @selector(update);
3578 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3579 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3580 // else if (error == "Malformed Status line")
3581 // else if (error == "The list of sources could not be read.")
3583 if (repair != NULL) {
3585 [delegate_ repairWithSelector:repair];
3594 unlink("/tmp/cydia.chk");
3596 now_ = [[NSDate date] timeIntervalSince1970];
3598 policy_ = new pkgDepCache::Policy();
3599 records_ = new pkgRecords(cache_);
3600 resolver_ = new pkgProblemResolver(cache_);
3601 fetcher_ = new pkgAcquire(&status_);
3604 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3605 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3609 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3612 if (cache_->BrokenCount() != 0) {
3613 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3616 if (cache_->BrokenCount() != 0) {
3617 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3621 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3625 for (Source *object in (id) sourceList_) {
3626 metaIndex *source([object metaIndex]);
3627 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3628 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3629 // XXX: this could be more intelligent
3630 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3631 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3633 sourceMap_[cached->ID] = object;
3638 /*std::vector<Package *> packages;
3639 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3644 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3645 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3646 //packages.push_back(package);
3647 CFArrayAppendValue(packages_, CFRetain(package));
3651 /*if (packages.empty())
3652 packages_ = [[NSArray alloc] init];
3654 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3657 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3658 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3659 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3667 /*if (!packages.empty())
3668 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3669 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3671 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3673 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3675 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3679 size_t count(CFArrayGetCount(packages_));
3680 MetaFile_->active_ = count;
3682 for (size_t index(0); index != count; ++index)
3683 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3690 @synchronized (self) {
3692 resolver_ = new pkgProblemResolver(cache_);
3694 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3695 if (!cache_[iterator].Keep())
3696 cache_->MarkKeep(iterator, false);
3697 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3698 cache_->SetReInstall(iterator, false);
3701 - (void) configure {
3702 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3704 system([dpkg UTF8String]);
3709 @synchronized (self) {
3710 // XXX: I don't remember this condition
3715 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3717 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3719 if ([self popErrorWithTitle:title])
3723 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3725 CydiaLogCleaner cleaner;
3726 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3733 fetcher_->Shutdown();
3735 pkgRecords records(cache_);
3737 lock_ = new FileFd();
3738 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3740 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3742 if ([self popErrorWithTitle:title])
3746 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3749 manager_ = (_system->CreatePM(cache_));
3750 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3757 bool substrate(RestartSubstrate_);
3758 RestartSubstrate_ = false;
3760 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3762 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3764 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3766 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3767 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3770 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3772 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3774 [self popErrorWithTitle:title];
3778 bool failed = false;
3779 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3780 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3782 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3785 std::string uri = (*item)->DescURI();
3786 std::string error = (*item)->ErrorText;
3788 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3791 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3792 [delegate_ addProgressEventOnMainThread:event forTask:title];
3795 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3803 RestartSubstrate_ = true;
3806 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3807 if ([self popErrorWithTitle:title])
3810 if (result == pkgPackageManager::Failed) {
3815 if (result != pkgPackageManager::Completed) {
3820 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3822 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3824 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3825 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3828 if (![before isEqualToArray:after])
3833 NSString *title(UCLocalize("UPGRADE"));
3834 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3840 [self updateWithStatus:status_];
3843 - (void) updateWithStatus:(Status &)status {
3844 NSString *title(UCLocalize("REFRESHING_DATA"));
3847 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3851 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3852 if ([self popErrorWithTitle:title])
3855 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3857 bool success(ListUpdate(status, list, PulseInterval_));
3858 if (status.WasCancelled())
3861 [self popErrorWithTitle:title forOperation:success];
3862 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3866 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3869 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3870 delegate_ = delegate;
3873 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3874 progress_ = delegate;
3875 status_.setDelegate(delegate);
3878 - (NSObject<ProgressDelegate> *) progressDelegate {
3882 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3883 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3884 return i == sourceMap_.end() ? nil : i->second;
3887 - (NSString *) mappedSectionForPointer:(const char *)section {
3888 _H<NSString> *mapped;
3890 _profile(Database$mappedSectionForPointer$Cache)
3891 mapped = §ions_[section];
3894 if (*mapped == NULL) {
3895 size_t length(strlen(section));
3896 char spaced[length + 1];
3898 _profile(Database$mappedSectionForPointer$Replace)
3899 for (size_t index(0); index != length; ++index)
3900 spaced[index] = section[index] == '_' ? ' ' : section[index];
3901 spaced[length] = '\0';
3906 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3907 string = [NSString stringWithUTF8String:spaced];
3910 _profile(Database$mappedSectionForPointer$Map)
3911 string = [SectionMap_ objectForKey:string] ?: string;
3921 static _H<NSMutableSet> Diversions_;
3923 @interface Diversion : NSObject {
3926 _H<NSString> format_;
3931 @implementation Diversion
3933 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3934 if ((self = [super init]) != nil) {
3935 pattern_ = [from UTF8String];
3941 - (NSString *) divert:(NSString *)url {
3942 return !pattern_(url) ? nil : pattern_->*format_;
3945 + (NSURL *) divertURL:(NSURL *)url {
3947 NSString *href([url absoluteString]);
3949 for (Diversion *diversion in (id) Diversions_)
3950 if (NSString *diverted = [diversion divert:href]) {
3952 NSLog(@"div: %@", diverted);
3954 url = [NSURL URLWithString:diverted];
3961 - (NSString *) key {
3965 - (NSUInteger) hash {
3969 - (BOOL) isEqual:(Diversion *)object {
3970 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3975 @interface CydiaObject : NSObject {
3976 _H<CyteWebViewController> indirect_;
3977 _transient id delegate_;
3980 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3986 @interface CydiaWebViewController : CyteWebViewController {
3987 _H<CydiaObject> cydia_;
3990 + (void) addDiversion:(Diversion *)diversion;
3991 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
3992 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
3993 - (void) setDelegate:(id)delegate;
3997 /* Web Scripting {{{ */
3998 @implementation CydiaObject
4000 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4001 if ((self = [super init]) != nil) {
4002 indirect_ = (CyteWebViewController *) indirect;
4006 - (void) setDelegate:(id)delegate {
4007 delegate_ = delegate;
4010 + (NSArray *) _attributeKeys {
4011 return [NSArray arrayWithObjects:
4014 @"coreFoundationVersionNumber",
4031 - (NSArray *) attributeKeys {
4032 return [[self class] _attributeKeys];
4035 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4036 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4039 - (NSString *) version {
4043 - (NSString *) build {
4047 - (NSString *) coreFoundationVersionNumber {
4048 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4051 - (NSString *) device {
4052 return [[UIDevice currentDevice] uniqueIdentifier];
4055 - (NSString *) firmware {
4056 return [[UIDevice currentDevice] systemVersion];
4059 - (NSString *) hostname {
4060 return [[UIDevice currentDevice] name];
4063 - (NSString *) idiom {
4064 return (id) Idiom_ ?: [NSNull null];
4067 - (NSString *) mcc {
4068 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4069 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4073 - (NSString *) mnc {
4074 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4075 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4079 - (NSString *) operator {
4080 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4081 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4085 - (NSString *) bbsnum {
4086 return (id) BBSNum_ ?: [NSNull null];
4089 - (NSString *) ecid {
4090 return (id) ChipID_ ?: [NSNull null];
4093 - (NSString *) serial {
4094 return SerialNumber_;
4097 - (NSString *) role {
4098 return (id) Role_ ?: [NSNull null];
4101 - (NSString *) model {
4102 return [NSString stringWithUTF8String:Machine_];
4105 - (NSString *) token {
4106 return (id) Token_ ?: [NSNull null];
4109 + (NSString *) webScriptNameForSelector:(SEL)selector {
4111 else if (selector == @selector(addBridgedHost:))
4112 return @"addBridgedHost";
4113 else if (selector == @selector(addInsecureHost:))
4114 return @"addInsecureHost";
4115 else if (selector == @selector(addInternalRedirect::))
4116 return @"addInternalRedirect";
4117 else if (selector == @selector(addPipelinedHost:scheme:))
4118 return @"addPipelinedHost";
4119 else if (selector == @selector(addSource:::))
4120 return @"addSource";
4121 else if (selector == @selector(addTokenHost:))
4122 return @"addTokenHost";
4123 else if (selector == @selector(addTrivialSource:))
4124 return @"addTrivialSource";
4125 else if (selector == @selector(close))
4127 else if (selector == @selector(du:))
4129 else if (selector == @selector(stringWithFormat:arguments:))
4131 else if (selector == @selector(getAllSources))
4132 return @"getAllSourcs";
4133 else if (selector == @selector(getKernelNumber:))
4134 return @"getKernelNumber";
4135 else if (selector == @selector(getKernelString:))
4136 return @"getKernelString";
4137 else if (selector == @selector(getInstalledPackages))
4138 return @"getInstalledPackages";
4139 else if (selector == @selector(getIORegistryEntry::))
4140 return @"getIORegistryEntry";
4141 else if (selector == @selector(getLocaleIdentifier))
4142 return @"getLocaleIdentifier";
4143 else if (selector == @selector(getPreferredLanguages))
4144 return @"getPreferredLanguages";
4145 else if (selector == @selector(getPackageById:))
4146 return @"getPackageById";
4147 else if (selector == @selector(getMetadataKeys))
4148 return @"getMetadataKeys";
4149 else if (selector == @selector(getMetadataValue:))
4150 return @"getMetadataValue";
4151 else if (selector == @selector(getSessionValue:))
4152 return @"getSessionValue";
4153 else if (selector == @selector(installPackages:))
4154 return @"installPackages";
4155 else if (selector == @selector(isReachable:))
4156 return @"isReachable";
4157 else if (selector == @selector(localizedStringForKey:value:table:))
4159 else if (selector == @selector(popViewController:))
4160 return @"popViewController";
4161 else if (selector == @selector(refreshSources))
4162 return @"refreshSources";
4163 else if (selector == @selector(removeButton))
4164 return @"removeButton";
4165 else if (selector == @selector(saveConfig))
4166 return @"saveConfig";
4167 else if (selector == @selector(setMetadataValue::))
4168 return @"setMetadataValue";
4169 else if (selector == @selector(setSessionValue::))
4170 return @"setSessionValue";
4171 else if (selector == @selector(setShowPromoted:))
4172 return @"setShowPromoted";
4173 else if (selector == @selector(substitutePackageNames:))
4174 return @"substitutePackageNames";
4175 else if (selector == @selector(scrollToBottom:))
4176 return @"scrollToBottom";
4177 else if (selector == @selector(setAllowsNavigationAction:))
4178 return @"setAllowsNavigationAction";
4179 else if (selector == @selector(setBadgeValue:))
4180 return @"setBadgeValue";
4181 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4182 return @"setButtonImage";
4183 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4184 return @"setButtonTitle";
4185 else if (selector == @selector(setHidesBackButton:))
4186 return @"setHidesBackButton";
4187 else if (selector == @selector(setHidesNavigationBar:))
4188 return @"setHidesNavigationBar";
4189 else if (selector == @selector(setNavigationBarStyle:))
4190 return @"setNavigationBarStyle";
4191 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4192 return @"setNavigationBarTintColor";
4193 else if (selector == @selector(setPasteboardString:))
4194 return @"setPasteboardString";
4195 else if (selector == @selector(setPasteboardURL:))
4196 return @"setPasteboardURL";
4197 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4198 return @"setScrollAlwaysBounceVertical";
4199 else if (selector == @selector(setScrollIndicatorStyle:))
4200 return @"setScrollIndicatorStyle";
4201 else if (selector == @selector(setToken:))
4203 else if (selector == @selector(setViewportWidth:))
4204 return @"setViewportWidth";
4205 else if (selector == @selector(statfs:))
4207 else if (selector == @selector(supports:))
4209 else if (selector == @selector(unload))
4215 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4216 return [self webScriptNameForSelector:selector] == nil;
4219 - (BOOL) supports:(NSString *)feature {
4220 return [feature isEqualToString:@"window.open"];
4224 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4227 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4228 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4231 - (void) setScrollIndicatorStyle:(NSString *)style {
4232 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4235 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4236 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4239 - (NSNumber *) getKernelNumber:(NSString *)name {
4240 const char *string([name UTF8String]);
4243 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4244 return (id) [NSNull null];
4246 if (size != sizeof(int))
4247 return (id) [NSNull null];
4250 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4251 return (id) [NSNull null];
4253 return [NSNumber numberWithInt:value];
4256 - (NSString *) getKernelString:(NSString *)name {
4257 const char *string([name UTF8String]);
4260 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4261 return (id) [NSNull null];
4263 char value[size + 1];
4264 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4265 return (id) [NSNull null];
4267 // XXX: just in case you request something ludicrous
4270 return [NSString stringWithCString:value];
4273 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4274 NSObject *value(CYIOGetValue([path UTF8String], entry));
4277 if ([value isKindOfClass:[NSData class]])
4278 value = CYHex((NSData *) value);
4283 - (NSArray *) getMetadataKeys {
4284 @synchronized (Values_) {
4285 return [Values_ allKeys];
4288 - (void) _setShowPromoted:(NSNumber *)value {
4289 [Metadata_ setObject:value forKey:@"ShowPromoted"];
4293 - (void) setShowPromoted:(NSNumber *)value {
4294 [self performSelectorOnMainThread:@selector(_setShowPromoted:) withObject:value waitUntilDone:NO];
4297 - (id) getMetadataValue:(NSString *)key {
4298 @synchronized (Values_) {
4299 return [Values_ objectForKey:key];
4302 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4303 @synchronized (Values_) {
4304 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4305 [Values_ removeObjectForKey:key];
4307 [Values_ setObject:value forKey:key];
4309 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4312 - (id) getSessionValue:(NSString *)key {
4313 @synchronized (SessionData_) {
4314 return [SessionData_ objectForKey:key];
4317 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4318 @synchronized (SessionData_) {
4319 if (value == (id) [WebUndefined undefined])
4320 [SessionData_ removeObjectForKey:key];
4322 [SessionData_ setObject:value forKey:key];
4325 - (void) addBridgedHost:(NSString *)host {
4326 @synchronized (HostConfig_) {
4327 [BridgedHosts_ addObject:host];
4330 - (void) addInsecureHost:(NSString *)host {
4331 @synchronized (HostConfig_) {
4332 [InsecureHosts_ addObject:host];
4335 - (void) addTokenHost:(NSString *)host {
4336 @synchronized (HostConfig_) {
4337 [TokenHosts_ addObject:host];
4340 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4341 @synchronized (HostConfig_) {
4342 if (scheme != (id) [WebUndefined undefined])
4343 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4345 [PipelinedHosts_ addObject:host];
4348 - (void) popViewController:(NSNumber *)value {
4349 if (value == (id) [WebUndefined undefined])
4350 value = [NSNumber numberWithBool:YES];
4351 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4354 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4355 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4357 for (NSString *section in sections)
4358 [array addObject:section];
4360 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4363 distribution, @"Distribution",
4365 nil] waitUntilDone:NO];
4368 - (void) addTrivialSource:(NSString *)href {
4369 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4372 - (void) refreshSources {
4373 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4376 - (void) saveConfig {
4377 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4380 - (NSArray *) getAllSources {
4381 return [[Database sharedInstance] sources];
4384 - (NSArray *) getInstalledPackages {
4385 Database *database([Database sharedInstance]);
4386 @synchronized (database) {
4387 NSArray *packages([database packages]);
4388 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4389 for (Package *package in packages)
4390 if (![package uninstalled])
4391 [installed addObject:package];
4395 - (Package *) getPackageById:(NSString *)id {
4396 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4400 return (Package *) [NSNull null];
4403 - (NSString *) getLocaleIdentifier {
4404 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4407 - (NSArray *) getPreferredLanguages {
4411 - (NSArray *) statfs:(NSString *)path {
4414 if (path == nil || statfs([path UTF8String], &stat) == -1)
4417 return [NSArray arrayWithObjects:
4418 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4419 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4420 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4424 - (NSNumber *) du:(NSString *)path {
4425 NSNumber *value(nil);
4428 _assert(pipe(fds) != -1);
4430 pid_t pid(ExecFork());
4432 _assert(dup2(fds[1], 1) != -1);
4433 _assert(close(fds[0]) != -1);
4434 _assert(close(fds[1]) != -1);
4435 /* XXX: this should probably not use du */
4436 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4441 _assert(close(fds[1]) != -1);
4443 if (FILE *du = fdopen(fds[0], "r")) {
4445 while (fgets(line, sizeof(line), du) != NULL) {
4446 size_t length(strlen(line));
4447 while (length != 0 && line[length - 1] == '\n')
4448 line[--length] = '\0';
4449 if (char *tab = strchr(line, '\t')) {
4451 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4456 } else _assert(close(fds[0]));
4464 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4467 - (NSNumber *) isReachable:(NSString *)name {
4468 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4471 - (void) installPackages:(NSArray *)packages {
4472 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4475 - (NSString *) substitutePackageNames:(NSString *)message {
4476 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4477 for (size_t i(0), e([words count]); i != e; ++i) {
4478 NSString *word([words objectAtIndex:i]);
4479 if (Package *package = [[Database sharedInstance] packageWithName:word])
4480 [words replaceObjectAtIndex:i withObject:[package name]];
4483 return [words componentsJoinedByString:@" "];
4486 - (void) removeButton {
4487 [indirect_ removeButton];
4490 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4491 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4494 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4495 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4498 - (void) setBadgeValue:(id)value {
4499 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4502 - (void) setAllowsNavigationAction:(NSString *)value {
4503 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4506 - (void) setHidesBackButton:(NSString *)value {
4507 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4510 - (void) setHidesNavigationBar:(NSString *)value {
4511 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4514 - (void) setNavigationBarStyle:(NSString *)value {
4515 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4518 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4519 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4520 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4521 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4524 - (void) setPasteboardString:(NSString *)value {
4525 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4528 - (void) setPasteboardURL:(NSString *)value {
4529 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4532 - (void) _setToken:(NSString *)token {
4536 [Metadata_ removeObjectForKey:@"Token"];
4538 [Metadata_ setObject:Token_ forKey:@"Token"];
4543 - (void) setToken:(NSString *)token {
4544 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4547 - (void) scrollToBottom:(NSNumber *)animated {
4548 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4551 - (void) setViewportWidth:(float)width {
4552 [indirect_ setViewportWidthOnMainThread:width];
4555 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4556 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4557 unsigned count([arguments count]);
4559 for (unsigned i(0); i != count; ++i)
4560 values[i] = [arguments objectAtIndex:i];
4561 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4564 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4565 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4567 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4569 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4575 @interface NSURL (CydiaSecure)
4578 @implementation NSURL (CydiaSecure)
4580 - (bool) isCydiaSecure {
4581 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4584 @synchronized (HostConfig_) {
4585 if ([InsecureHosts_ containsObject:[self host]])
4594 /* Cydia Browser Controller {{{ */
4595 @implementation CydiaWebViewController
4597 - (NSURL *) navigationURL {
4598 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4601 + (void) _initialize {
4602 [super _initialize];
4604 Diversions_ = [NSMutableSet setWithCapacity:0];
4607 + (void) addDiversion:(Diversion *)diversion {
4608 [Diversions_ addObject:diversion];
4611 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4612 [super webView:view didClearWindowObject:window forFrame:frame];
4613 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4616 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4617 WebDataSource *source([frame dataSource]);
4618 NSURLResponse *response([source response]);
4619 NSURL *url([response URL]);
4620 NSString *scheme([[url scheme] lowercaseString]);
4622 bool bridged(false);
4624 @synchronized (HostConfig_) {
4625 if ([scheme isEqualToString:@"file"])
4627 else if ([scheme isEqualToString:@"https"])
4628 if ([BridgedHosts_ containsObject:[url host]])
4633 [window setValue:cydia forKey:@"cydia"];
4636 - (void) _setupMail:(MFMailComposeViewController *)controller {
4637 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4639 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4640 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4643 - (NSURL *) URLWithURL:(NSURL *)url {
4644 return [Diversion divertURL:url];
4647 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4648 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4651 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4652 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4654 NSURL *url([copy URL]);
4655 NSString *href([url absoluteString]);
4656 NSString *host([url host]);
4658 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4659 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4660 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4661 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4664 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4665 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4667 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4671 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4672 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4673 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4674 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4679 @synchronized (HostConfig_) {
4680 bridged = [BridgedHosts_ containsObject:host];
4681 token = [TokenHosts_ containsObject:host];
4684 if ([url isCydiaSecure]) {
4686 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4687 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4689 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4690 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4697 - (void) setDelegate:(id)delegate {
4698 [super setDelegate:delegate];
4699 [cydia_ setDelegate:delegate];
4702 - (NSString *) applicationNameForUserAgent {
4707 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4708 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4714 @interface AppCacheController : CydiaWebViewController {
4719 @implementation AppCacheController
4721 - (void) didReceiveMemoryWarning {
4722 // XXX: this doesn't work
4725 - (bool) retainsNetworkActivityIndicator {
4733 @interface NSObject (CydiaScript)
4734 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4737 @implementation NSObject (CydiaScript)
4739 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4745 @implementation NSArray (CydiaScript)
4747 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4748 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4749 for (size_t i(0), e([self count]); i != e; ++i)
4750 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4756 @implementation NSDictionary (CydiaScript)
4758 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4759 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4761 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4768 /* Package Cell {{{ */
4769 @interface PackageCell : CyteTableViewCell <
4770 CyteTableViewCellDelegate
4774 _H<NSString> description_;
4776 _H<NSString> source_;
4778 _H<UIImage> placard_;
4781 - (PackageCell *) init;
4782 - (void) setPackage:(Package *)package;
4784 - (void) drawContentRect:(CGRect)rect;
4788 @implementation PackageCell
4790 - (PackageCell *) init {
4791 CGRect frame(CGRectMake(0, 0, 320, 74));
4792 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4793 UIView *content([self contentView]);
4794 CGRect bounds([content bounds]);
4796 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
4797 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4798 [content addSubview:content_];
4800 [content_ setDelegate:self];
4801 [content_ setOpaque:YES];
4805 - (NSString *) accessibilityLabel {
4806 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
4809 - (void) setPackage:(Package *)package {
4818 [content_ setBackgroundColor:[UIColor whiteColor]];
4822 Source *source = [package source];
4824 icon_ = [package icon];
4826 if (NSString *name = [package name])
4827 name_ = [NSString stringWithString:name];
4829 NSString *description(nil);
4831 if (description == nil && IsWildcat_)
4832 description = [package longDescription];
4833 if (description == nil)
4834 description = [package shortDescription];
4836 if (description != nil)
4837 description_ = [NSString stringWithString:description];
4839 commercial_ = [package isCommercial];
4841 NSString *label = nil;
4842 bool trusted = false;
4844 if (source != nil) {
4845 label = [source label];
4846 trusted = [source trusted];
4847 } else if ([[package id] isEqualToString:@"firmware"])
4848 label = UCLocalize("APPLE");
4850 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4852 NSString *from(label);
4854 NSString *section = [package simpleSection];
4855 if (section != nil && ![section isEqualToString:label]) {
4856 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4857 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4860 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
4862 if (NSString *purpose = [package primaryPurpose])
4863 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
4868 if (NSString *mode = [package mode]) {
4869 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
4870 color = RemovingColor_;
4871 //placard = @"removing";
4873 color = InstallingColor_;
4874 //placard = @"installing";
4877 // XXX: the removing/installing placards are not @2x
4880 color = [UIColor whiteColor];
4882 if ([package installed] != nil)
4883 placard = @"installed";
4888 [content_ setBackgroundColor:color];
4891 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
4894 [self setNeedsDisplay];
4895 [content_ setNeedsDisplay];
4898 - (void) drawContentRect:(CGRect)rect {
4899 bool highlighted(highlighted_);
4900 float width([self bounds].size.width);
4904 rect.size = [(UIImage *) icon_ size];
4906 while (rect.size.width > 32 || rect.size.height > 32) {
4907 rect.size.width /= 2;
4908 rect.size.height /= 2;
4911 rect.origin.x = 25 - rect.size.width / 2;
4912 rect.origin.y = 25 - rect.size.height / 2;
4914 [icon_ drawInRect:rect];
4917 if (badge_ != nil) {
4919 rect.size = [(UIImage *) badge_ size];
4921 rect.size.width /= 2;
4922 rect.size.height /= 2;
4924 rect.origin.x = 36 - rect.size.width / 2;
4925 rect.origin.y = 36 - rect.size.height / 2;
4927 [badge_ drawInRect:rect];
4934 UISetColor(commercial_ ? Purple_ : Black_);
4935 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4936 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4939 UISetColor(commercial_ ? Purplish_ : Gray_);
4940 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4942 if (placard_ != nil)
4943 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4948 /* Section Cell {{{ */
4949 @interface SectionCell : CyteTableViewCell <
4950 CyteTableViewCellDelegate
4952 _H<NSString> basic_;
4953 _H<NSString> section_;
4955 _H<NSString> count_;
4957 _H<UISwitch> switch_;
4961 - (void) setSection:(Section *)section editing:(BOOL)editing;
4965 @implementation SectionCell
4967 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4968 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4969 icon_ = [UIImage applicationImageNamed:@"folder.png"];
4970 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
4971 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4973 UIView *content([self contentView]);
4974 CGRect bounds([content bounds]);
4976 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
4977 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4978 [content addSubview:content_];
4979 [content_ setBackgroundColor:[UIColor whiteColor]];
4981 [content_ setDelegate:self];
4985 - (void) onSwitch:(id)sender {
4986 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
4987 if (metadata == nil) {
4988 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4989 [Sections_ setObject:metadata forKey:basic_];
4992 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4996 - (void) setSection:(Section *)section editing:(BOOL)editing {
4997 if (editing != editing_) {
4999 [switch_ removeFromSuperview];
5001 [self addSubview:switch_];
5010 if (section == nil) {
5011 name_ = UCLocalize("ALL_PACKAGES");
5014 basic_ = [section name];
5015 section_ = [section localized];
5017 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5018 count_ = [NSString stringWithFormat:@"%d", [section count]];
5021 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5024 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5025 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5027 [content_ setNeedsDisplay];
5030 - (void) setFrame:(CGRect)frame {
5031 [super setFrame:frame];
5033 CGRect rect([switch_ frame]);
5034 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5037 - (NSString *) accessibilityLabel {
5041 - (void) drawContentRect:(CGRect)rect {
5042 bool highlighted(highlighted_ && !editing_);
5044 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5049 float width(rect.size.width);
5055 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5057 CGSize size = [count_ sizeWithFont:Font14_];
5061 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5067 /* File Table {{{ */
5068 @interface FileTable : CyteViewController <
5069 UITableViewDataSource,
5072 _transient Database *database_;
5073 _H<Package> package_;
5075 _H<NSMutableArray> files_;
5076 _H<UITableView, 2> list_;
5079 - (id) initWithDatabase:(Database *)database;
5080 - (void) setPackage:(Package *)package;
5084 @implementation FileTable
5086 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5087 return files_ == nil ? 0 : [files_ count];
5090 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5094 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5095 static NSString *reuseIdentifier = @"Cell";
5097 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5099 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5100 [cell setFont:[UIFont systemFontOfSize:16]];
5102 [cell setText:[files_ objectAtIndex:indexPath.row]];
5103 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5108 - (NSURL *) navigationURL {
5109 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5113 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5114 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5115 [list_ setRowHeight:24.0f];
5116 [(UITableView *) list_ setDataSource:self];
5117 [list_ setDelegate:self];
5118 [self setView:list_];
5121 - (void) viewDidLoad {
5122 [super viewDidLoad];
5124 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5127 - (void) releaseSubviews {
5133 [super releaseSubviews];
5136 - (id) initWithDatabase:(Database *)database {
5137 if ((self = [super init]) != nil) {
5138 database_ = database;
5142 - (void) setPackage:(Package *)package {
5146 files_ = [NSMutableArray arrayWithCapacity:32];
5148 if (package != nil) {
5150 name_ = [package id];
5152 if (NSArray *files = [package files])
5153 [files_ addObjectsFromArray:files];
5155 if ([files_ count] != 0) {
5156 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5157 [files_ removeObjectAtIndex:0];
5158 [files_ sortUsingSelector:@selector(compareByPath:)];
5160 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5161 [stack addObject:@"/"];
5163 for (int i(0), e([files_ count]); i != e; ++i) {
5164 NSString *file = [files_ objectAtIndex:i];
5165 while (![file hasPrefix:[stack lastObject]])
5166 [stack removeLastObject];
5167 NSString *directory = [stack lastObject];
5168 [stack addObject:[file stringByAppendingString:@"/"]];
5169 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5170 ([stack count] - 2) * 3, "",
5171 [file substringFromIndex:[directory length]]
5180 - (void) reloadData {
5183 [self setPackage:[database_ packageWithName:name_]];
5188 /* Package Controller {{{ */
5189 @interface CYPackageController : CydiaWebViewController <
5190 UIActionSheetDelegate
5192 _transient Database *database_;
5193 _H<Package> package_;
5196 _H<NSMutableArray> buttons_;
5197 _H<UIBarButtonItem> button_;
5200 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
5204 @implementation CYPackageController
5206 - (NSURL *) navigationURL {
5207 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5210 /* XXX: this is not safe at all... localization of /fail/ */
5211 - (void) _clickButtonWithName:(NSString *)name {
5212 if ([name isEqualToString:UCLocalize("CLEAR")])
5213 [delegate_ clearPackage:package_];
5214 else if ([name isEqualToString:UCLocalize("INSTALL")])
5215 [delegate_ installPackage:package_];
5216 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5217 [delegate_ installPackage:package_];
5218 else if ([name isEqualToString:UCLocalize("REMOVE")])
5219 [delegate_ removePackage:package_];
5220 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5221 [delegate_ installPackage:package_];
5222 else _assert(false);
5224 UITabBar *tabBar = [[self tabBarController] tabBar];
5225 UITabBarItem *lastItem = [[tabBar items] lastObject];
5226 CGPoint endPoint = [[[lastItem view] superview] convertPoint:[[lastItem view] frame].origin toView:nil];
5227 endPoint = CGPointMake(endPoint.x + [[lastItem view] frame].size.width / 2, endPoint.y + [[lastItem view] frame].size.height / 2);
5229 UIBarButtonItem *rightItem = [[self navigationItem] rightBarButtonItem];
5230 CGPoint startPoint = [[[rightItem view] superview] convertPoint:[[rightItem view] frame].origin toView:nil];
5231 startPoint = CGPointMake(startPoint.x + [[rightItem view] frame].size.width / 2, startPoint.y + [[rightItem view] frame].size.height / 2);
5233 NSLog(@"animating from %@ to %@", NSStringFromCGPoint(startPoint), NSStringFromCGPoint(endPoint));
5235 // Determine the animation's path.
5236 CGPoint curvePoint1 = CGPointMake(startPoint.x - 130, startPoint.y - 10);
5237 CGPoint curvePoint2 = CGPointMake(startPoint.x - 140, endPoint.y - 40);
5239 // Create the animation's path.
5240 CGPathRef path = NULL;
5241 CGMutablePathRef mutablepath = CGPathCreateMutable();
5242 CGPathMoveToPoint(mutablepath, NULL, startPoint.x, startPoint.y);
5244 CGPathAddCurveToPoint(mutablepath, NULL,
5245 curvePoint1.x, curvePoint1.y,
5246 curvePoint2.x, curvePoint2.y,
5247 endPoint.x, endPoint.y);
5249 path = CGPathCreateCopy(mutablepath);
5250 CGPathRelease(mutablepath);
5252 UIImageView* animatedLabel = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"packages.png"]];
5253 animatedLabel.tag = 12345;
5254 [[[self view] window] addSubview:animatedLabel];
5255 [animatedLabel release];
5256 CALayer *iconViewLayer = animatedLabel.layer;
5258 CAKeyframeAnimation *animatedIconAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
5259 animatedIconAnimation.removedOnCompletion = YES;
5260 animatedIconAnimation.duration = 0.5;
5261 animatedIconAnimation.delegate = self;
5262 animatedIconAnimation.path = path;
5263 animatedIconAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
5264 [iconViewLayer addAnimation:animatedIconAnimation forKey:@"animateIcon"];
5266 // Start the icon animation.
5267 [iconViewLayer setPosition:CGPointMake(endPoint.x, endPoint.y)];
5269 [UIView beginAnimations:nil context:iconViewLayer];
5270 [UIView setAnimationDelegate:self];
5271 [UIView setAnimationDidStopSelector:@selector(flyAnimationCompleted:finished:context:)];
5272 [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
5273 [UIView setAnimationDuration:0.5];
5274 [animatedLabel setTransform:CGAffineTransformMakeScale(0.3, 0.3)];
5275 [UIView commitAnimations];
5278 - (void) flyAnimationCompleted:(NSString *)animation finished:(BOOL)finished context:(void *)context {
5279 CALayer *layer = (CALayer *) context;
5280 [layer removeFromSuperlayer];
5283 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5284 NSString *context([sheet context]);
5286 if ([context isEqualToString:@"modify"]) {
5287 if (button != [sheet cancelButtonIndex]) {
5288 NSString *buttonName = [buttons_ objectAtIndex:button];
5289 [self _clickButtonWithName:buttonName];
5292 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5296 - (bool) _allowJavaScriptPanel {
5301 - (void) _customButtonClicked {
5302 int count([buttons_ count]);
5307 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5309 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5310 [buttons addObjectsFromArray:buttons_];
5312 UIActionSheet *sheet = [[[UIActionSheet alloc]
5315 cancelButtonTitle:nil
5316 destructiveButtonTitle:nil
5317 otherButtonTitles:nil
5320 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5322 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5323 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5325 [sheet setContext:@"modify"];
5327 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5331 // We don't want to allow non-commercial packages to do custom things to the install button,
5332 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5333 - (void) customButtonClicked {
5335 [super customButtonClicked];
5337 [self _customButtonClicked];
5340 - (void) reloadButtonClicked {
5341 // Don't reload a commerical package by tapping the loading button,
5342 // but if it's not an Install button, we should forward it on.
5343 if (![package_ uninstalled])
5344 [self _customButtonClicked];
5347 - (void) applyLoadingTitle {
5348 // Don't show "Loading" as the title. Ever.
5351 - (UIBarButtonItem *) rightButton {
5356 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
5357 if ((self = [super init]) != nil) {
5358 database_ = database;
5359 buttons_ = [NSMutableArray arrayWithCapacity:4];
5360 name_ = name == nil ? @"" : [NSString stringWithString:name];
5361 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
5365 - (void) reloadData {
5368 package_ = [database_ packageWithName:name_];
5370 [buttons_ removeAllObjects];
5372 if (package_ != nil) {
5373 [(Package *) package_ parse];
5375 commercial_ = [package_ isCommercial];
5377 if ([package_ mode] != nil)
5378 [buttons_ addObject:UCLocalize("CLEAR")];
5379 if ([package_ source] == nil);
5380 else if ([package_ upgradableAndEssential:NO])
5381 [buttons_ addObject:UCLocalize("UPGRADE")];
5382 else if ([package_ uninstalled])
5383 [buttons_ addObject:UCLocalize("INSTALL")];
5385 [buttons_ addObject:UCLocalize("REINSTALL")];
5386 if (![package_ uninstalled])
5387 [buttons_ addObject:UCLocalize("REMOVE")];
5391 switch ([buttons_ count]) {
5392 case 0: title = nil; break;
5393 case 1: title = [buttons_ objectAtIndex:0]; break;
5394 default: title = UCLocalize("MODIFY"); break;
5397 button_ = [[[UIBarButtonItem alloc]
5399 style:UIBarButtonItemStylePlain
5401 action:@selector(customButtonClicked)
5405 - (bool) isLoading {
5406 return commercial_ ? [super isLoading] : false;
5412 /* Package List Controller {{{ */
5414 // This is used to sort the filters. We want this to ensure that the
5415 // cheapest filters run first. This is probably a premature optimization.
5417 kPackageListFilterPriorityLow,
5418 kPackageListFilterPriorityNormal,
5419 kPackageListFilterPriorityHigh
5420 } PackageListFilterPriority;
5425 PackageListFilterPriority priority;
5427 } PackageListFilter;
5429 @interface NSValue(PackageListFilter)
5431 + (id)valueWithPackageListFilter:(PackageListFilter)filter;
5432 - (PackageListFilter)packageListFilterValue;
5436 @implementation NSValue(PackageListFilter)
5438 + (id)valueWithPackageListFilter:(PackageListFilter)filter {
5439 return [NSValue valueWithBytes:&filter objCType:@encode(PackageListFilter)];
5442 - (PackageListFilter)packageListFilterValue {
5443 PackageListFilter filter;
5444 [self getValue:&filter];
5450 @interface FilteredPackageListDataSource : NSObject <UITableViewDataSource> {
5451 _transient Database *database_;
5453 _H<NSArray> packages_;
5454 _H<NSMutableArray> sections_;
5455 _H<NSMutableArray> index_;
5456 _H<NSMutableDictionary> indices_;
5457 _H<NSMutableDictionary> filters_;
5460 - (id)objectForFilter:(NSString *)filter;
5461 - (void)setObject:(id)object forFilter:(NSString *)filter;
5462 - (SEL)selectorForFilter:(NSString *)filter;
5463 - (void)setSelector:(SEL)selector forFilter:(NSString *)filter;
5464 - (PackageListFilterPriority)priorityForFilter:(NSString *)filter;
5465 - (void)setPriority:(PackageListFilterPriority)priority forFilter:(NSString *)filter;
5467 - (void)addFilter:(NSString *)filter withSelector:(SEL)selector;
5468 - (void)addFilter:(NSString *)filter withSelector:(SEL)selector priority:(PackageListFilterPriority)priority;
5469 - (void)addFilter:(NSString *)filter withSelector:(SEL)selector priority:(PackageListFilterPriority)priority object:(id)object;
5470 - (void)removeFilter:(NSString *)filter;
5472 - (NSArray *)packages;
5476 @implementation FilteredPackageListDataSource
5478 - (NSArray *) packages {
5482 - (id) initWithDatabase:(Database *)database {
5483 if ((self = [super init]) != nil) {
5484 database_ = database;
5485 filters_ = [NSMutableDictionary dictionary];
5489 + (BOOL) supportsSearch {
5493 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5494 @synchronized (database_) {
5495 if ([database_ era] != era_)
5498 Section *section([sections_ objectAtIndex:[path section]]);
5499 NSInteger row([path row]);
5500 Package *package([packages_ objectAtIndex:([section row] + row)]);
5501 return [[package retain] autorelease];
5504 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5505 if ([[self class] supportsSearch])
5506 return [[NSArray arrayWithObject:UITableViewIndexSearch] arrayByAddingObjectsFromArray:index_];
5511 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5512 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5514 cell = [[[PackageCell alloc] init] autorelease];
5516 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
5517 [cell setPackage:package];
5521 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5522 NSInteger count([sections_ count]);
5523 return count == 0 ? 1 : count;
5526 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5527 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5529 return [[sections_ objectAtIndex:section] name];
5532 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5533 if ([sections_ count] == 0)
5535 return [[sections_ objectAtIndex:section] count];
5538 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5539 if ([[self class] supportsSearch]) {
5541 [tableView setContentOffset:CGPointZero animated:NO];
5551 - (IMP)implementationForSelector:(SEL)selector {
5552 @synchronized (self) {
5553 /* XXX: this is an unsafe optimization of doomy hell */
5554 Method method(class_getInstanceMethod([Package class], selector));
5555 _assert(method != NULL);
5556 IMP imp = method_getImplementation(method);
5557 _assert(imp != NULL);
5562 - (PackageListFilter)packageListFilterForFilter:(NSString *)filter {
5563 return [[filters_ objectForKey:filter] packageListFilterValue];
5566 - (void)setPackageListFilter:(PackageListFilter)filter forFilter:(NSString *)filterName {
5567 [filters_ setObject:[NSValue valueWithPackageListFilter:filter] forKey:filterName];
5570 - (id)objectForFilter:(NSString *)filter {
5571 return [self packageListFilterForFilter:filter].object;
5574 - (SEL)selectorForFilter:(NSString *)filter {
5575 return [self packageListFilterForFilter:filter].selector;
5578 - (IMP)implementationForFilter:(NSString *)filter {
5579 return [self packageListFilterForFilter:filter].implementation;
5582 - (PackageListFilterPriority)priorityForFilter:(NSString *)filter {
5583 return [self packageListFilterForFilter:filter].priority;
5586 - (void)setObject:(id)object forFilter:(NSString *)filterName {
5587 PackageListFilter filter = [self packageListFilterForFilter:filterName];
5588 filter.object = object;
5589 [self setPackageListFilter:filter forFilter:filterName];
5592 - (void)setPriority:(PackageListFilterPriority)priority forFilter:(NSString *)filterName {
5593 PackageListFilter filter = [self packageListFilterForFilter:filterName];
5594 filter.priority = priority;
5595 [self setPackageListFilter:filter forFilter:filterName];
5598 - (void)setImplementation:(IMP)implementation forFilter:(NSString *)filterName {
5599 PackageListFilter filter = [self packageListFilterForFilter:filterName];
5600 filter.implementation = implementation;
5601 [self setPackageListFilter:filter forFilter:filterName];
5604 - (void)setSelector:(SEL)selector forFilter:(NSString *)filterName {
5605 PackageListFilter filter = [self packageListFilterForFilter:filterName];
5606 filter.selector = selector;
5607 [self setPackageListFilter:filter forFilter:filterName];
5609 [self setImplementation:[self implementationForSelector:selector] forFilter:filterName];
5612 - (void)addFilter:(NSString *)filterName {
5613 PackageListFilter filter;
5614 filter.object = nil;
5615 filter.selector = NULL;
5616 filter.implementation = NULL;
5617 filter.priority = kPackageListFilterPriorityNormal;
5619 [self setPackageListFilter:filter forFilter:filterName];
5622 - (void)addFilter:(NSString *)filter withSelector:(SEL)selector {
5623 [self addFilter:filter];
5624 [self setSelector:selector forFilter:filter];
5627 - (void)addFilter:(NSString *)filter withSelector:(SEL)selector priority:(PackageListFilterPriority)priority {
5628 [self addFilter:filter withSelector:selector];
5629 [self setPriority:priority forFilter:filter];
5632 - (void)addFilter:(NSString *)filter withSelector:(SEL)selector priority:(PackageListFilterPriority)priority object:(id)object {
5633 [self addFilter:filter withSelector:selector];
5634 [self setObject:object forFilter:filter];
5637 - (void)removeFilter:(NSString *)filter {
5638 [filters_ removeObjectForKey:filter];
5641 - (NSMutableArray *) _reloadPackages {
5642 @synchronized (database_) {
5643 era_ = [database_ era];
5645 NSArray *packages([database_ packages]);
5646 NSMutableArray *filtered;
5648 NSArray *filters = [filters_ allKeys];
5650 for (PackageListFilterPriority currentPriority = kPackageListFilterPriorityHigh; currentPriority >= kPackageListFilterPriorityLow; currentPriority = static_cast<PackageListFilterPriority>(static_cast<int>(currentPriority) - 1)) {
5651 for (NSString *filterName in filters) {
5652 PackageListFilter filter = [self packageListFilterForFilter:filterName];
5654 if (filter.priority == currentPriority) {
5655 filtered = [NSMutableArray arrayWithCapacity:[packages count]];
5659 _H<NSObject> object;
5661 @synchronized (self) {
5662 implementation = filter.implementation;
5663 selector = filter.selector;
5664 object = filter.object;
5667 if (implementation == NULL) continue;
5669 _profile(PackageTable$reloadData$Filter)
5670 for (Package *package in packages)
5671 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(implementation))(package, selector, object))
5672 [filtered addObject:package];
5675 packages = filtered;
5680 // packages would also be valid here, but it's defined
5681 // as an immutable array. filtered works too, so use it.
5685 - (void) reloadData {
5689 packages = [self _reloadPackages];
5691 @synchronized (database_) {
5692 if (era_ != [database_ era])
5695 packages_ = packages;
5697 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
5698 sections_ = [NSMutableArray arrayWithCapacity:16];
5700 Section *section = nil;
5701 index_ = [NSMutableArray arrayWithCapacity:32];
5703 _profile(PackageTable$reloadData$Section)
5704 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5708 _profile(PackageTable$reloadData$Section$Package)
5709 package = [packages_ objectAtIndex:offset];
5710 index = [package index];
5713 if (section == nil || [section index] != index) {
5714 _profile(PackageTable$reloadData$Section$Allocate)
5715 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5718 [index_ addObject:[section name]];
5719 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5721 _profile(PackageTable$reloadData$Section$Add)
5722 [sections_ addObject:section];
5726 [section addToCount];
5733 @interface FilteredPackageListController : CyteViewController <UITableViewDelegate, UISearchDisplayDelegate> {
5734 _transient Database *database_;
5735 _H<UISearchDisplayController> searchController_;
5736 _H<UISearchBar> searchBar_;
5737 _H<FilteredPackageListDataSource> datasource_;
5738 _H<UITableView, 2> list_;
5739 _H<NSString> title_;
5742 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5747 @implementation FilteredPackageListController
5749 - (NSURL *) referrerURL {
5750 return [self navigationURL];
5753 - (void) deselectWithAnimation:(BOOL)animated {
5754 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5757 - (void) viewDidAppear:(BOOL)animated {
5758 [super viewDidAppear:animated];
5759 [self deselectWithAnimation:animated];
5762 - (void) didSelectPackage:(Package *)package {
5763 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
5764 [view setDelegate:delegate_];
5765 [[self navigationController] pushViewController:view animated:YES];
5768 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
5769 FilteredPackageListDataSource *source = datasource_;
5771 Package *package([source packageAtIndexPath:path]);
5772 package = [database_ packageWithName:[package id]];
5773 [self didSelectPackage:package];
5776 + (Class) dataSourceClass {
5777 return [FilteredPackageListDataSource class];
5780 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
5781 if ((self = [super init]) != nil) {
5782 database_ = database;
5784 datasource_ = [[[[[self class] dataSourceClass] alloc] initWithDatabase:database_] autorelease];
5786 title_ = [title copy];
5787 [[self navigationItem] setTitle:title_];
5792 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
5793 [view setBackgroundColor:[UIColor whiteColor]];
5794 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
5795 [self setView:view];
5797 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
5798 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5799 [view addSubview:list_];
5801 // XXX: is 20 the most optimal number here?
5802 [list_ setSectionIndexMinimumDisplayRowCount:20];
5803 [list_ setRowHeight:73];
5804 [(UITableView *) list_ setDataSource:datasource_];
5805 [list_ setDelegate:self];
5807 if ([[[self class] dataSourceClass] supportsSearch]) {
5808 searchBar_ = [[UISearchBar alloc] init];
5809 [searchBar_ sizeToFit];
5810 searchController_ = [[UISearchDisplayController alloc] initWithSearchBar:searchBar_ contentsController:self];
5811 [searchController_ setDelegate:self];
5812 [list_ setTableHeaderView:searchBar_];
5814 [searchController_ setSearchResultsDataSource:datasource_];
5815 [searchController_ setSearchResultsDelegate:self];
5819 - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
5820 [datasource_ addFilter:@"search" withSelector:@selector(isUnfilteredAndSelectedForBy:) priority:kPackageListFilterPriorityLow object:searchString];
5821 [datasource_ reloadData];
5825 - (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller {
5826 [datasource_ removeFilter:@"search"];
5830 - (void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView {
5831 // XXX: is 20 the most optimal number here?
5832 [tableView setSectionIndexMinimumDisplayRowCount:20];
5833 [tableView setRowHeight:73];
5836 - (void) releaseSubviews {
5839 [super releaseSubviews];
5842 - (void) reloadData {
5845 [datasource_ reloadData];
5849 - (void) resetScrollPosition {
5850 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
5853 - (void) clearData {
5854 [list_ setDataSource:nil];
5857 [self resetScrollPosition];
5863 /* Home Controller {{{ */
5864 @interface HomeController : CydiaWebViewController {
5865 CFRunLoopRef runloop_;
5866 SCNetworkReachabilityRef reachability_;
5871 @implementation HomeController
5873 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
5874 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
5878 if ((self = [super init]) != nil) {
5879 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
5882 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
5883 if (reachability_ != NULL) {
5884 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
5885 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
5887 CFRunLoopRef runloop(CFRunLoopGetCurrent());
5888 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
5895 if (reachability_ != NULL && runloop_ != NULL)
5896 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
5900 - (NSURL *) navigationURL {
5901 return [NSURL URLWithString:@"cydia://home"];
5904 - (void) aboutButtonClicked {
5905 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
5907 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
5908 [alert addButtonWithTitle:UCLocalize("CLOSE")];
5909 [alert setCancelButtonIndex:0];
5912 @"Copyright \u00a9 2008-2011\n"
5915 "Jay Freeman (saurik)\n"
5916 "saurik@saurik.com\n"
5917 "http://www.saurik.com/"
5923 - (UIBarButtonItem *) leftButton {
5924 return [[[UIBarButtonItem alloc]
5925 initWithTitle:UCLocalize("ABOUT")
5926 style:UIBarButtonItemStylePlain
5928 action:@selector(aboutButtonClicked)
5935 /* Refresh Bar {{{ */
5936 @interface RefreshBar : UINavigationBar {
5937 _H<UIProgressIndicator> indicator_;
5938 _H<UITextLabel> prompt_;
5939 _H<UIProgressBar> progress_;
5940 _H<UINavigationButton> cancel_;
5945 @implementation RefreshBar
5947 - (void) positionViews {
5948 CGRect frame = [cancel_ frame];
5949 frame.size = [cancel_ sizeThatFits:frame.size];
5950 frame.origin.x = [self frame].size.width - frame.size.width - 5;
5951 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
5952 [cancel_ setFrame:frame];
5954 CGSize prgsize = {75, 100};
5956 [self frame].size.width - prgsize.width - 10,
5957 ([self frame].size.height - prgsize.height) / 2
5959 [progress_ setFrame:prgrect];
5961 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
5962 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
5963 CGRect indrect = {{indoffset, indoffset}, indsize};
5964 [indicator_ setFrame:indrect];
5966 CGSize prmsize = {215, indsize.height + 4};
5968 indoffset * 2 + indsize.width,
5969 unsigned([self frame].size.height - prmsize.height) / 2 - 1
5971 [prompt_ setFrame:prmrect];
5974 - (void) setFrame:(CGRect)frame {
5975 [super setFrame:frame];
5976 [self positionViews];
5979 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
5980 if ((self = [super initWithFrame:frame]) != nil) {
5981 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
5983 [self setBarStyle:UIBarStyleBlack];
5985 UIBarStyle barstyle([self _barStyle:NO]);
5986 bool ugly(barstyle == UIBarStyleDefault);
5988 UIProgressIndicatorStyle style = ugly ?
5989 UIProgressIndicatorStyleMediumBrown :
5990 UIProgressIndicatorStyleMediumWhite;
5992 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
5993 [(UIProgressIndicator *) indicator_ setStyle:style];
5994 [indicator_ startAnimation];
5995 [self addSubview:indicator_];
5997 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
5998 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
5999 [prompt_ setBackgroundColor:[UIColor clearColor]];
6000 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6001 [self addSubview:prompt_];
6003 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6004 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6005 [(UIProgressBar *) progress_ setStyle:0];
6006 [self addSubview:progress_];
6008 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6009 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6010 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6011 [cancel_ setBarStyle:barstyle];
6013 [self positionViews];
6017 - (void) setCancellable:(bool)cancellable {
6019 [self addSubview:cancel_];
6021 [cancel_ removeFromSuperview];
6025 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6026 [progress_ setProgress:0];
6030 [self setCancellable:NO];
6033 - (void) setPrompt:(NSString *)prompt {
6034 [prompt_ setText:prompt];
6037 - (void) setProgress:(float)progress {
6038 [progress_ setProgress:progress];
6044 /* Cydia Navigation Controller Interface {{{ */
6045 @interface UINavigationController (Cydia)
6047 - (NSArray *) navigationURLCollection;
6048 - (void) unloadData;
6053 /* Cydia Tab Bar Controller {{{ */
6054 @interface CYTabBarController : UITabBarController <
6055 UITabBarControllerDelegate,
6058 _transient Database *database_;
6059 _H<RefreshBar, 1> refreshbar_;
6063 // XXX: ok, "updatedelegate_"?...
6064 _transient NSObject<CydiaDelegate> *updatedelegate_;
6066 _H<UIViewController> remembered_;
6067 _transient UIViewController *transient_;
6070 - (NSArray *) navigationURLCollection;
6071 - (void) dropBar:(BOOL)animated;
6072 - (void) beginUpdate;
6073 - (void) raiseBar:(BOOL)animated;
6075 - (void) unloadData;
6079 @implementation CYTabBarController
6081 - (void) didReceiveMemoryWarning {
6082 [super didReceiveMemoryWarning];
6084 // presenting a UINavigationController on 2.x does not update its transitionView
6085 // it thereby will not allow its topViewController to be unloaded by memory pressure
6086 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6087 UIViewController *selected([self selectedViewController]);
6088 for (UINavigationController *controller in [self viewControllers])
6089 if (controller != selected)
6090 if (UIViewController *top = [controller topViewController])
6095 - (void) setUnselectedViewController:(UIViewController *)transient {
6096 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6097 if (transient != nil) {
6098 [[[self viewControllers] objectAtIndex:0] pushViewController:transient animated:YES];
6099 [self setSelectedIndex:0];
6103 NSMutableArray *controllers = [[[self viewControllers] mutableCopy] autorelease];
6104 if (transient != nil) {
6105 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
6106 [navigation setViewControllers:[NSArray arrayWithObject:transient]];
6107 transient = navigation;
6109 if (transient_ == nil)
6110 remembered_ = [controllers objectAtIndex:0];
6111 transient_ = transient;
6112 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6113 [controllers replaceObjectAtIndex:0 withObject:transient_];
6114 [self setSelectedIndex:0];
6115 [self setViewControllers:controllers];
6116 [self concealTabBarSelection];
6117 } else if (remembered_ != nil) {
6118 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6119 transient_ = transient;
6120 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6122 [self setViewControllers:controllers];
6123 [self revealTabBarSelection];
6127 - (UIViewController *) unselectedViewController {
6131 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6132 if ([self unselectedViewController])
6133 [self setUnselectedViewController:nil];
6135 // presenting a UINavigationController on 2.x does not update its transitionView
6136 // if this view was unloaded, the tranitionView may currently be presenting nothing
6137 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6138 UINavigationController *navigation((UINavigationController *) viewController);
6139 [navigation pushViewController:[[[UIViewController alloc] init] autorelease] animated:NO];
6140 [navigation popViewControllerAnimated:NO];
6144 - (NSArray *) navigationURLCollection {
6145 NSMutableArray *items([NSMutableArray array]);
6147 // XXX: Should this deal with transient view controllers?
6148 for (id navigation in [self viewControllers]) {
6149 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6151 [items addObject:stack];
6157 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6158 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6159 [self setUnselectedViewController:nil];
6161 [super dismissModalViewControllerAnimated:YES];
6164 - (void) unloadData {
6167 for (UINavigationController *controller in [self viewControllers])
6168 [controller unloadData];
6170 if (UIViewController *selected = [self selectedViewController])
6171 [selected reloadData];
6173 if (UIViewController *unselected = [self unselectedViewController]) {
6174 [unselected unloadData];
6175 [unselected reloadData];
6180 [[NSNotificationCenter defaultCenter] removeObserver:self];
6185 - (id) initWithDatabase:(Database *)database {
6186 if ((self = [super init]) != nil) {
6187 database_ = database;
6188 [self setDelegate:self];
6190 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6191 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6193 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6197 - (void) setUpdate:(NSDate *)date {
6201 - (void) beginUpdate {
6202 [(RefreshBar *) refreshbar_ start];
6205 [updatedelegate_ retainNetworkActivityIndicator];
6209 detachNewThreadSelector:@selector(performUpdate)
6215 - (void) performUpdate {
6216 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6219 status.setDelegate(self);
6220 [database_ updateWithStatus:status];
6223 performSelectorOnMainThread:@selector(completeUpdate)
6231 - (void) stopUpdateWithSelector:(SEL)selector {
6233 [updatedelegate_ releaseNetworkActivityIndicator];
6235 [self raiseBar:YES];
6238 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6241 - (void) completeUpdate {
6244 [self stopUpdateWithSelector:@selector(reloadData)];
6247 - (void) cancelUpdate {
6248 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
6251 - (void) cancelPressed {
6252 [self cancelUpdate];
6259 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6260 [refreshbar_ setPrompt:[event compoundMessage]];
6263 - (bool) isProgressCancelled {
6267 - (void) setProgressCancellable:(NSNumber *)cancellable {
6268 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6271 - (void) setProgressPercent:(NSNumber *)percent {
6272 [refreshbar_ setProgress:[percent floatValue]];
6275 - (void) setProgressStatus:(NSDictionary *)status {
6277 [self setProgressPercent:[status objectForKey:@"Percent"]];
6280 - (void) setUpdateDelegate:(id)delegate {
6281 updatedelegate_ = delegate;
6284 - (UIView *) transitionView {
6285 if ([self respondsToSelector:@selector(_transitionView)])
6286 return [self _transitionView];
6288 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6291 - (void) dropBar:(BOOL)animated {
6296 UIView *transition([self transitionView]);
6297 [[self view] addSubview:refreshbar_];
6299 CGRect barframe([refreshbar_ frame]);
6301 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6302 barframe.origin.y = CYStatusBarHeight();
6304 barframe.origin.y = 0;
6306 [refreshbar_ setFrame:barframe];
6309 [UIView beginAnimations:nil context:NULL];
6311 CGRect viewframe = [transition frame];
6312 viewframe.origin.y += barframe.size.height;
6313 viewframe.size.height -= barframe.size.height;
6314 [transition setFrame:viewframe];
6317 [UIView commitAnimations];
6319 // Ensure bar has the proper width for our view, it might have changed
6320 barframe.size.width = viewframe.size.width;
6321 [refreshbar_ setFrame:barframe];
6324 - (void) raiseBar:(BOOL)animated {
6329 UIView *transition([self transitionView]);
6330 [refreshbar_ removeFromSuperview];
6332 CGRect barframe([refreshbar_ frame]);
6335 [UIView beginAnimations:nil context:NULL];
6337 CGRect viewframe = [transition frame];
6338 viewframe.origin.y -= barframe.size.height;
6339 viewframe.size.height += barframe.size.height;
6340 [transition setFrame:viewframe];
6343 [UIView commitAnimations];
6346 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6347 bool dropped(dropped_);
6352 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6358 - (void) statusBarFrameChanged:(NSNotification *)notification {
6368 /* Cydia Navigation Controller Implementation {{{ */
6369 @implementation UINavigationController (Cydia)
6371 - (NSArray *) navigationURLCollection {
6372 NSMutableArray *stack([NSMutableArray array]);
6374 for (CyteViewController *controller in [self viewControllers]) {
6375 NSString *url = [[controller navigationURL] absoluteString];
6377 [stack addObject:url];
6383 - (void) reloadData {
6386 UIViewController *visible([self visibleViewController]);
6388 [visible reloadData];
6390 // on the iPad, this view controller is ALSO visible. :(
6392 if (UIViewController *top = [self topViewController])
6397 - (void) unloadData {
6398 for (CyteViewController *page in [self viewControllers])
6407 /* Cydia:// Protocol {{{ */
6408 @interface CydiaURLProtocol : NSURLProtocol {
6413 @implementation CydiaURLProtocol
6415 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6416 NSURL *url([request URL]);
6420 NSString *scheme([[url scheme] lowercaseString]);
6421 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6423 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6429 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6433 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6434 id<NSURLProtocolClient> client([self client]);
6436 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6438 NSData *data(UIImagePNGRepresentation(icon));
6440 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6441 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6442 [client URLProtocol:self didLoadData:data];
6443 [client URLProtocolDidFinishLoading:self];
6447 - (void) startLoading {
6448 id<NSURLProtocolClient> client([self client]);
6449 NSURLRequest *request([self request]);
6451 NSURL *url([request URL]);
6452 NSString *href([url absoluteString]);
6453 NSString *scheme([[url scheme] lowercaseString]);
6457 if ([scheme isEqualToString:@"cydia"])
6458 path = [href substringFromIndex:8];
6459 else if ([scheme isEqualToString:@"about"])
6460 path = [href substringFromIndex:12];
6461 else _assert(false);
6463 NSRange slash([path rangeOfString:@"/"]);
6466 if (slash.location == NSNotFound) {
6470 command = [path substringToIndex:slash.location];
6471 path = [path substringFromIndex:(slash.location + 1)];
6474 Database *database([Database sharedInstance]);
6476 if ([command isEqualToString:@"package-icon"]) {
6479 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6480 Package *package([database packageWithName:path]);
6484 UIImage *icon([package icon]);
6485 [self _returnPNGWithImage:icon forRequest:request];
6486 } else if ([command isEqualToString:@"uikit-image"]) {
6489 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6490 UIImage *icon(_UIImageWithName(path));
6491 [self _returnPNGWithImage:icon forRequest:request];
6492 } else if ([command isEqualToString:@"section-icon"]) {
6495 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6496 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
6498 icon = [UIImage applicationImageNamed:@"unknown.png"];
6499 [self _returnPNGWithImage:icon forRequest:request];
6501 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6505 - (void) stopLoading {
6511 /* Section Controller {{{ */
6512 @interface SectionController : FilteredPackageListController {
6513 _H<IndirectDelegate, 1> indirect_;
6514 _H<CydiaObject> cydia_;
6515 _H<NSString> section_;
6517 _transient Source *source_;
6518 std::vector< _H<CyteWebViewTableViewCell, 1> > promoted_;
6521 - (id) initWithDatabase:(Database *)database section:(NSString *)section source:(Source *)source;
6525 @implementation SectionController
6527 - (NSURL *) referrerURL {
6528 NSMutableString *path = [NSMutableString string];
6530 if (source_ != nil) {
6531 [path appendString:[NSString stringWithFormat:@"sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
6533 [path appendString:@"sections"];
6536 [path appendString:@"/"];
6538 if (section_ != nil) {
6539 [path appendString:[NSString stringWithFormat:@"%@", [section_ stringByAddingPercentEscapesIncludingReserved]]];
6541 [path appendString:@"all"];
6544 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/%@", UI_, path]];
6547 - (NSURL *) navigationURL {
6548 NSMutableString *path = [NSMutableString string];
6550 if (source_ != nil) {
6551 [path appendString:[NSString stringWithFormat:@"sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
6553 [path appendString:@"sections"];
6556 [path appendString:@"/"];
6558 if (section_ != nil) {
6559 [path appendString:[NSString stringWithFormat:@"%@", [section_ stringByAddingPercentEscapesIncludingReserved]]];
6561 [path appendString:@"all"];
6564 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://%@", path]];
6567 - (id) initWithDatabase:(Database *)database section:(NSString *)name source:(Source *)source {
6570 title = UCLocalize("ALL_PACKAGES");
6571 else if (![name isEqual:@""])
6572 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6574 title = UCLocalize("NO_SECTION");
6576 if ((self = [super initWithDatabase:database title:title]) != nil) {
6577 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
6578 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
6580 [datasource_ addFilter:@"section" withSelector:@selector(isVisibleInSection:) priority:kPackageListFilterPriorityHigh object:name];
6581 [datasource_ addFilter:@"source" withSelector:@selector(isVisibleInSource:) priority:kPackageListFilterPriorityHigh object:source];
6585 key_ = [source key];
6589 /*- (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6590 return [super numberOfSectionsInTableView:list] + 1;
6593 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6594 return section == 0 ? nil : [super tableView:list titleForHeaderInSection:(section - 1)];
6597 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6598 return section == 0 ? promoted_.size() : [super tableView:list numberOfRowsInSection:(section - 1)];
6601 + (NSIndexPath *) adjustedIndexPath:(NSIndexPath *)path {
6602 return [NSIndexPath indexPathForRow:[path row] inSection:([path section] - 1)];
6605 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6606 if ([path section] != 0)
6607 return [super tableView:table cellForRowAtIndexPath:[SectionController adjustedIndexPath:path]];
6609 return promoted_[[path row]];
6612 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6613 if ([path section] != 0)
6614 return [super tableView:table didSelectRowAtIndexPath:[SectionController adjustedIndexPath:path]];
6617 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6618 NSInteger section([super tableView:tableView sectionForSectionIndexTitle:title atIndex:index]);
6619 return section == 0 ? 0 : section + 1;
6622 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
6623 NSURL *url([request URL]);
6627 if ([frame isEqualToString:@"_open"])
6628 [delegate_ openURL:url];
6630 WebFrame *frame(nil);
6631 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
6632 frame = [WebActionElement objectForKey:@"WebElementFrame"];
6634 frame = [view mainFrame];
6636 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
6638 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
6639 [controller setDelegate:delegate_];
6640 [[self navigationController] pushViewController:controller animated:YES];
6646 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
6647 return [CydiaWebViewController requestWithHeaders:request];
6650 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
6651 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
6657 // XXX: this code is horrible. I mean, wtf Jay?
6658 if (ShowPromoted_ && [[Metadata_ objectForKey:@"ShowPromoted"] boolValue]) {
6659 promoted_.resize(1);
6661 for (unsigned i(0); i != promoted_.size(); ++i) {
6662 CyteWebViewTableViewCell *promoted([CyteWebViewTableViewCell cellWithRequest:[NSURLRequest
6663 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sectionhead/%u/%@",
6664 UI_, i, section_ == nil ? @"" : [section_ stringByAddingPercentEscapesIncludingReserved]]
6667 cachePolicy:NSURLRequestUseProtocolCachePolicy
6671 [promoted setDelegate:self];
6672 promoted_[i] = promoted;
6677 - (void) setDelegate:(id)delegate {
6678 [super setDelegate:delegate];
6679 [cydia_ setDelegate:delegate];
6682 - (void) releaseSubviews {
6684 [super releaseSubviews];
6687 - (void)reloadData {
6688 source_ = [database_ sourceWithKey:key_];
6689 key_ = [source_ key];
6690 [datasource_ setObject:source_ forFilter:@"source"];
6697 /* Sections Controller {{{ */
6698 @interface SectionsController : CyteViewController <
6699 UITableViewDataSource,
6702 _transient Database *database_;
6703 _H<NSMutableArray> sections_;
6704 _H<NSMutableArray> filtered_;
6705 _H<UITableView, 2> list_;
6707 _transient Source *source_;
6710 - (id) initWithDatabase:(Database *)database source:(Source *)source;
6711 - (void) editButtonClicked;
6715 @implementation SectionsController
6717 - (NSURL *) navigationURL {
6718 if (source_ != nil) {
6719 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
6721 return [NSURL URLWithString:@"cydia://sections"];
6725 - (NSString *)defaultTitle {
6726 if (source_ != nil) {
6727 return [source_ label];
6729 return UCLocalize("SECTIONS");
6733 - (void) updateNavigationItem {
6734 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : [self defaultTitle]];
6735 if ([sections_ count] == 0) {
6736 [[self navigationItem] setRightBarButtonItem:nil];
6738 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6739 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6741 action:@selector(editButtonClicked)
6742 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6746 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
6747 [super setEditing:editing animated:animated];
6752 [delegate_ updateData];
6754 [self updateNavigationItem];
6757 - (void) viewDidAppear:(BOOL)animated {
6758 [super viewDidAppear:animated];
6759 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6762 - (void) viewWillDisappear:(BOOL)animated {
6763 [super viewWillDisappear:animated];
6764 [self setEditing:NO];
6767 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6768 Section *section = nil;
6769 int index = [indexPath row];
6770 if (![self isEditing]) {
6773 section = [filtered_ objectAtIndex:index];
6775 section = [sections_ objectAtIndex:index];
6780 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6781 if ([self isEditing])
6782 return [sections_ count];
6784 return [filtered_ count] + 1;
6787 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6791 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6792 static NSString *reuseIdentifier = @"SectionCell";
6794 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6796 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6798 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
6803 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6804 if ([self isEditing])
6807 Section *section = [self sectionAtIndexPath:indexPath];
6809 SectionController *controller = [[[SectionController alloc]
6810 initWithDatabase:database_
6811 section:[section name]
6814 [controller setDelegate:delegate_];
6816 [[self navigationController] pushViewController:controller animated:YES];
6820 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6821 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6822 [list_ setRowHeight:45.0f];
6823 [(UITableView *) list_ setDataSource:self];
6824 [list_ setDelegate:self];
6825 [self setView:list_];
6828 - (void) viewDidLoad {
6829 [super viewDidLoad];
6831 [[self navigationItem] setTitle:[self defaultTitle]];
6834 - (void) releaseSubviews {
6840 [super releaseSubviews];
6843 - (id) initWithDatabase:(Database *)database source:(Source *)source {
6844 if ((self = [super init]) != nil) {
6845 database_ = database;
6847 key_ = [source_ key];
6851 - (void) reloadData {
6852 source_ = [database_ sourceWithKey:key_];
6853 key_ = [source_ key];
6855 [[self navigationItem] setTitle:[source_ label]];
6859 NSArray *packages = [database_ packages];
6861 sections_ = [NSMutableArray arrayWithCapacity:16];
6862 filtered_ = [NSMutableArray arrayWithCapacity:16];
6864 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6867 for (Package *package in packages) {
6868 // Ignore packages from other sources (but allow all without a source).
6869 if (source_ != nil && ![package isVisibleInSource:source_]) continue;
6871 NSString *name([package section]);
6872 NSString *key(name == nil ? @"" : name);
6876 _profile(SectionsView$reloadData$Section)
6877 section = [sections objectForKey:key];
6878 if (section == nil) {
6879 _profile(SectionsView$reloadData$Section$Allocate)
6880 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
6881 [sections setObject:section forKey:key];
6886 [section addToCount];
6888 _profile(SectionsView$reloadData$Filter)
6889 if (![package valid] || ![package visible])
6897 [sections_ addObjectsFromArray:[sections allValues]];
6899 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6901 for (Section *section in (id) sections_) {
6902 size_t count([section row]);
6906 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6907 [section setCount:count];
6908 [filtered_ addObject:section];
6911 [self updateNavigationItem];
6916 - (void) editButtonClicked {
6917 [self setEditing:![self isEditing] animated:YES];
6923 /* Changes Controller {{{ */
6924 @interface ChangesPackageListDataSource : FilteredPackageListDataSource {
6930 @implementation ChangesPackageListDataSource
6932 - (NSMutableArray *) _reloadPackages {
6933 @synchronized (database_) {
6934 era_ = [database_ era];
6935 NSArray *packages([database_ packages]);
6937 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6940 _profile(ChangesPackageListController$_reloadPackages$Filter)
6941 for (Package *package in packages)
6942 if ([package upgradableAndEssential:YES] || [package visible])
6943 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
6946 _profile(ChangesPackageListController$_reloadPackages$radixSort)
6947 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
6954 - (void) reloadData {
6955 NSArray *packages = [self _reloadPackages];
6957 @synchronized (database_) {
6958 packages_ = packages;
6959 sections_ = [NSMutableArray arrayWithCapacity:16];
6961 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6962 Section *ignored = nil;
6963 Section *section = nil;
6967 bool unseens = false;
6969 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6971 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6972 Package *package = [packages_ objectAtIndex:offset];
6974 BOOL uae = [package upgradableAndEssential:YES];
6978 time_t seen([package seen]);
6980 if (section == nil || last != seen) {
6984 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
6987 _profile(ChangesPackageListController$reloadData$Allocate)
6988 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
6989 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6990 [sections_ addObject:section];
6994 [section addToCount];
6995 } else if ([package ignored]) {
6996 if (ignored == nil) {
6997 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
6999 [ignored addToCount];
7002 [upgradable addToCount];
7007 CFRelease(formatter);
7010 Section *last = [sections_ lastObject];
7011 size_t count = [last count];
7012 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7013 [sections_ removeLastObject];
7016 if ([ignored count] != 0)
7017 [sections_ insertObject:ignored atIndex:0];
7019 [sections_ insertObject:upgradable atIndex:0];
7026 + (BOOL) supportsSearch {
7032 @interface ChangesPackageListController : FilteredPackageListController <
7035 _H<CyteWebView, 1> dickbar_;
7036 _H<IndirectDelegate, 1> indirect_;
7037 _H<CydiaObject> cydia_;
7040 - (id) initWithDatabase:(Database *)database;
7044 @implementation ChangesPackageListController
7046 - (NSURL *) navigationURL {
7047 return [NSURL URLWithString:@"cydia://changes"];
7050 - (void) viewDidAppear:(BOOL)animated {
7051 [super viewDidAppear:animated];
7052 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7055 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
7056 Package *package([datasource_ packageAtIndexPath:path]);
7057 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[NSString stringWithFormat:@"%@/#!/changes/", UI_]] autorelease]);
7058 [view setDelegate:delegate_];
7059 [[self navigationController] pushViewController:view animated:YES];
7062 + (Class) dataSourceClass {
7063 return [ChangesPackageListDataSource class];
7066 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7067 NSString *context([alert context]);
7069 if ([context isEqualToString:@"norefresh"])
7070 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7073 - (void) refreshButtonClicked {
7074 if (IsReachable("cydia.saurik.com")) {
7075 [delegate_ beginUpdate];
7076 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7078 UIAlertView *alert = [[[UIAlertView alloc]
7079 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
7080 message:@"Host Unreachable" // XXX: Localize
7082 cancelButtonTitle:UCLocalize("OK")
7083 otherButtonTitles:nil
7086 [alert setContext:@"norefresh"];
7091 - (void) upgradeButtonClicked {
7092 [delegate_ distUpgrade];
7093 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7099 if (AprilFools_ && kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
7100 CGRect dickframe([[self view] bounds]);
7101 dickframe.size.height = 44;
7103 dickbar_ = [[[CyteWebView alloc] initWithFrame:dickframe] autorelease];
7104 [dickbar_ setDelegate:self];
7105 [[self view] addSubview:dickbar_];
7107 [dickbar_ setBackgroundColor:[UIColor clearColor]];
7108 [dickbar_ setScalesPageToFit:YES];
7110 UIWebDocumentView *document([dickbar_ _documentView]);
7111 [document setBackgroundColor:[UIColor clearColor]];
7112 [document setDrawsBackground:NO];
7114 WebView *webview([document webView]);
7115 [webview setShouldUpdateWhileOffscreen:NO];
7117 UIScrollView *scroller([dickbar_ scrollView]);
7118 [scroller setScrollingEnabled:NO];
7119 [scroller setFixedBackgroundPattern:YES];
7120 [scroller setBackgroundColor:[UIColor clearColor]];
7122 WebPreferences *preferences([webview preferences]);
7123 [preferences setCacheModel:WebCacheModelDocumentBrowser];
7124 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
7125 [preferences setOfflineWebApplicationCacheEnabled:YES];
7127 [dickbar_ loadRequest:[NSURLRequest
7128 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/dickbar/", UI_]]]
7129 cachePolicy:NSURLRequestUseProtocolCachePolicy
7133 UIEdgeInsets inset = {44, 0, 0, 0};
7134 [list_ setContentInset:inset];
7136 [dickbar_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7140 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7141 NSURL *url([request URL]);
7145 if ([frame isEqualToString:@"_open"])
7146 [delegate_ openURL:url];
7148 WebFrame *frame(nil);
7149 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7150 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7152 frame = [view mainFrame];
7154 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7156 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7157 [controller setDelegate:delegate_];
7158 [[self navigationController] pushViewController:controller animated:YES];
7164 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7165 return [CydiaWebViewController requestWithHeaders:request];
7168 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7169 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7172 - (void) setDelegate:(id)delegate {
7173 [super setDelegate:delegate];
7174 [cydia_ setDelegate:delegate];
7177 - (void) releaseSubviews {
7180 [super releaseSubviews];
7183 - (id) initWithDatabase:(Database *)database {
7184 if ((self = [super initWithDatabase:database title:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES"))]) != nil) {
7185 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7186 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7187 database_ = database;
7191 - (void) reloadData {
7194 [[self navigationItem] setRightBarButtonItem:([datasource_ upgrades] == 0 ? nil : [[[UIBarButtonItem alloc]
7195 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", [datasource_ upgrades]]]
7196 style:UIBarButtonItemStylePlain
7198 action:@selector(upgradeButtonClicked)
7199 ] autorelease]) animated:YES];
7201 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7202 initWithTitle:UCLocalize("REFRESH")
7203 style:UIBarButtonItemStylePlain
7205 action:@selector(refreshButtonClicked)
7206 ] autorelease]) animated:YES];
7213 /* Package Settings Controller {{{ */
7214 @interface PackageSettingsController : CyteViewController <
7215 UITableViewDataSource,
7218 _transient Database *database_;
7220 _H<Package> package_;
7221 _H<UITableView, 2> table_;
7222 _H<UISwitch> subscribedSwitch_;
7223 _H<UISwitch> ignoredSwitch_;
7224 _H<UITableViewCell> subscribedCell_;
7225 _H<UITableViewCell> ignoredCell_;
7228 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7232 @implementation PackageSettingsController
7234 - (NSURL *) navigationURL {
7235 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7238 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7239 if (package_ == nil)
7242 if ([package_ installed] == nil)
7248 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7249 if (package_ == nil)
7252 // both sections contain just one item right now.
7256 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7260 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7262 return UCLocalize("SHOW_ALL_CHANGES_EX");
7264 return UCLocalize("IGNORE_UPGRADES_EX");
7267 - (void) onSubscribed:(id)control {
7268 bool value([control isOn]);
7269 if (package_ == nil)
7271 if ([package_ setSubscribed:value])
7272 [delegate_ updateData];
7275 - (void) _updateIgnored {
7276 const char *package([name_ UTF8String]);
7277 bool on([ignoredSwitch_ isOn]);
7279 pid_t pid(ExecFork());
7281 FILE *dpkg(popen("dpkg --set-selections", "w"));
7282 fwrite(package, strlen(package), 1, dpkg);
7285 fwrite(" hold\n", 6, 1, dpkg);
7287 fwrite(" install\n", 9, 1, dpkg);
7298 - (void) onIgnored:(id)control {
7299 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7300 [invocation setTarget:self];
7301 [invocation setSelector:@selector(_updateIgnored)];
7303 [delegate_ reloadDataWithInvocation:invocation];
7306 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7307 if (package_ == nil)
7310 switch ([indexPath section]) {
7311 case 0: return subscribedCell_;
7312 case 1: return ignoredCell_;
7321 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7322 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7323 [self setView:view];
7325 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7326 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7327 [(UITableView *) table_ setDataSource:self];
7328 [table_ setDelegate:self];
7329 [view addSubview:table_];
7331 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7332 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7333 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7335 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7336 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7337 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7339 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7340 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7341 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7342 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7344 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7345 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7346 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7347 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7350 - (void) viewDidLoad {
7351 [super viewDidLoad];
7353 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7356 - (void) releaseSubviews {
7358 subscribedCell_ = nil;
7360 ignoredSwitch_ = nil;
7361 subscribedSwitch_ = nil;
7363 [super releaseSubviews];
7366 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7367 if ((self = [super init]) != nil) {
7368 database_ = database;
7373 - (void) reloadData {
7376 package_ = [database_ packageWithName:name_];
7378 if (package_ != nil) {
7379 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7380 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7381 } // XXX: what now, G?
7383 [table_ reloadData];
7389 /* Installed Controller {{{ */
7390 @interface InstalledController : FilteredPackageListController {
7394 - (id) initWithDatabase:(Database *)database;
7396 - (void) updateRoleButton;
7400 @implementation InstalledController
7402 - (NSURL *) referrerURL {
7403 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
7406 - (NSURL *) navigationURL {
7407 return [NSURL URLWithString:@"cydia://installed"];
7410 - (id) initWithDatabase:(Database *)database {
7411 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") ]) != nil) {
7412 [datasource_ addFilter:@"installed" withSelector:@selector(isInstalledAndUnfiltered:) priority:kPackageListFilterPriorityHigh object:[NSNumber numberWithBool:YES]];
7413 [self updateRoleButton];
7417 - (void) updateRoleButton {
7418 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7419 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7420 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7421 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7423 action:@selector(roleButtonClicked)
7427 - (void) roleButtonClicked {
7428 [datasource_ setObject:[NSNumber numberWithBool:expert_] forFilter:@"installed"];
7432 [self updateRoleButton];
7438 /* Confirmation Controller {{{ */
7439 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
7440 if (!iterator.end())
7441 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
7442 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
7444 pkgCache::PkgIterator package(dep.TargetPkg());
7447 if (strcmp(package.Name(), "mobilesubstrate") == 0)
7454 @protocol ConfirmationControllerDelegate
7455 - (void) clearQueue;
7456 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
7459 @interface ConfirmationControllerDataSource : FilteredPackageListDataSource {
7460 _H<NSMutableArray> issues_;
7461 BOOL removeEssential_;
7465 @property (nonatomic, readonly) NSMutableArray *issues;
7466 @property (nonatomic, readonly, assign, getter=willRemoveEssential) BOOL removeEssential;
7467 @property (nonatomic, readonly, assign) BOOL substrate;
7471 @implementation ConfirmationControllerDataSource
7473 - (int) numberOfSectionsInTableView:(UITableView *)table {
7474 int n = [super numberOfSectionsInTableView:table];
7475 NSLog(@"nubmer of sectoins: %d");
7479 - (NSMutableArray *)issues {
7483 - (BOOL)willRemoveEssential {
7484 return removeEssential_;
7491 + (BOOL)supportsSearch {
7495 - (void)reloadData {
7498 era_ = [database_ era];
7500 pkgCacheFile &cache([database_ cache]);
7501 NSArray *packages([database_ packages]);
7502 pkgDepCache::Policy *policy([database_ policy]);
7504 issues_ = [NSMutableArray arrayWithCapacity:4];
7506 Section *installsSection = [[[Section alloc] initWithName:@"Install" localized:UCLocalize("INSTALLS")] autorelease];
7507 Section *reinstallsSection = [[[Section alloc] initWithName:@"Reinstall" localized:UCLocalize("REINSTALLS")] autorelease];
7508 Section *upgradesSection = [[[Section alloc] initWithName:@"Upgrade" localized:UCLocalize("UPGRADES")] autorelease];
7509 Section *downgradesSection = [[[Section alloc] initWithName:@"Downgrade" localized:UCLocalize("DOWNGRADES")] autorelease];
7510 Section *removesSection = [[[Section alloc] initWithName:@"Remove" localized:UCLocalize("REMOVES")] autorelease];
7512 NSMutableArray *installs = [NSMutableArray arrayWithCapacity:16];
7513 NSMutableArray *reinstalls = [NSMutableArray arrayWithCapacity:16];
7514 NSMutableArray *upgrades = [NSMutableArray arrayWithCapacity:16];
7515 NSMutableArray *downgrades = [NSMutableArray arrayWithCapacity:16];
7516 NSMutableArray *removes = [NSMutableArray arrayWithCapacity:16];
7518 for (Package *package in packages) {
7519 pkgCache::PkgIterator iterator([package iterator]);
7520 NSString *name([package id]);
7522 if ([package broken]) {
7523 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
7525 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
7527 reasons, @"reasons",
7530 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
7534 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
7535 pkgCache::DepIterator start;
7536 pkgCache::DepIterator end;
7537 dep.GlobOr(start, end); // ++dep
7539 if (!cache->IsImportantDep(end))
7541 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
7544 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
7546 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
7547 [NSString stringWithUTF8String:start.DepType()], @"relationship",
7548 clauses, @"clauses",
7552 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
7554 pkgCache::PkgIterator target(start.TargetPkg());
7555 if (target->ProvidesList != 0)
7556 reason = @"missing";
7558 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
7560 reason = @"installed";
7561 installed = [NSString stringWithUTF8String:ver.VerStr()];
7562 } else if (!cache[target].CandidateVerIter(cache).end())
7563 reason = @"uninstalled";
7564 else if (target->ProvidesList == 0)
7565 reason = @"uninstallable";
7567 reason = @"virtual";
7570 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
7571 [NSString stringWithUTF8String:start.CompType()], @"operator",
7572 [NSString stringWithUTF8String:start.TargetVer()], @"value",
7574 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
7575 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
7576 version, @"version",
7578 installed, @"installed",
7581 // yes, seriously. (wtf?)
7589 pkgDepCache::StateCache &state(cache[iterator]);
7591 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
7593 if (state.NewInstall()) {
7594 [installs addObject:package];
7595 [installsSection addToCount];
7596 // XXX: } else if (state.Install()) {
7597 } else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall) {
7598 [reinstalls addObject:package];
7599 [reinstallsSection addToCount];
7600 // XXX: move before previous if
7601 } else if (state.Upgrade()) {
7602 [upgrades addObject:package];
7603 [upgradesSection addToCount];
7604 } else if (state.Downgrade()) {
7605 [downgrades addObject:package];
7606 [downgradesSection addToCount];
7607 } else if (!state.Delete()) {
7608 // XXX: _assert(state.Keep());
7610 } else if (special_r(name)) {
7611 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
7612 [NSNull null], @"package",
7613 [NSArray arrayWithObjects:
7614 [NSDictionary dictionaryWithObjectsAndKeys:
7615 @"Conflicts", @"relationship",
7616 [NSArray arrayWithObjects:
7617 [NSDictionary dictionaryWithObjectsAndKeys:
7619 [NSNull null], @"version",
7620 @"installed", @"reason",
7627 if ([package essential])
7629 [removes addObject:package];
7630 [removesSection addToCount];
7633 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
7634 substrate_ |= DepSubstrate(iterator.CurrentVer());
7637 /*sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
7638 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
7639 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
7642 NSMutableArray *packagesList = [NSMutableArray arrayWithCapacity:64];
7644 count += [installs count];
7645 [packagesList addObjectsFromArray:installs];
7646 for (size_t i = 0; i < count; i++) [reinstallsSection addToRow];
7647 count += [reinstalls count];
7648 [packagesList addObjectsFromArray:reinstalls];
7649 for (size_t i = 0; i < count; i++) [upgradesSection addToRow];
7650 count += [upgrades count];
7651 [packagesList addObjectsFromArray:upgrades];
7652 for (size_t i = 0; i < count; i++) [downgradesSection addToRow];
7653 count += [downgrades count];
7654 [packagesList addObjectsFromArray:downgrades];
7655 for (size_t i = 0; i < count; i++) [removesSection addToRow];
7656 [packagesList addObjectsFromArray:removes];
7657 packages_ = packagesList;
7659 sections_ = [NSMutableArray arrayWithCapacity:4];
7660 if ([installsSection count] > 0) [sections_ addObject:installsSection];
7661 if ([reinstallsSection count] > 0) [sections_ addObject:reinstallsSection];
7662 if ([upgradesSection count] > 0) [sections_ addObject:upgradesSection];
7663 if ([downgradesSection count] > 0) [sections_ addObject:downgradesSection];
7664 if ([removesSection count] > 0) [sections_ addObject:removesSection];
7669 @interface ConfirmationController : FilteredPackageListController {
7670 _H<UIAlertView> essential_;
7673 - (id) initWithDatabase:(Database *)database;
7677 @implementation ConfirmationController
7679 + (Class) dataSourceClass {
7680 return [ConfirmationControllerDataSource class];
7684 if ([datasource_ substrate])
7685 RestartSubstrate_ = true;
7686 [delegate_ confirmWithNavigationController:[self navigationController]];
7689 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7690 NSString *context([alert context]);
7692 if ([context isEqualToString:@"remove"]) {
7693 if (button == [alert cancelButtonIndex])
7694 [self dismissModalViewControllerAnimated:YES];
7695 else if (button == [alert firstOtherButtonIndex]) {
7696 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
7699 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7700 } else if ([context isEqualToString:@"unable"]) {
7701 [self dismissModalViewControllerAnimated:YES];
7702 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7706 - (id) initWithDatabase:(Database *)database {
7707 if ((self = [super initWithDatabase:database title:UCLocalize("QUEUE")]) != nil) {
7711 - (void)viewWillAppear:(BOOL)animated {
7712 [super viewWillAppear:animated];
7717 - (void)reloadData {
7720 if (![datasource_ willRemoveEssential]) {
7722 } else if (Advanced_) {
7723 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
7725 essential_ = [[[UIAlertView alloc]
7726 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
7727 message:UCLocalize("REMOVING_ESSENTIALS_EX")
7729 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
7731 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
7735 [essential_ setContext:@"remove"];
7736 [essential_ setNumberOfRows:2];
7738 essential_ = [[[UIAlertView alloc]
7739 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
7740 message:UCLocalize("UNABLE_TO_COMPLY_EX")
7742 cancelButtonTitle:UCLocalize("OKAY")
7743 otherButtonTitles:nil
7746 [essential_ setContext:@"unable"];
7749 if ([[datasource_ packages] count] > 0) {
7750 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7751 initWithTitle:UCLocalize("CLEAR")
7752 style:UIBarButtonItemStylePlain
7754 action:@selector(clearButtonClicked)
7757 [[self navigationItem] setLeftBarButtonItem:nil];
7760 if ([[datasource_ issues] count] == 0) {
7761 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7762 initWithTitle:UCLocalize("CONFIRM")
7763 style:UIBarButtonItemStyleDone
7765 action:@selector(confirmButtonClicked)
7768 [[self navigationItem] setRightBarButtonItem:nil];
7772 - (void) clearButtonClicked {
7773 [delegate_ clearQueue];
7777 - (void) confirmButtonClicked {
7778 if (essential_ != nil)
7787 /* Progress Data {{{ */
7788 @interface CydiaProgressData : NSObject {
7789 _transient id delegate_;
7798 _H<NSMutableArray> events_;
7799 _H<NSString> title_;
7801 _H<NSString> status_;
7802 _H<NSString> finish_;
7807 @implementation CydiaProgressData
7809 + (NSArray *) _attributeKeys {
7810 return [NSArray arrayWithObjects:
7822 - (NSArray *) attributeKeys {
7823 return [[self class] _attributeKeys];
7826 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
7827 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
7831 if ((self = [super init]) != nil) {
7832 events_ = [NSMutableArray arrayWithCapacity:32];
7836 - (void) setDelegate:(id)delegate {
7837 delegate_ = delegate;
7840 - (void) setPercent:(float)value {
7844 - (NSNumber *) percent {
7845 return [NSNumber numberWithFloat:percent_];
7848 - (void) setCurrent:(float)value {
7852 - (NSNumber *) current {
7853 return [NSNumber numberWithFloat:current_];
7856 - (void) setTotal:(float)value {
7860 - (NSNumber *) total {
7861 return [NSNumber numberWithFloat:total_];
7864 - (void) setSpeed:(float)value {
7868 - (NSNumber *) speed {
7869 return [NSNumber numberWithFloat:speed_];
7872 - (NSArray *) events {
7876 - (void) removeAllEvents {
7877 [events_ removeAllObjects];
7880 - (void) addEvent:(CydiaProgressEvent *)event {
7881 [events_ addObject:event];
7884 - (void) setTitle:(NSString *)text {
7888 - (NSString *) title {
7892 - (void) setFinish:(NSString *)text {
7896 - (NSString *) finish {
7897 return (id) finish_ ?: [NSNull null];
7900 - (void) setRunning:(bool)running {
7904 - (NSNumber *) running {
7905 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
7910 /* Progress Controller {{{ */
7911 @interface ProgressController : CydiaWebViewController <
7914 _transient Database *database_;
7915 _H<CydiaProgressData, 1> progress_;
7919 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
7921 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
7923 - (void) setTitle:(NSString *)title;
7924 - (void) setCancellable:(bool)cancellable;
7928 @implementation ProgressController
7931 [database_ setProgressDelegate:nil];
7935 - (UIBarButtonItem *) leftButton {
7936 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
7937 initWithTitle:UCLocalize("CANCEL")
7938 style:UIBarButtonItemStylePlain
7940 action:@selector(cancel)
7941 ] autorelease] : nil;
7944 - (void) updateCancel {
7945 [super applyLeftButton];
7948 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7949 if ((self = [super init]) != nil) {
7950 database_ = database;
7951 delegate_ = delegate;
7953 [database_ setProgressDelegate:self];
7955 progress_ = [[[CydiaProgressData alloc] init] autorelease];
7956 [progress_ setDelegate:self];
7958 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
7960 [scroller_ setBackgroundColor:[UIColor blackColor]];
7962 [[self navigationItem] setHidesBackButton:YES];
7964 [self updateCancel];
7968 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7969 [super webView:view didClearWindowObject:window forFrame:frame];
7970 [window setValue:progress_ forKey:@"cydiaProgress"];
7973 - (void) updateProgress {
7974 [self dispatchEvent:@"CydiaProgressUpdate"];
7977 - (void) viewWillAppear:(BOOL)animated {
7978 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
7979 [super viewWillAppear:animated];
7982 - (void) reloadSpringBoard {
7983 pid_t pid(ExecFork());
7985 pid_t pid(ExecFork());
7987 execl("/usr/bin/sbreload", "sbreload", NULL);
7998 system("/usr/bin/killall SpringBoard");
8002 UpdateExternalStatus(0);
8005 [delegate_ saveState];
8009 [delegate_ returnToCydia];
8013 [delegate_ terminateWithSuccess];
8014 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
8015 [delegate_ suspendWithAnimation:YES];
8017 [delegate_ suspend];*/
8029 UIProgressHUD *hud([delegate_ addProgressHUD]);
8030 [hud setText:UCLocalize("LOADING")];
8031 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
8037 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
8038 SBReboot(SBSSpringBoardServerPort());
8040 reboot2(RB_AUTOBOOT);
8047 - (void) setTitle:(NSString *)title {
8048 [progress_ setTitle:title];
8049 [self updateProgress];
8052 - (UIBarButtonItem *) rightButton {
8053 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
8054 initWithTitle:UCLocalize("CLOSE")
8055 style:UIBarButtonItemStylePlain
8057 action:@selector(close)
8061 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
8062 UpdateExternalStatus(1);
8064 [progress_ setRunning:true];
8065 [self setTitle:title];
8066 // implicit updateProgress
8068 SHA1SumValue notifyconf; {
8070 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
8073 MMap mmap(file, MMap::ReadOnly);
8075 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
8076 notifyconf = sha1.Result();
8080 SHA1SumValue springlist; {
8082 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
8085 MMap mmap(file, MMap::ReadOnly);
8087 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
8088 springlist = sha1.Result();
8092 if (invocation != nil) {
8093 [invocation yieldToSelector:@selector(invoke)];
8094 [self setTitle:@"COMPLETE"];
8099 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
8102 MMap mmap(file, MMap::ReadOnly);
8104 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
8105 if (!(notifyconf == sha1.Result()))
8112 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
8115 MMap mmap(file, MMap::ReadOnly);
8117 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
8118 if (!(springlist == sha1.Result()))
8124 if (RestartSubstrate_)
8128 RestartSubstrate_ = false;
8131 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
8132 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
8133 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
8134 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
8135 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
8138 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
8140 [progress_ setRunning:false];
8141 [self updateProgress];
8143 [self applyRightButton];
8146 - (void) addProgressEvent:(CydiaProgressEvent *)event {
8147 [progress_ addEvent:event];
8148 [self updateProgress];
8151 - (bool) isProgressCancelled {
8152 return cancel_ == 2;
8157 [self updateCancel];
8160 - (void) setCancellable:(bool)cancellable {
8161 unsigned cancel(cancel_);
8165 else if (cancel_ == 0)
8168 if (cancel != cancel_)
8169 [self updateCancel];
8172 - (void) setProgressCancellable:(NSNumber *)cancellable {
8173 [self setCancellable:[cancellable boolValue]];
8176 - (void) setProgressPercent:(NSNumber *)percent {
8177 [progress_ setPercent:[percent floatValue]];
8178 [self updateProgress];
8181 - (void) setProgressStatus:(NSDictionary *)status {
8182 if (status == nil) {
8183 [progress_ setCurrent:0];
8184 [progress_ setTotal:0];
8185 [progress_ setSpeed:0];
8187 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
8189 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
8190 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
8191 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
8194 [self updateProgress];
8200 /* Source Cell {{{ */
8201 @interface SourceCell : CyteTableViewCell <
8202 CyteTableViewCellDelegate
8206 _H<NSString> origin_;
8207 _H<NSString> label_;
8210 - (void) setSource:(Source *)source;
8214 @implementation SourceCell
8216 - (void) _setImage:(NSArray *)data {
8217 if ([url_ isEqual:[data objectAtIndex:0]]) {
8218 icon_ = [data objectAtIndex:1];
8219 [content_ setNeedsDisplay];
8223 - (void) _setSource:(NSURL *) url {
8224 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8226 if (NSData *data = [NSURLConnection
8227 sendSynchronousRequest:[NSURLRequest
8229 cachePolicy:NSURLRequestUseProtocolCachePolicy
8233 returningResponse:NULL
8236 if (UIImage *image = [UIImage imageWithData:data])
8237 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8242 - (void) setSource:(Source *)source {
8243 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8245 origin_ = [source name];
8246 label_ = [source rooturi];
8248 [content_ setNeedsDisplay];
8250 url_ = [source iconURL];
8251 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8254 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8255 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8256 UIView *content([self contentView]);
8257 CGRect bounds([content bounds]);
8259 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8260 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8261 [content_ setBackgroundColor:[UIColor whiteColor]];
8262 [content addSubview:content_];
8264 [content_ setDelegate:self];
8265 [content_ setOpaque:YES];
8267 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8271 - (NSString *) accessibilityLabel {
8275 - (void) drawContentRect:(CGRect)rect {
8276 bool highlighted(highlighted_);
8277 float width(rect.size.width);
8281 rect.size = [(UIImage *) icon_ size];
8283 while (rect.size.width > 32 || rect.size.height > 32) {
8284 rect.size.width /= 2;
8285 rect.size.height /= 2;
8288 rect.origin.x = 25 - rect.size.width / 2;
8289 rect.origin.y = 25 - rect.size.height / 2;
8291 [icon_ drawInRect:rect];
8299 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 65) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8303 [label_ drawAtPoint:CGPointMake(48, 29) forWidth:(width - 65) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8308 /* Sources Controller {{{ */
8309 @interface SourcesController : CyteViewController <
8310 UITableViewDataSource,
8313 _transient Database *database_;
8316 _H<UITableView, 2> list_;
8317 _H<NSMutableArray> sources_;
8321 _H<UIProgressHUD> hud_;
8324 //NSURLConnection *installer_;
8325 NSURLConnection *trivial_;
8326 NSURLConnection *trivial_bz2_;
8327 NSURLConnection *trivial_gz_;
8328 //NSURLConnection *automatic_;
8333 - (id) initWithDatabase:(Database *)database;
8334 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8338 @implementation SourcesController
8340 - (void) _releaseConnection:(NSURLConnection *)connection {
8341 if (connection != nil) {
8342 [connection cancel];
8343 //[connection setDelegate:nil];
8344 [connection release];
8349 //[self _releaseConnection:installer_];
8350 [self _releaseConnection:trivial_];
8351 [self _releaseConnection:trivial_gz_];
8352 [self _releaseConnection:trivial_bz2_];
8353 //[self _releaseConnection:automatic_];
8358 - (NSURL *) navigationURL {
8359 return [NSURL URLWithString:@"cydia://sources"];
8362 - (void) viewDidAppear:(BOOL)animated {
8363 [super viewDidAppear:animated];
8364 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8367 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8371 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8375 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8376 return [sources_ count];
8379 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8380 @synchronized (database_) {
8381 if ([database_ era] != era_)
8384 NSUInteger index([indexPath row]);
8385 return index < [sources_ count] ? [sources_ objectAtIndex:index] : nil;
8388 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8389 static NSString *cellIdentifier = @"SourceCell";
8391 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8392 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8393 [cell setSource:[self sourceAtIndexPath:indexPath]];
8394 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8399 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8400 Source *source = [self sourceAtIndexPath:indexPath];
8401 if (source == nil) return;
8403 SectionsController *controller = [[[SectionsController alloc]
8404 initWithDatabase:database_
8408 [controller setDelegate:delegate_];
8410 [[self navigationController] pushViewController:controller animated:YES];
8413 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8414 Source *source = [self sourceAtIndexPath:indexPath];
8415 return [source record] != nil;
8418 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8419 if (editingStyle == UITableViewCellEditingStyleDelete) {
8420 Source *source = [self sourceAtIndexPath:indexPath];
8421 if (source == nil) return;
8423 [Sources_ removeObjectForKey:[source key]];
8424 [delegate_ _saveConfig];
8425 [delegate_ reloadDataWithInvocation:nil];
8430 [delegate_ addTrivialSource:href_];
8433 [delegate_ syncData];
8436 - (NSString *) getWarning {
8437 NSString *href(href_);
8438 NSRange colon([href rangeOfString:@"://"]);
8439 if (colon.location != NSNotFound)
8440 href = [href substringFromIndex:(colon.location + 3)];
8441 href = [href stringByAddingPercentEscapes];
8442 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8444 NSURL *url([NSURL URLWithString:href]);
8446 NSStringEncoding encoding;
8447 NSError *error(nil);
8449 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8450 return [warning length] == 0 ? nil : warning;
8454 - (void) _endConnection:(NSURLConnection *)connection {
8455 // XXX: the memory management in this method is horribly awkward
8457 NSURLConnection **field = NULL;
8458 if (connection == trivial_)
8460 else if (connection == trivial_bz2_)
8461 field = &trivial_bz2_;
8462 else if (connection == trivial_gz_)
8463 field = &trivial_gz_;
8464 _assert(field != NULL);
8465 [connection release];
8470 trivial_bz2_ == nil &&
8473 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8475 [delegate_ releaseNetworkActivityIndicator];
8477 [delegate_ removeProgressHUD:hud_];
8481 if (warning != nil) {
8482 UIAlertView *alert = [[[UIAlertView alloc]
8483 initWithTitle:UCLocalize("SOURCE_WARNING")
8486 cancelButtonTitle:UCLocalize("CANCEL")
8488 UCLocalize("ADD_ANYWAY"),
8492 [alert setContext:@"warning"];
8493 [alert setNumberOfRows:1];
8496 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8502 } else if (error_ != nil) {
8503 UIAlertView *alert = [[[UIAlertView alloc]
8504 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8505 message:[error_ localizedDescription]
8507 cancelButtonTitle:UCLocalize("OK")
8508 otherButtonTitles:nil
8511 [alert setContext:@"urlerror"];
8516 UIAlertView *alert = [[[UIAlertView alloc]
8517 initWithTitle:UCLocalize("NOT_REPOSITORY")
8518 message:UCLocalize("NOT_REPOSITORY_EX")
8520 cancelButtonTitle:UCLocalize("OK")
8521 otherButtonTitles:nil
8524 [alert setContext:@"trivial"];
8534 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8535 switch ([response statusCode]) {
8541 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8542 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8544 [self _endConnection:connection];
8547 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8548 [self _endConnection:connection];
8551 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8552 NSURL *url([NSURL URLWithString:href]);
8554 NSMutableURLRequest *request = [NSMutableURLRequest
8556 cachePolicy:NSURLRequestUseProtocolCachePolicy
8560 [request setHTTPMethod:method];
8562 if (Machine_ != NULL)
8563 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8565 if (UniqueID_ != nil)
8566 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8568 if ([url isCydiaSecure]) {
8569 if (UniqueID_ != nil)
8570 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8573 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8576 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8577 NSString *context([alert context]);
8579 if ([context isEqualToString:@"source"]) {
8582 NSString *href = [[alert textField] text];
8584 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8586 if (![href hasSuffix:@"/"])
8587 href_ = [href stringByAppendingString:@"/"];
8591 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8592 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8593 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8594 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8598 // XXX: this is stupid
8599 hud_ = [delegate_ addProgressHUD];
8600 [hud_ setText:UCLocalize("VERIFYING_URL")];
8601 [delegate_ retainNetworkActivityIndicator];
8610 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8611 } else if ([context isEqualToString:@"trivial"])
8612 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8613 else if ([context isEqualToString:@"urlerror"])
8614 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8615 else if ([context isEqualToString:@"warning"]) {
8618 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8627 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8632 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8633 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8634 [list_ setRowHeight:53];
8635 [(UITableView *) list_ setDataSource:self];
8636 [list_ setDelegate:self];
8637 [self setView:list_];
8640 - (void) viewDidLoad {
8641 [super viewDidLoad];
8643 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8644 [self updateButtonsForEditingStatusAnimated:NO];
8647 - (void) viewWillDisappear:(BOOL)animated {
8648 [super viewWillAppear:animated];
8650 [list_ setEditing:NO];
8651 [self updateButtonsForEditingStatusAnimated:NO];
8654 - (void) releaseSubviews {
8659 [super releaseSubviews];
8662 - (id) initWithDatabase:(Database *)database {
8663 if ((self = [super init]) != nil) {
8664 database_ = database;
8668 - (void) reloadData {
8671 @synchronized (database_) {
8672 era_ = [database_ era];
8674 sources_ = [NSMutableArray arrayWithCapacity:16];
8675 [sources_ addObjectsFromArray:[database_ sources]];
8677 [sources_ sortUsingSelector:@selector(compareByName:)];
8680 int count([sources_ count]);
8682 for (int i = 0; i != count; i++) {
8683 if ([[sources_ objectAtIndex:i] record] == nil)
8691 - (void) showAddSourcePrompt {
8692 UIAlertView *alert = [[[UIAlertView alloc]
8693 initWithTitle:UCLocalize("ENTER_APT_URL")
8696 cancelButtonTitle:UCLocalize("CANCEL")
8698 UCLocalize("ADD_SOURCE"),
8702 [alert setContext:@"source"];
8704 [alert setNumberOfRows:1];
8705 [alert addTextFieldWithValue:@"http://" label:@""];
8707 UITextInputTraits *traits = [[alert textField] textInputTraits];
8708 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8709 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8710 [traits setKeyboardType:UIKeyboardTypeURL];
8711 // XXX: UIReturnKeyDone
8712 [traits setReturnKeyType:UIReturnKeyNext];
8717 - (void) addButtonClicked {
8718 [self showAddSourcePrompt];
8721 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8722 BOOL editing([list_ isEditing]);
8724 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8725 initWithTitle:UCLocalize("ADD")
8726 style:UIBarButtonItemStylePlain
8728 action:@selector(addButtonClicked)
8729 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8731 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8732 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8733 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8735 action:@selector(editButtonClicked)
8736 ] autorelease] animated:animated];
8739 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8740 initWithTitle:UCLocalize("SETTINGS")
8741 style:UIBarButtonItemStylePlain
8743 action:@selector(settingsButtonClicked)
8748 - (void) settingsButtonClicked {
8749 [delegate_ showSettings];
8752 - (void) editButtonClicked {
8753 [list_ setEditing:![list_ isEditing] animated:YES];
8754 [self updateButtonsForEditingStatusAnimated:YES];
8760 /* Settings Controller {{{ */
8761 @interface SettingsController : CyteViewController <
8762 UITableViewDataSource,
8765 _transient Database *database_;
8766 // XXX: ok, "roledelegate_"?...
8767 _transient id roledelegate_;
8768 _H<UITableView, 2> table_;
8769 _H<UISegmentedControl> segment_;
8770 _H<UIView> container_;
8773 - (void) showDoneButton;
8774 - (void) resizeSegmentedControl;
8778 @implementation SettingsController
8781 table_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
8782 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8783 [table_ setDelegate:self];
8784 [(UITableView *) table_ setDataSource:self];
8785 [self setView:table_];
8787 NSArray *items = [NSArray arrayWithObjects:
8789 UCLocalize("HACKER"),
8790 UCLocalize("DEVELOPER"),
8792 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8793 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
8794 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8795 [container_ addSubview:segment_];
8798 - (void) viewDidLoad {
8799 [super viewDidLoad];
8801 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8804 if ([Role_ isEqualToString:@"User"]) index = 0;
8805 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8806 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8808 [segment_ setSelectedSegmentIndex:index];
8809 [self showDoneButton];
8812 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8813 [self resizeSegmentedControl];
8816 - (void) releaseSubviews {
8821 [super releaseSubviews];
8824 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8825 if ((self = [super init]) != nil) {
8826 database_ = database;
8827 roledelegate_ = delegate;
8831 - (void) resizeSegmentedControl {
8832 CGFloat width = [[self view] frame].size.width;
8833 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8836 - (void) viewWillAppear:(BOOL)animated {
8837 [super viewWillAppear:animated];
8839 [self resizeSegmentedControl];
8842 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8843 [self resizeSegmentedControl];
8846 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8847 [self resizeSegmentedControl];
8851 NSString *role(nil);
8853 switch ([segment_ selectedSegmentIndex]) {
8854 case 0: role = @"User"; break;
8855 case 1: role = @"Hacker"; break;
8856 case 2: role = @"Developer"; break;
8861 if (![role isEqualToString:Role_]) {
8862 bool rolling(Role_ == nil);
8865 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8869 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8873 [roledelegate_ loadData];
8875 [roledelegate_ updateData];
8879 - (void) segmentChanged:(UISegmentedControl *)control {
8880 [self showDoneButton];
8883 - (void) saveAndClose {
8886 [[self navigationItem] setRightBarButtonItem:nil];
8887 [[self navigationController] dismissModalViewControllerAnimated:YES];
8890 - (void) doneButtonClicked {
8891 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8892 [spinner startAnimating];
8893 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8894 [[self navigationItem] setRightBarButtonItem:spinItem];
8896 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8899 - (void) showDoneButton {
8900 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8901 initWithTitle:UCLocalize("DONE")
8902 style:UIBarButtonItemStyleDone
8904 action:@selector(doneButtonClicked)
8905 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8908 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8909 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8913 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8917 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8918 return nil; // This method is required by the protocol.
8921 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8923 return UCLocalize("ROLE_EX");
8925 return [NSString stringWithFormat:
8926 @"%@: %@\n%@: %@\n%@: %@",
8927 UCLocalize("USER"), UCLocalize("USER_EX"),
8928 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8929 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8934 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8935 return section == 3 ? 44.0f : 0;
8938 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8939 return section == 3 ? container_ : nil;
8942 - (void) reloadData {
8945 [table_ reloadData];
8950 /* Stash Controller {{{ */
8951 @interface StashController : CyteViewController {
8952 _H<UIActivityIndicatorView> spinner_;
8953 _H<UILabel> status_;
8954 _H<UILabel> caption_;
8959 @implementation StashController
8962 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8963 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8964 [self setView:view];
8966 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8968 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8969 CGRect spinrect = [spinner_ frame];
8970 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8971 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8972 [spinner_ setFrame:spinrect];
8973 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8974 [view addSubview:spinner_];
8975 [spinner_ startAnimating];
8978 captrect.size.width = [[self view] frame].size.width;
8979 captrect.size.height = 40.0f;
8980 captrect.origin.x = 0;
8981 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8982 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8983 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8984 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8985 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8986 [caption_ setTextColor:[UIColor whiteColor]];
8987 [caption_ setBackgroundColor:[UIColor clearColor]];
8988 [caption_ setShadowColor:[UIColor blackColor]];
8989 [caption_ setTextAlignment:UITextAlignmentCenter];
8990 [view addSubview:caption_];
8993 statusrect.size.width = [[self view] frame].size.width;
8994 statusrect.size.height = 30.0f;
8995 statusrect.origin.x = 0;
8996 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8997 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8998 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8999 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
9000 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
9001 [status_ setTextColor:[UIColor whiteColor]];
9002 [status_ setBackgroundColor:[UIColor clearColor]];
9003 [status_ setShadowColor:[UIColor blackColor]];
9004 [status_ setTextAlignment:UITextAlignmentCenter];
9005 [view addSubview:status_];
9008 - (void) releaseSubviews {
9013 [super releaseSubviews];
9019 @interface CYURLCache : SDURLCache {
9024 @implementation CYURLCache
9026 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
9029 else if ([event isEqualToString:@"no-cache"])
9031 else if ([event isEqualToString:@"store"])
9033 else if ([event isEqualToString:@"invalid"])
9035 else if ([event isEqualToString:@"memory"])
9037 else if ([event isEqualToString:@"disk"])
9039 else if ([event isEqualToString:@"miss"])
9042 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
9046 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
9047 if (NSURLResponse *response = [cached response])
9048 if (NSString *mime = [response MIMEType])
9049 if ([mime isEqualToString:@"text/cache-manifest"]) {
9050 NSURL *url([response URL]);
9053 NSLog(@"###: %@", [url absoluteString]);
9056 @synchronized (HostConfig_) {
9057 [CachedURLs_ addObject:url];
9061 [super storeCachedResponse:cached forRequest:request];
9066 @interface Cydia : UIApplication <
9067 ConfirmationControllerDelegate,
9070 UINavigationControllerDelegate,
9071 UITabBarControllerDelegate
9073 _H<UIWindow> window_;
9074 _H<CYTabBarController> tabbar_;
9075 _H<CydiaLoadingViewController> emulated_;
9077 _H<NSMutableArray> essential_;
9078 _H<NSMutableArray> broken_;
9080 Database *database_;
9082 _H<NSURL> starturl_;
9087 _H<StashController> stash_;
9096 @implementation Cydia
9098 - (void) beginUpdate {
9099 [tabbar_ beginUpdate];
9103 return [tabbar_ updating];
9107 if ([broken_ count] != 0) {
9108 int count = [broken_ count];
9110 UIAlertView *alert = [[[UIAlertView alloc]
9111 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9112 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9114 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
9116 UCLocalize("TEMPORARY_IGNORE"),
9120 [alert setContext:@"fixhalf"];
9121 [alert setNumberOfRows:2];
9123 } else if (!Ignored_ && [essential_ count] != 0) {
9124 int count = [essential_ count];
9126 UIAlertView *alert = [[[UIAlertView alloc]
9127 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9128 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9130 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9132 UCLocalize("UPGRADE_ESSENTIAL"),
9133 UCLocalize("COMPLETE_UPGRADE"),
9137 [alert setContext:@"upgrade"];
9142 - (void) returnToCydia {
9146 - (void) _saveConfig {
9147 @synchronized (database_) {
9154 NSString *error(nil);
9156 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9158 NSError *error(nil);
9159 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9160 NSLog(@"failure to save metadata data: %@", error);
9165 NSLog(@"failure to serialize metadata: %@", error);
9169 CydiaWriteSources();
9172 - (void) unloadData {
9173 [tabbar_ unloadData];
9176 - (void) _updateData {
9181 - (void) _refreshIfPossible:(NSDate *)update {
9182 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9184 bool recently = false;
9185 if (update != nil) {
9186 NSTimeInterval interval([update timeIntervalSinceNow]);
9187 if (interval <= 0 && interval > -(15*60))
9191 // Don't automatic refresh if:
9192 // - We already refreshed recently.
9193 // - We already auto-refreshed this launch.
9194 // - Auto-refresh is disabled.
9195 if (recently || loaded_ || ManualRefresh) {
9196 // If we are cancelling, we need to make sure it knows it's already loaded.
9199 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9201 // We are going to load, so remember that.
9204 // If we can reach the server, auto-refresh!
9205 if (IsReachable("cydia.saurik.com"))
9206 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9212 - (void) refreshIfPossible {
9213 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9216 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9217 @synchronized (self) {
9218 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9219 [hud setText:UCLocalize("RELOADING_DATA")];
9221 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9225 [essential_ removeAllObjects];
9226 [broken_ removeAllObjects];
9228 NSArray *packages([database_ packages]);
9229 for (Package *package in packages) {
9231 [broken_ addObject:package];
9232 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9233 if ([package essential] && [package installed] != nil)
9234 [essential_ addObject:package];
9239 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9242 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9243 [changesItem setBadgeValue:badge];
9244 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9245 [self setApplicationIconBadgeNumber:changes];
9248 [changesItem setBadgeValue:nil];
9249 [changesItem setAnimatedBadge:NO];
9250 [self setApplicationIconBadgeNumber:0];
9256 [self removeProgressHUD:hud];
9259 - (void) updateData {
9263 - (void) updateDataAndLoad {
9265 if ([database_ progressDelegate] == nil)
9271 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9274 - (void) disemulate {
9275 if (emulated_ == nil)
9278 [window_ addSubview:[tabbar_ view]];
9279 [[emulated_ view] removeFromSuperview];
9281 [window_ setUserInteractionEnabled:YES];
9284 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9285 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9287 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9289 UIViewController *parent;
9290 if (emulated_ == nil)
9299 [parent presentModalViewController:navigation animated:YES];
9302 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9303 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9305 if (navigation != nil)
9306 [navigation pushViewController:progress animated:YES];
9308 [self presentModalViewController:progress force:YES];
9310 [progress invoke:invocation withTitle:title];
9314 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9315 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9318 - (void) repairWithInvocation:(NSInvocation *)invocation {
9320 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9324 - (void) repairWithSelector:(SEL)selector {
9325 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9328 - (void) reloadData {
9329 [self reloadDataWithInvocation:nil];
9330 if ([database_ progressDelegate] == nil)
9336 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9339 - (void) addSource:(NSDictionary *) source {
9340 CydiaAddSource(source);
9343 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9344 CydiaAddSource(href, distribution, sections);
9347 - (void) addTrivialSource:(NSString *)href {
9348 CydiaAddSource(href, @"./");
9351 - (void) updateValues {
9356 pkgProblemResolver *resolver = [database_ resolver];
9358 resolver->InstallProtect();
9359 if (!resolver->Resolve(true))
9363 - (void) clearPackage:(Package *)package {
9364 @synchronized (self) {
9370 - (void) installPackages:(NSArray *)packages {
9371 @synchronized (self) {
9372 for (Package *package in packages)
9378 - (void) installPackage:(Package *)package {
9379 @synchronized (self) {
9385 - (void) removePackage:(Package *)package {
9386 @synchronized (self) {
9392 - (void) distUpgrade {
9393 @synchronized (self) {
9394 if (![database_ upgrade])
9401 system("su -c /usr/bin/uicache mobile");
9406 UIProgressHUD *hud([self addProgressHUD]);
9407 [hud setText:UCLocalize("LOADING")];
9408 [self yieldToSelector:@selector(_uicache)];
9409 [self removeProgressHUD:hud];
9413 [database_ perform];
9414 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9415 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9418 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9420 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9424 - (void) showSettings {
9425 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9428 - (void) retainNetworkActivityIndicator {
9429 if (activity_++ == 0)
9430 [self setNetworkActivityIndicatorVisible:YES];
9433 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9437 - (void) releaseNetworkActivityIndicator {
9438 if (--activity_ == 0)
9439 [self setNetworkActivityIndicatorVisible:NO];
9442 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9447 - (void) clearQueue {
9448 @synchronized (self) {
9455 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9456 NSString *context([alert context]);
9458 if ([context isEqualToString:@"conffile"]) {
9459 FILE *input = [database_ input];
9460 if (button == [alert cancelButtonIndex])
9461 fprintf(input, "N\n");
9462 else if (button == [alert firstOtherButtonIndex])
9463 fprintf(input, "Y\n");
9466 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9467 } else if ([context isEqualToString:@"fixhalf"]) {
9468 if (button == [alert cancelButtonIndex]) {
9469 @synchronized (self) {
9470 for (Package *broken in (id) broken_) {
9473 NSString *id = [broken id];
9474 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9475 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9476 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9477 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9481 // XXX: [self perform];
9483 } else if (button == [alert firstOtherButtonIndex]) {
9484 [broken_ removeAllObjects];
9488 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9489 } else if ([context isEqualToString:@"upgrade"]) {
9490 if (button == [alert firstOtherButtonIndex]) {
9491 @synchronized (self) {
9492 for (Package *essential in (id) essential_)
9493 [essential install];
9496 // XXX: [self perform];
9498 } else if (button == [alert firstOtherButtonIndex] + 1) {
9500 } else if (button == [alert cancelButtonIndex]) {
9504 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9508 - (void) system:(NSString *)command {
9509 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9512 system([command UTF8String]);
9518 - (void) applicationWillSuspend {
9520 [super applicationWillSuspend];
9523 - (BOOL) isSafeToSuspend {
9526 NSLog(@"isSafeToSuspend: locked_ != 0");
9531 // Use external process status API internally.
9532 // This is probably a really bad idea.
9533 // XXX: what is the point of this? does this solve anything at all?
9534 uint64_t status = 0;
9536 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9537 notify_get_state(notify_token, &status);
9538 notify_cancel(notify_token);
9543 NSLog(@"isSafeToSuspend: status != 0");
9549 NSLog(@"isSafeToSuspend: -> true");
9554 - (void) applicationSuspend:(__GSEvent *)event {
9555 if ([self isSafeToSuspend])
9556 [super applicationSuspend:event];
9559 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9560 if ([self isSafeToSuspend])
9561 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9564 - (void) _setSuspended:(BOOL)value {
9565 if ([self isSafeToSuspend])
9566 [super _setSuspended:value];
9569 - (UIProgressHUD *) addProgressHUD {
9570 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9571 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9573 [window_ setUserInteractionEnabled:NO];
9575 UIViewController *target(tabbar_);
9576 if (UIViewController *modal = [target modalViewController])
9579 [hud showInView:[target view]];
9585 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9588 [hud removeFromSuperview];
9589 [window_ setUserInteractionEnabled:YES];
9592 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9593 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9596 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9597 NSString *scheme([[url scheme] lowercaseString]);
9598 if ([[url absoluteString] length] <= [scheme length] + 3)
9600 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9601 NSArray *components([path componentsSeparatedByString:@"/"]);
9603 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9604 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9605 if (controller != nil)
9606 [controller setDelegate:self];
9610 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9613 NSString *base([components objectAtIndex:0]);
9615 CyteViewController *controller = nil;
9617 if ([base isEqualToString:@"url"]) {
9618 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9619 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9620 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9621 } else if (!external && [components count] == 1) {
9622 if ([base isEqualToString:@"storage"]) {
9623 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9626 if ([base isEqualToString:@"sources"]) {
9627 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9630 if ([base isEqualToString:@"home"]) {
9631 controller = [[[HomeController alloc] init] autorelease];
9634 if ([base isEqualToString:@"sections"]) {
9635 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9638 if ([base isEqualToString:@"changes"]) {
9639 controller = [[[ChangesPackageListController alloc] initWithDatabase:database_] autorelease];
9642 if ([base isEqualToString:@"installed"]) {
9643 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9646 if ([base isEqualToString:@"queue"]) {
9647 controller = [[[ConfirmationController alloc] initWithDatabase:database_] autorelease];
9649 } else if ([components count] == 2) {
9650 NSString *argument = [components objectAtIndex:1];
9652 if ([base isEqualToString:@"package"]) {
9653 controller = [self pageForPackage:argument withReferrer:referrer];
9656 if (!external && [base isEqualToString:@"sections"]) {
9657 if ([argument isEqualToString:@"all"])
9659 controller = [[[SectionController alloc] initWithDatabase:database_ section:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] source:nil] autorelease];
9662 if (!external && [base isEqualToString:@"sources"]) {
9663 if ([argument isEqualToString:@"add"]) {
9664 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9665 [(SourcesController *)controller showAddSourcePrompt];
9669 if (!external && [base isEqualToString:@"launch"]) {
9670 [self launchApplicationWithIdentifier:argument suspended:NO];
9673 } else if ([components count] == 3) {
9674 NSString *arg1 = [components objectAtIndex:1];
9675 NSString *arg2 = [components objectAtIndex:2];
9677 if (!external && [base isEqualToString:@"package"]) {
9678 if ([arg2 isEqualToString:@"settings"]) {
9679 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9680 } else if ([arg2 isEqualToString:@"files"]) {
9681 if (Package *package = [database_ packageWithName:arg1]) {
9682 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9683 [(FileTable *)controller setPackage:package];
9688 if (!external && [base isEqualToString:@"sources"]) {
9689 Source *source = [database_ sourceWithKey:[arg1 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9690 NSString *section = [arg2 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9691 if ([section isEqualToString:@"all"])
9694 controller = [[[SectionController alloc] initWithDatabase:database_ section:arg2 source:source] autorelease];
9698 [controller setDelegate:self];
9702 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9703 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9706 [tabbar_ setUnselectedViewController:page];
9711 - (void) applicationOpenURL:(NSURL *)url {
9712 [super applicationOpenURL:url];
9717 [self openCydiaURL:url forExternal:YES];
9720 - (void) applicationWillResignActive:(UIApplication *)application {
9721 // Stop refreshing if you get a phone call or lock the device.
9722 if ([tabbar_ updating])
9723 [tabbar_ cancelUpdate];
9725 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9726 [super applicationWillResignActive:application];
9729 - (void) saveState {
9730 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9731 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9732 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9738 - (void) applicationWillTerminate:(UIApplication *)application {
9742 - (void) setConfigurationData:(NSString *)data {
9743 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9745 if (!conffile_r(data)) {
9746 lprintf("E:invalid conffile\n");
9750 NSString *ofile = conffile_r[1];
9751 //NSString *nfile = conffile_r[2];
9753 UIAlertView *alert = [[[UIAlertView alloc]
9754 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9755 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9757 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9759 UCLocalize("ACCEPT_NEW_COPY"),
9760 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9764 [alert setContext:@"conffile"];
9765 [alert setNumberOfRows:2];
9769 - (void) addStashController {
9771 stash_ = [[[StashController alloc] init] autorelease];
9772 [window_ addSubview:[stash_ view]];
9775 - (void) removeStashController {
9776 [[stash_ view] removeFromSuperview];
9782 [self setIdleTimerDisabled:YES];
9784 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9785 UpdateExternalStatus(1);
9786 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9787 UpdateExternalStatus(0);
9789 [self removeStashController];
9791 pid_t pid(ExecFork());
9793 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9794 perror("launchctl stop");
9801 - (void) setupViewControllers {
9802 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9804 NSMutableArray *items([NSMutableArray arrayWithObjects:
9805 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9806 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease],
9807 [[[UITabBarItem alloc] initWithTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES")) image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9808 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease],
9809 [[[UITabBarItem alloc] initWithTitle:UCLocalize("QUEUE") image:[UIImage applicationImageNamed:@"queue.png"] tag:0] autorelease],
9812 NSMutableArray *controllers([NSMutableArray array]);
9813 for (UITabBarItem *item in items) {
9814 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9815 [controller setTabBarItem:item];
9816 [controllers addObject:controller];
9818 [tabbar_ setViewControllers:controllers];
9820 [tabbar_ setUpdateDelegate:self];
9823 - (void) _sendMemoryWarningNotification {
9824 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9825 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9827 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9830 - (void) _sendMemoryWarningNotifications {
9832 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9838 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9840 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9843 - (void) applicationDidFinishLaunching:(id)unused {
9844 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9847 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9848 [self setApplicationSupportsShakeToEdit:NO];
9850 @synchronized (HostConfig_) {
9851 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9854 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9855 initWithMemoryCapacity:524288
9856 diskCapacity:10485760
9857 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9860 [CydiaWebViewController _initialize];
9862 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9864 // this would disallow http{,s} URLs from accessing this data
9865 //[WebView registerURLSchemeAsLocal:@"cydia"];
9867 Font12_ = [UIFont systemFontOfSize:12];
9868 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9869 Font14_ = [UIFont systemFontOfSize:14];
9870 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9871 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9873 essential_ = [NSMutableArray arrayWithCapacity:4];
9874 broken_ = [NSMutableArray arrayWithCapacity:4];
9876 // XXX: I really need this thing... like, seriously... I'm sorry
9877 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9879 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9880 [window_ orderFront:self];
9881 [window_ makeKey:self];
9882 [window_ setHidden:NO];
9885 [self addStashController];
9886 // XXX: this would be much cleaner as a yieldToSelector:
9887 // that way the removeStashController could happen right here inline
9888 // we also could no longer require the useless stash_ field anymore
9889 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9894 int error(stat("/", &root));
9895 _assert(error != -1);
9897 #define Stash_(path) do { \
9898 struct stat folder; \
9899 int error(lstat((path), &folder)); \
9900 if (error != -1 && ( \
9901 folder.st_dev == root.st_dev && \
9902 S_ISDIR(folder.st_mode) \
9903 ) || error == -1 && ( \
9904 errno == ENOENT || \
9909 Stash_("/Applications");
9910 Stash_("/Library/Ringtones");
9911 Stash_("/Library/Wallpaper");
9912 //Stash_("/usr/bin");
9913 Stash_("/usr/include");
9914 Stash_("/usr/lib/pam");
9915 Stash_("/usr/libexec");
9916 Stash_("/usr/share");
9917 //Stash_("/var/lib");
9919 database_ = [Database sharedInstance];
9920 [database_ setDelegate:self];
9922 [window_ setUserInteractionEnabled:NO];
9923 [self setupViewControllers];
9925 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9926 [window_ addSubview:[emulated_ view]];
9928 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9932 - (NSArray *) defaultStartPages {
9933 NSMutableArray *standard = [NSMutableArray array];
9934 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9935 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9936 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9937 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9938 [standard addObject:[NSArray arrayWithObject:@"cydia://queue"]];
9945 [window_ setUserInteractionEnabled:YES];
9946 [self showSettings];
9949 if ([emulated_ modalViewController] != nil)
9950 [emulated_ dismissModalViewControllerAnimated:YES];
9951 [window_ setUserInteractionEnabled:NO];
9954 [self reloadDataWithInvocation:nil];
9955 [self refreshIfPossible];
9960 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9961 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9962 int standardIndex = 0;
9963 NSArray *standard = [self defaultStartPages];
9970 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9971 if (valid && closed != nil) {
9972 NSTimeInterval interval([closed timeIntervalSinceNow]);
9973 // XXX: Is 30 minutes the optimal time here?
9974 if (interval <= -(30*60))
9978 if (valid && [saved count] != [standard count])
9982 for (unsigned int i = 0; i < [standard count]; i++) {
9983 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9984 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9985 // but it's good enough for now.
9986 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9993 NSArray *items = nil;
9995 [tabbar_ setSelectedIndex:savedIndex];
9998 [tabbar_ setSelectedIndex:standardIndex];
10002 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10003 NSArray *stack = [items objectAtIndex:tab];
10004 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10005 NSMutableArray *current = [NSMutableArray array];
10007 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10008 NSString *addr = [stack objectAtIndex:nav];
10009 NSURL *url = [NSURL URLWithString:addr];
10010 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10012 [current addObject:page];
10015 [navigation setViewControllers:current];
10018 // (Try to) show the startup URL.
10019 if (starturl_ != nil) {
10020 [self openCydiaURL:starturl_ forExternal:NO];
10025 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10026 if (item != nil && IsWildcat_) {
10027 [sheet showFromBarButtonItem:item animated:YES];
10029 [sheet showInView:window_];
10033 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10034 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10035 [progress setTitle:task];
10036 [progress addProgressEvent:event];
10039 - (void) addProgressEventForTask:(NSArray *)data {
10040 CydiaProgressEvent *event([data objectAtIndex:0]);
10041 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10042 [self addProgressEvent:event forTask:task];
10045 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10046 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10052 id Alloc_(id self, SEL selector) {
10053 id object = alloc_(self, selector);
10054 lprintf("[%s]A-%p\n", self->isa->name, object);
10059 id Dealloc_(id self, SEL selector) {
10060 id object = dealloc_(self, selector);
10061 lprintf("[%s]D-%p\n", self->isa->name, object);
10065 Class $WebDefaultUIKitDelegate;
10067 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
10068 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
10069 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
10070 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
10073 static NSSet *MobilizedFiles_;
10075 static NSURL *MobilizeURL(NSURL *url) {
10076 NSString *path([url path]);
10077 if ([path hasPrefix:@"/var/root/"]) {
10078 NSString *file([path substringFromIndex:10]);
10079 if ([MobilizedFiles_ containsObject:file])
10080 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10086 Class $CFXPreferencesPropertyListSource;
10087 @class CFXPreferencesPropertyListSource;
10089 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10090 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10091 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10092 url = MobilizeURL(url);
10093 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10094 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10100 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10101 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10102 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10103 url = MobilizeURL(url);
10104 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10105 //NSLog(@"%@ %@", [url absoluteString], value);
10111 Class $NSURLConnection;
10113 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10114 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10116 NSURL *url([copy URL]);
10118 NSString *host([url host]);
10119 NSString *scheme([[url scheme] lowercaseString]);
10121 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10123 @synchronized (HostConfig_) {
10124 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10125 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10126 [copy setHTTPShouldUsePipelining:YES];
10128 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10129 if ([control isEqualToString:@"max-age=0"])
10130 if ([CachedURLs_ containsObject:url]) {
10132 NSLog(@"~~~: %@", url);
10135 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10137 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10138 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10139 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10143 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10149 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10150 CGSize size([[UIScreen mainScreen] bounds].size);
10151 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10152 if ([$WAKWindow hasLandscapeOrientation])
10153 std::swap(size.width, size.height);*/
10157 int main(int argc, char *argv[]) {
10158 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10162 UpdateExternalStatus(0);
10164 if (Class $UIDevice = objc_getClass("UIDevice")) {
10165 UIDevice *device([$UIDevice currentDevice]);
10166 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10168 IsWildcat_ = false;
10170 UIScreen *screen([UIScreen mainScreen]);
10171 if ([screen respondsToSelector:@selector(scale)])
10172 ScreenScale_ = [screen scale];
10176 UIDevice *device([UIDevice currentDevice]);
10177 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10178 Idiom_ = @"iphone";
10180 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10181 if (idiom == UIUserInterfaceIdiomPhone)
10182 Idiom_ = @"iphone";
10183 else if (idiom == UIUserInterfaceIdiomPad)
10186 NSLog(@"unknown UIUserInterfaceIdiom!");
10189 Pcre pattern("^([0-9]+\\.[0-9]+)");
10191 if (pattern([device systemVersion]))
10192 Firmware_ = pattern[1];
10193 if (pattern(Cydia_))
10194 Major_ = pattern[1];
10196 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10198 HostConfig_ = [[[NSObject alloc] init] autorelease];
10199 @synchronized (HostConfig_) {
10200 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10201 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10202 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10203 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10204 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10207 NSString *ui(@"ui/ios");
10209 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10210 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10211 UI_ = CydiaURL(ui);
10213 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10215 MobilizedFiles_ = [NSMutableSet setWithObjects:
10216 @"Library/Preferences/com.apple.Accessibility.plist",
10217 @"Library/Preferences/com.apple.preferences.sounds.plist",
10220 /* Library Hacks {{{ */
10221 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10223 $WAKWindow = objc_getClass("WAKWindow");
10224 if ($WAKWindow != NULL)
10225 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10226 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10228 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10230 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10231 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10232 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10233 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10236 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10237 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10238 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10239 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10242 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10243 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10244 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10245 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10246 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10249 $NSURLConnection = objc_getClass("NSURLConnection");
10250 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10251 if (NSURLConnection$init$ != NULL) {
10252 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10253 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10256 /* Set Locale {{{ */
10257 Locale_ = CFLocaleCopyCurrent();
10258 Languages_ = [NSLocale preferredLanguages];
10260 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10261 //NSLog(@"%@", [Languages_ description]);
10264 if (Locale_ != NULL)
10265 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10266 else if (Languages_ != nil && [Languages_ count] != 0)
10267 lang = [[Languages_ objectAtIndex:0] UTF8String];
10269 // XXX: consider just setting to C and then falling through?
10272 if (lang != NULL) {
10273 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10274 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10277 NSLog(@"Setting Language: %s", lang);
10279 if (lang != NULL) {
10280 setenv("LANG", lang, true);
10281 std::setlocale(LC_ALL, lang);
10285 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10287 /* Parse Arguments {{{ */
10288 bool substrate(false);
10294 for (int argi(1); argi != argc; ++argi)
10295 if (strcmp(argv[argi], "--") == 0) {
10297 argv[argi] = argv[0];
10303 for (int argi(1); argi != arge; ++argi)
10304 if (strcmp(args[argi], "--substrate") == 0)
10307 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10311 App_ = [[NSBundle mainBundle] bundlePath];
10317 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10318 alloc_ = alloc->method_imp;
10319 alloc->method_imp = (IMP) &Alloc_;*/
10321 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10322 dealloc_ = dealloc->method_imp;
10323 dealloc->method_imp = (IMP) &Dealloc_;*/
10325 /* System Information {{{ */
10329 size = sizeof(maxproc);
10330 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10331 perror("sysctlbyname(\"kern.maxproc\", ?)");
10332 else if (maxproc < 64) {
10334 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10335 perror("sysctlbyname(\"kern.maxproc\", #)");
10338 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10339 char *osversion = new char[size];
10340 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10341 perror("sysctlbyname(\"kern.osversion\", ?)");
10343 System_ = [NSString stringWithUTF8String:osversion];
10345 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10346 char *machine = new char[size];
10347 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10348 perror("sysctlbyname(\"hw.machine\", ?)");
10350 Machine_ = machine;
10352 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10353 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10354 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10356 UniqueID_ = [device uniqueIdentifier];
10358 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10359 Product_ = [info objectForKey:@"SafariProductVersion"];
10360 Safari_ = [info objectForKey:@"CFBundleVersion"];
10363 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10365 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10366 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10367 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10368 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10369 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10370 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10372 UserAgent_ = agent;
10374 /* Load Database {{{ */
10376 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10378 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10380 if (Metadata_ == NULL)
10381 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10383 Settings_ = [Metadata_ objectForKey:@"Settings"];
10385 Packages_ = [Metadata_ objectForKey:@"Packages"];
10387 Values_ = [Metadata_ objectForKey:@"Values"];
10388 Sections_ = [Metadata_ objectForKey:@"Sections"];
10389 Sources_ = [Metadata_ objectForKey:@"Sources"];
10391 Token_ = [Metadata_ objectForKey:@"Token"];
10393 Version_ = [Metadata_ objectForKey:@"Version"];
10396 if (Settings_ != nil)
10397 Role_ = [Settings_ objectForKey:@"Role"];
10399 if (Values_ == nil) {
10400 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10401 [Metadata_ setObject:Values_ forKey:@"Values"];
10404 if (Sections_ == nil) {
10405 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10406 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10409 if (Sources_ == nil) {
10410 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10411 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10414 if (Version_ == nil) {
10415 Version_ = [NSNumber numberWithUnsignedInt:0];
10416 [Metadata_ setObject:Version_ forKey:@"Version"];
10419 if ([Version_ unsignedIntValue] == 0) {
10420 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10421 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10422 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10423 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10425 Version_ = [NSNumber numberWithUnsignedInt:1];
10426 [Metadata_ setObject:Version_ forKey:@"Version"];
10428 [Metadata_ removeObjectForKey:@"LastUpdate"];
10434 CydiaWriteSources();
10437 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10440 if (Packages_ != nil) {
10442 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10446 [Metadata_ removeObjectForKey:@"Packages"];
10452 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10454 #define MobileSubstrate_(name) \
10455 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10456 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10457 if (handle == NULL) \
10458 NSLog(@"%s", dlerror()); \
10461 MobileSubstrate_(Activator)
10462 MobileSubstrate_(libstatusbar)
10463 MobileSubstrate_(SimulatedKeyEvents)
10464 MobileSubstrate_(WinterBoard)
10466 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10467 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10469 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10471 if (access("/User", F_OK) != 0 || version != 5) {
10473 system("/usr/libexec/cydia/firmware.sh");
10477 _assert([[NSFileManager defaultManager]
10478 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10479 withIntermediateDirectories:YES
10484 if (access("/tmp/cydia.chk", F_OK) == 0) {
10485 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10486 _assert(errno == ENOENT);
10487 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10488 _assert(errno == ENOENT);
10491 /* APT Initialization {{{ */
10492 _assert(pkgInitConfig(*_config));
10493 _assert(pkgInitSystem(*_config, _system));
10496 _config->Set("APT::Acquire::Translation", lang);
10498 // XXX: this timeout might be important :(
10499 //_config->Set("Acquire::http::Timeout", 15);
10501 _config->Set("Acquire::http::MaxParallel", 3);
10503 /* Color Choices {{{ */
10504 space_ = CGColorSpaceCreateDeviceRGB();
10506 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10507 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10508 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10509 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10510 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10511 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10512 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10513 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10514 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10516 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10517 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10519 /* UIKit Configuration {{{ */
10520 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10521 if ($GSFontSetUseLegacyFontMetrics != NULL)
10522 $GSFontSetUseLegacyFontMetrics(YES);
10524 // XXX: I have a feeling this was important
10525 //UIKeyboardDisableAutomaticAppearance();
10528 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemHasCapability"));
10529 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10531 ShowPromoted_ = fast;
10532 PulseInterval_ = fast ? 50000 : 500000;
10534 Colon_ = UCLocalize("COLON_DELIMITED");
10535 Elision_ = UCLocalize("ELISION");
10536 Error_ = UCLocalize("ERROR");
10537 Warning_ = UCLocalize("WARNING");
10540 AprilFools_ = true;
10542 CFGregorianDate date(CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem()));
10543 AprilFools_ = date.month == 4 && date.day == 1;
10547 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10549 CGColorSpaceRelease(space_);
10550 CFRelease(Locale_);