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 <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
105 #include <sys/reboot.h>
112 #include <mach-o/nlist.h>
121 #include <Cytore.hpp>
123 #include <CydiaSubstrate/CydiaSubstrate.h>
124 #include "Menes/Menes.h"
126 #include "CyteKit/PerlCompatibleRegEx.hpp"
127 #include "CyteKit/TableViewCell.h"
128 #include "CyteKit/WebScriptObject-Cyte.h"
129 #include "CyteKit/WebViewController.h"
130 #include "CyteKit/stringWithUTF8Bytes.h"
132 #include "Cydia/MIMEAddress.h"
133 #include "Cydia/LoadingViewController.h"
134 #include "Cydia/ProgressEvent.h"
136 #include "SDURLCache/SDURLCache.h"
143 #define _timestamp ({ \
145 gettimeofday(&tv, NULL); \
146 tv.tv_sec * 1000000 + tv.tv_usec; \
149 typedef std::vector<class ProfileTime *> TimeList;
159 ProfileTime(const char *name) :
163 times_.push_back(this);
166 void AddTime(uint64_t time) {
173 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
185 ProfileTimer(ProfileTime &time) :
192 time_.AddTime(_timestamp - start_);
197 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
199 std::cerr << "========" << std::endl;
202 #define _profile(name) { \
203 static ProfileTime name(#name); \
204 ProfileTimer _ ## name(name);
210 #define Cydia_ CYDIA_VERSION
212 #define lprintf(args...) fprintf(stderr, args)
215 #define TraceLogging (1 && !ForRelease)
216 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
217 #define ProfileTimes (0 && !ForRelease)
218 #define ForSaurik (0 && !ForRelease)
219 #define LogBrowser (0 && !ForRelease)
220 #define TrackResize (0 && !ForRelease)
221 #define ManualRefresh (1 && !ForRelease)
222 #define ShowInternals (0 && !ForRelease)
223 #define AlwaysReload (0 && !ForRelease)
224 #define TryIndexedCollation (0 && !ForRelease)
228 #define _trace(args...)
233 #define _profile(name) {
236 #define PrintTimes() do {} while (false)
239 // Hash Functions/Structures {{{
240 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
248 static NSString *Colon_;
250 static NSString *Error_;
251 static NSString *Warning_;
253 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
255 static _finline NSString *CydiaURL(NSString *path) {
257 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
258 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
259 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
260 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
261 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
263 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
266 static _finline void UpdateExternalStatus(uint64_t newStatus) {
268 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
269 notify_set_state(notify_token, newStatus);
270 notify_cancel(notify_token);
272 notify_post("com.saurik.Cydia.status");
275 static CGFloat CYStatusBarHeight(UIInterfaceOrientation orientation) {
276 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
277 return UIInterfaceOrientationIsPortrait(orientation) ? size.height : size.width;
280 /* NSForcedOrderingSearch doesn't work on the iPhone */
281 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
282 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
283 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
285 /* Insertion Sort {{{ */
287 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
288 const char *ptr = (const char *)list;
290 CFIndex half = count / 2;
291 const char *probe = ptr + elementSize * half;
292 CFComparisonResult cr = comparator(element, probe, context);
293 if (0 == cr) return (probe - (const char *)list) / elementSize;
294 ptr = (cr < 0) ? ptr : probe + elementSize;
295 count = (cr < 0) ? half : (half + (count & 1) - 1);
297 return (ptr - (const char *)list) / elementSize;
300 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
301 const char *ptr = (const char *)list;
303 CFIndex half = count / 2;
304 const char *probe = ptr + elementSize * half;
305 CFComparisonResult cr = comparator(element, probe, context);
306 if (0 == cr) return (probe - (const char *)list) / elementSize;
307 ptr = (cr < 0) ? ptr : probe + elementSize;
308 count = (cr < 0) ? half : (half + (count & 1) - 1);
310 return (ptr - (const char *)list) / elementSize;
313 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
314 if (range.length == 0)
316 const void **values(new const void *[range.length]);
317 CFArrayGetValues(array, range, values);
319 #if HistogramInsertionSort > 0
320 uint32_t total(0), *offsets(new uint32_t[range.length]);
323 for (CFIndex index(1); index != range.length; ++index) {
324 const void *value(values[index]);
325 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
326 CFIndex correct(index);
327 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
328 #if HistogramInsertionSort > 1
329 NSLog(@"%@ < %@", value, values[correct - 1]);
334 if (correct != index) {
335 size_t offset(index - correct);
336 #if HistogramInsertionSort
340 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
342 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
343 values[correct] = value;
347 CFArrayReplaceValues(array, range, values, range.length);
350 #if HistogramInsertionSort > 0
351 for (CFIndex index(0); index != range.length; ++index)
352 if (offsets[index] != 0)
353 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
354 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
361 /* Apple Bug Fixes {{{ */
362 @implementation UIWebDocumentView (Cydia)
364 - (void) _setScrollerOffset:(CGPoint)offset {
365 UIScroller *scroller([self _scroller]);
367 CGSize size([scroller contentSize]);
368 CGSize bounds([scroller bounds].size);
371 max.x = size.width - bounds.width;
372 max.y = size.height - bounds.height;
380 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
381 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
383 [scroller setOffset:offset];
389 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
390 size_t length([self length] - state->state);
393 else if (length > count)
395 for (size_t i(0); i != length; ++i)
396 objects[i] = [self item:state->state++];
397 state->itemsPtr = objects;
398 state->mutationsPtr = (unsigned long *) self;
402 /* Cydia NSString Additions {{{ */
403 @interface NSString (Cydia)
404 - (NSComparisonResult) compareByPath:(NSString *)other;
405 - (NSString *) stringByCachingURLWithCurrentCDN;
406 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
409 @implementation NSString (Cydia)
411 - (NSComparisonResult) compareByPath:(NSString *)other {
412 NSString *prefix = [self commonPrefixWithString:other options:0];
413 size_t length = [prefix length];
415 NSRange lrange = NSMakeRange(length, [self length] - length);
416 NSRange rrange = NSMakeRange(length, [other length] - length);
418 lrange = [self rangeOfString:@"/" options:0 range:lrange];
419 rrange = [other rangeOfString:@"/" options:0 range:rrange];
421 NSComparisonResult value;
423 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
424 value = NSOrderedSame;
425 else if (lrange.location == NSNotFound)
426 value = NSOrderedAscending;
427 else if (rrange.location == NSNotFound)
428 value = NSOrderedDescending;
430 value = NSOrderedSame;
432 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
433 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
434 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
435 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
437 NSComparisonResult result = [lpath compare:rpath];
438 return result == NSOrderedSame ? value : result;
441 - (NSString *) stringByCachingURLWithCurrentCDN {
443 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
444 withString:@"://cache.cydia.saurik.com/"
448 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
449 return [(id)CFURLCreateStringByAddingPercentEscapes(
454 kCFStringEncodingUTF8
461 /* C++ NSString Wrapper Cache {{{ */
462 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
463 return size == 0 ? NULL :
464 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
465 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
468 static _finline CFStringRef CYStringCreate(const char *data) {
469 return CYStringCreate(data, strlen(data));
478 _finline void clear_() {
479 if (cache_ != NULL) {
486 _finline bool empty() const {
490 _finline size_t size() const {
494 _finline char *data() const {
498 _finline void clear() {
503 _finline CYString() :
510 _finline ~CYString() {
514 void operator =(const CYString &rhs) {
518 if (rhs.cache_ == nil)
521 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
524 void copy(apr_pool_t *pool) {
525 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
526 memcpy(temp, data_, size_);
531 void set(apr_pool_t *pool, const char *data, size_t size) {
537 data_ = const_cast<char *>(data);
545 _finline void set(apr_pool_t *pool, const char *data) {
546 set(pool, data, data == NULL ? 0 : strlen(data));
549 _finline void set(apr_pool_t *pool, const std::string &rhs) {
550 set(pool, rhs.data(), rhs.size());
553 bool operator ==(const CYString &rhs) const {
554 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
557 _finline operator CFStringRef() {
559 cache_ = CYStringCreate(data_, size_);
563 _finline operator id() {
564 return (NSString *) static_cast<CFStringRef>(*this);
567 _finline operator const char *() {
568 return reinterpret_cast<const char *>(data_);
572 /* C++ NSString Algorithm Adapters {{{ */
574 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
577 struct NSStringMapHash :
578 std::unary_function<NSString *, size_t>
580 _finline size_t operator ()(NSString *value) const {
581 return CFStringHashNSString((CFStringRef) value);
585 struct NSStringMapLess :
586 std::binary_function<NSString *, NSString *, bool>
588 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
589 return [lhs compare:rhs] == NSOrderedAscending;
593 struct NSStringMapEqual :
594 std::binary_function<NSString *, NSString *, bool>
596 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
597 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
598 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
599 //[lhs isEqualToString:rhs];
604 /* CoreGraphics Primitives {{{ */
609 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
610 CGFloat color[] = {red, green, blue, alpha};
611 return CGColorCreate(space, color);
620 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
621 color_(Create_(space, red, green, blue, alpha))
623 Set(space, red, green, blue, alpha);
628 CGColorRelease(color_);
635 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
637 color_ = Create_(space, red, green, blue, alpha);
640 operator CGColorRef() {
646 /* Random Global Variables {{{ */
647 static const int PulseInterval_ = 50000;
649 static const NSString *UI_;
652 static bool RestartSubstrate_;
653 static NSArray *Finishes_;
655 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
656 #define NotifyConfig_ "/etc/notify.conf"
658 static bool Queuing_;
660 static CYColor Blue_;
661 static CYColor Blueish_;
662 static CYColor Black_;
664 static CYColor White_;
665 static CYColor Gray_;
666 static CYColor Green_;
667 static CYColor Purple_;
668 static CYColor Purplish_;
670 static UIColor *InstallingColor_;
671 static UIColor *RemovingColor_;
673 static NSString *App_;
675 static BOOL Advanced_;
676 static BOOL Ignored_;
678 static _H<UIFont> Font12_;
679 static _H<UIFont> Font12Bold_;
680 static _H<UIFont> Font14_;
681 static _H<UIFont> Font18Bold_;
682 static _H<UIFont> Font22Bold_;
684 static const char *Machine_ = NULL;
685 static NSString *System_ = nil;
686 static NSString *SerialNumber_ = nil;
687 static NSString *ChipID_ = nil;
688 static NSString *BBSNum_ = nil;
689 static _H<NSString> Token_;
690 static NSString *UniqueID_ = nil;
691 static NSString *PLMN_ = nil;
692 static NSString *Build_ = nil;
693 static NSString *Product_ = nil;
694 static NSString *Safari_ = nil;
696 static CFLocaleRef Locale_;
697 static NSArray *Languages_;
698 static CGColorSpaceRef space_;
700 static NSDictionary *SectionMap_;
701 static NSMutableDictionary *Metadata_;
702 static _transient NSMutableDictionary *Settings_;
703 static _transient NSString *Role_;
704 static _transient NSMutableDictionary *Packages_;
705 static _transient NSMutableDictionary *Values_;
706 static _transient NSMutableDictionary *Sections_;
707 static _transient NSMutableDictionary *Sources_;
708 static _transient NSNumber *Version_;
709 static _transient _H<NSString> CydiaSource_;
710 static bool Changed_;
714 static CGFloat ScreenScale_;
715 static NSString *Idiom_;
717 static _H<NSMutableDictionary> SessionData_;
718 static _H<NSObject> HostConfig_;
719 static _H<NSMutableSet> BridgedHosts_;
720 static _H<NSMutableSet> TokenHosts_;
721 static _H<NSMutableSet> InsecureHosts_;
722 static _H<NSMutableSet> PipelinedHosts_;
723 static _H<NSMutableSet> CachedURLs_;
725 static NSString *kCydiaProgressEventTypeError = @"Error";
726 static NSString *kCydiaProgressEventTypeInformation = @"Information";
727 static NSString *kCydiaProgressEventTypeStatus = @"Status";
728 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
731 static void AddSource(NSDictionary *source) {
732 [Sources_ setObject:source forKey:[NSString stringWithFormat:@"%@:%@:%@", [source objectForKey:@"Type"], [source objectForKey:@"URI"], [source objectForKey:@"Distribution"]]];
736 static void AddSource(NSString *href, NSString *distribution, NSArray *sections = nil) {
737 AddSource([NSMutableDictionary dictionaryWithObjectsAndKeys:
740 distribution, @"Distribution",
741 sections ?: [NSMutableArray array], @"Sections",
745 static void WriteSources() {
746 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
747 _assert(file != NULL);
749 fprintf(file, "deb http://%s/ tangelo-3.7 main\n",
750 [CydiaSource_ UTF8String]
753 for (NSString *key in [Sources_ allKeys]) {
754 NSDictionary *source([Sources_ objectForKey:key]);
756 NSArray *sections([source objectForKey:@"Sections"] ?: [NSArray array]);
758 fprintf(file, "%s %s %s%s%s\n",
759 [[source objectForKey:@"Type"] UTF8String],
760 [[source objectForKey:@"URI"] UTF8String],
761 [[source objectForKey:@"Distribution"] UTF8String],
762 [sections count] == 0 ? "" : " ",
763 [[sections componentsJoinedByString:@" "] UTF8String]
770 /* Display Helpers {{{ */
771 inline float Interpolate(float begin, float end, float fraction) {
772 return (end - begin) * fraction + begin;
775 static _finline const char *StripVersion_(const char *version) {
776 const char *colon(strchr(version, ':'));
777 return colon == NULL ? version : colon + 1;
780 NSString *LocalizeSection(NSString *section) {
781 static Pcre title_r("^(.*?) \\((.*)\\)$");
782 if (title_r(section)) {
783 NSString *parent(title_r[1]);
784 NSString *child(title_r[2]);
786 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
787 LocalizeSection(parent),
788 LocalizeSection(child)
792 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
795 NSString *Simplify(NSString *title) {
796 const char *data = [title UTF8String];
797 size_t size = [title length];
799 static Pcre square_r("^\\[(.*)\\]$");
800 if (square_r(data, size))
801 return Simplify(square_r[1]);
803 static Pcre paren_r("^\\((.*)\\)$");
804 if (paren_r(data, size))
805 return Simplify(paren_r[1]);
807 static Pcre title_r("^(.*?) \\((.*)\\)$");
808 if (title_r(data, size))
809 return Simplify(title_r[1]);
815 NSString *GetLastUpdate() {
816 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
819 return UCLocalize("NEVER_OR_UNKNOWN");
821 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
822 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
824 CFRelease(formatter);
826 return [(NSString *) formatted autorelease];
829 bool isSectionVisible(NSString *section) {
830 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
831 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
832 return hidden == nil || ![hidden boolValue];
835 static NSObject *CYIOGetValue(const char *path, NSString *property) {
836 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
837 if (entry == MACH_PORT_NULL)
840 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
841 IOObjectRelease(entry);
845 return [(id) value autorelease];
848 static NSString *CYHex(NSData *data, bool reverse = false) {
852 size_t length([data length]);
853 uint8_t bytes[length];
854 [data getBytes:bytes];
856 char string[length * 2 + 1];
857 for (size_t i(0); i != length; ++i)
858 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
860 return [NSString stringWithUTF8String:string];
865 /* Delegate Prototypes {{{ */
868 @class CydiaProgressEvent;
870 @protocol DatabaseDelegate
871 - (void) repairWithSelector:(SEL)selector;
872 - (void) setConfigurationData:(NSString *)data;
873 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
876 @class CYPackageController;
878 @protocol CydiaDelegate
879 - (void) returnToCydia;
881 - (void) retainNetworkActivityIndicator;
882 - (void) releaseNetworkActivityIndicator;
883 - (void) clearPackage:(Package *)package;
884 - (void) installPackage:(Package *)package;
885 - (void) installPackages:(NSArray *)packages;
886 - (void) removePackage:(Package *)package;
887 - (void) beginUpdate;
889 - (void) distUpgrade;
893 - (void) addSource:(NSDictionary *)source;
894 - (void) addTrivialSource:(NSString *)href;
895 - (void) showSettings;
896 - (UIProgressHUD *) addProgressHUD;
897 - (void) removeProgressHUD:(UIProgressHUD *)hud;
898 - (CyteViewController *) pageForPackage:(NSString *)name;
899 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
900 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
904 /* Status Delegation {{{ */
906 public pkgAcquireStatus
909 _transient NSObject<ProgressDelegate> *delegate_;
919 void setDelegate(NSObject<ProgressDelegate> *delegate) {
920 delegate_ = delegate;
923 NSObject<ProgressDelegate> *getDelegate() const {
927 virtual bool MediaChange(std::string media, std::string drive) {
931 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
935 virtual void Fetch(pkgAcquire::ItemDesc &item) {
936 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
937 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
938 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
941 virtual void Done(pkgAcquire::ItemDesc &item) {
942 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
943 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
944 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
947 virtual void Fail(pkgAcquire::ItemDesc &item) {
949 item.Owner->Status == pkgAcquire::Item::StatIdle ||
950 item.Owner->Status == pkgAcquire::Item::StatDone
954 std::string &error(item.Owner->ErrorText);
958 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
959 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
962 virtual bool Pulse(pkgAcquire *Owner) {
963 bool value = pkgAcquireStatus::Pulse(Owner);
966 double(CurrentBytes + CurrentItems) /
967 double(TotalBytes + TotalItems)
970 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
971 [NSNumber numberWithDouble:percent], @"Percent",
973 [NSNumber numberWithDouble:CurrentBytes], @"Current",
974 [NSNumber numberWithDouble:TotalBytes], @"Total",
975 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
976 nil] waitUntilDone:YES];
978 if (value && ![delegate_ isProgressCancelled])
986 _finline bool WasCancelled() const {
990 virtual void Start() {
991 pkgAcquireStatus::Start();
992 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
995 virtual void Stop() {
996 pkgAcquireStatus::Stop();
997 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
998 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1002 /* Database Interface {{{ */
1003 typedef std::map< unsigned long, _H<Source> > SourceMap;
1005 @interface Database : NSObject {
1011 pkgCacheFile cache_;
1012 pkgDepCache::Policy *policy_;
1013 pkgRecords *records_;
1014 pkgProblemResolver *resolver_;
1015 pkgAcquire *fetcher_;
1017 SPtr<pkgPackageManager> manager_;
1018 pkgSourceList *list_;
1020 SourceMap sourceMap_;
1021 _H<NSMutableArray> sourceList_;
1023 CFMutableArrayRef packages_;
1025 _transient NSObject<DatabaseDelegate> *delegate_;
1026 _transient NSObject<ProgressDelegate> *progress_;
1034 std::map<const char *, _H<NSString> > sections_;
1037 + (Database *) sharedInstance;
1040 - (void) _readCydia:(NSNumber *)fd;
1041 - (void) _readStatus:(NSNumber *)fd;
1042 - (void) _readOutput:(NSNumber *)fd;
1046 - (Package *) packageWithName:(NSString *)name;
1048 - (pkgCacheFile &) cache;
1049 - (pkgDepCache::Policy *) policy;
1050 - (pkgRecords *) records;
1051 - (pkgProblemResolver *) resolver;
1052 - (pkgAcquire &) fetcher;
1053 - (pkgSourceList &) list;
1054 - (NSArray *) packages;
1055 - (NSArray *) sources;
1056 - (Source *) sourceWithKey:(NSString *)key;
1057 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1065 - (void) updateWithStatus:(Status &)status;
1067 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1069 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1070 - (NSObject<ProgressDelegate> *) progressDelegate;
1072 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1074 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1078 /* ProgressEvent Implementation {{{ */
1079 @implementation CydiaProgressEvent
1081 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1082 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1085 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1086 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1087 [event setPackage:package];
1091 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1092 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1094 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1095 NSArray *fields([description componentsSeparatedByString:@" "]);
1096 [event setItem:fields];
1098 if ([fields count] > 3) {
1099 [event setPackage:[fields objectAtIndex:2]];
1100 [event setVersion:[fields objectAtIndex:3]];
1103 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1108 + (NSArray *) _attributeKeys {
1109 return [NSArray arrayWithObjects:
1119 - (NSArray *) attributeKeys {
1120 return [[self class] _attributeKeys];
1123 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1124 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1127 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1128 if ((self = [super init]) != nil) {
1134 - (NSString *) message {
1138 - (NSString *) type {
1142 - (NSArray *) item {
1143 return (id) item_ ?: [NSNull null];
1146 - (void) setItem:(NSArray *)item {
1150 - (NSString *) package {
1151 return (id) package_ ?: [NSNull null];
1154 - (void) setPackage:(NSString *)package {
1158 - (NSString *) url {
1159 return (id) url_ ?: [NSNull null];
1162 - (void) setURL:(NSString *)url {
1166 - (void) setVersion:(NSString *)version {
1170 - (NSString *) version {
1171 return (id) version_ ?: [NSNull null];
1174 - (NSString *) compound:(NSString *)value {
1176 NSString *mode(nil); {
1177 NSString *type([self type]);
1178 if ([type isEqualToString:kCydiaProgressEventTypeError])
1179 mode = UCLocalize("ERROR");
1180 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1181 mode = UCLocalize("WARNING");
1185 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1191 - (NSString *) compoundMessage {
1192 return [self compound:[self message]];
1195 - (NSString *) compoundTitle {
1198 if (package_ == nil)
1200 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1201 title = [package name];
1205 return [self compound:title];
1211 // Cytore Definitions {{{
1212 struct PackageValue :
1215 Cytore::Offset<PackageValue> next_;
1217 uint32_t index_ : 23;
1218 uint32_t subscribed_ : 1;
1235 Cytore::Offset<PackageValue> packages_[1 << 16];
1238 static Cytore::File<MetaValue> MetaFile_;
1240 // Cytore Helper Functions {{{
1241 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1242 SplitHash nhash = { hashlittle(name, length) };
1244 PackageValue *metadata;
1246 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1247 offset: if (offset->IsNull()) {
1248 *offset = MetaFile_.New<PackageValue>(length + 1);
1249 metadata = &MetaFile_.Get(*offset);
1251 if (metadata == NULL) {
1255 metadata = new PackageValue();
1256 memset(metadata, 0, sizeof(*metadata));
1259 memcpy(metadata->name_, name, length + 1);
1260 metadata->nhash_ = nhash.u16[1];
1262 metadata = &MetaFile_.Get(*offset);
1264 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1265 offset = &metadata->next_;
1273 static void PackageImport(const void *key, const void *value, void *context) {
1274 bool &fail(*reinterpret_cast<bool *>(context));
1277 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1278 NSLog(@"failed to import package %@", key);
1282 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1283 NSDictionary *package((NSDictionary *) value);
1285 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1286 if ([subscribed boolValue] && !metadata->subscribed_)
1287 metadata->subscribed_ = true;
1289 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1290 time_t time([date timeIntervalSince1970]);
1291 if (metadata->first_ > time || metadata->first_ == 0)
1292 metadata->first_ = time;
1295 NSDate *date([package objectForKey:@"LastSeen"]);
1296 NSString *version([package objectForKey:@"LastVersion"]);
1298 if (date != nil && version != nil) {
1299 time_t time([date timeIntervalSince1970]);
1300 if (metadata->last_ < time || metadata->last_ == 0)
1301 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1302 size_t length(strlen(buffer));
1303 uint16_t vhash(hashlittle(buffer, length));
1305 size_t capped(std::min<size_t>(8, length));
1306 char *latest(buffer + length - capped);
1308 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1309 metadata->vhash_ = vhash;
1311 metadata->last_ = time;
1317 /* Source Class {{{ */
1318 @interface Source : NSObject {
1319 CYString depiction_;
1320 CYString description_;
1326 CYString distribution_;
1332 _H<NSString> authority_;
1334 CYString defaultIcon_;
1336 _H<NSDictionary> record_;
1340 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1342 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1344 - (NSString *) depictionForPackage:(NSString *)package;
1345 - (NSString *) supportForPackage:(NSString *)package;
1347 - (NSDictionary *) record;
1351 - (NSString *) distribution;
1352 - (NSString *) type;
1354 - (NSString *) base;
1357 - (NSString *) host;
1359 - (NSString *) name;
1360 - (NSString *) shortDescription;
1361 - (NSString *) label;
1362 - (NSString *) origin;
1363 - (NSString *) version;
1365 - (NSString *) defaultIcon;
1369 @implementation Source
1373 distribution_.clear();
1378 description_.clear();
1384 defaultIcon_.clear();
1391 + (NSString *) webScriptNameForSelector:(SEL)selector {
1393 else if (selector == @selector(addSection:))
1394 return @"addSection";
1395 else if (selector == @selector(removeSection:))
1396 return @"removeSection";
1397 else if (selector == @selector(remove))
1403 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1404 return [self webScriptNameForSelector:selector] == nil;
1407 + (NSArray *) _attributeKeys {
1408 return [NSArray arrayWithObjects:
1416 @"shortDescription",
1424 - (NSArray *) attributeKeys {
1425 return [[self class] _attributeKeys];
1428 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1429 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1432 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1435 trusted_ = index->IsTrusted();
1437 uri_.set(pool, index->GetURI());
1438 distribution_.set(pool, index->GetDist());
1439 type_.set(pool, index->GetType());
1441 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1442 if (dindex != NULL) {
1443 base_.set(pool, dindex->MetaIndexURI(""));
1446 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1449 pkgTagFile tags(&fd);
1451 pkgTagSection section;
1458 {"default-icon", &defaultIcon_},
1459 {"depiction", &depiction_},
1460 {"description", &description_},
1462 {"origin", &origin_},
1463 {"support", &support_},
1464 {"version", &version_},
1467 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1468 const char *start, *end;
1470 if (section.Find(names[i].name_, start, end)) {
1471 CYString &value(*names[i].value_);
1472 value.set(pool, start, end - start);
1478 record_ = [Sources_ objectForKey:[self key]];
1480 NSURL *url([NSURL URLWithString:uri_]);
1484 host_ = [host_ lowercaseString];
1489 authority_ = [url path];
1492 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1493 if ((self = [super init]) != nil) {
1494 [self setMetaIndex:index inPool:pool];
1498 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1499 NSDictionary *lhr = [self record];
1500 NSDictionary *rhr = [source record];
1502 if ((lhr == nil) != (rhr == nil))
1503 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1505 NSString *lhs = [self name];
1506 NSString *rhs = [source name];
1508 if ([lhs length] != 0 && [rhs length] != 0) {
1509 unichar lhc = [lhs characterAtIndex:0];
1510 unichar rhc = [rhs characterAtIndex:0];
1512 if (isalpha(lhc) && !isalpha(rhc))
1513 return NSOrderedAscending;
1514 else if (!isalpha(lhc) && isalpha(rhc))
1515 return NSOrderedDescending;
1518 return [lhs compare:rhs options:LaxCompareOptions_];
1521 - (NSString *) depictionForPackage:(NSString *)package {
1522 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1525 - (NSString *) supportForPackage:(NSString *)package {
1526 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1529 - (NSArray *) sections {
1530 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1533 - (void) _addSection:(NSString *)section {
1536 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1537 if (![sections containsObject:section]) {
1538 [sections addObject:section];
1542 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1547 - (bool) addSection:(NSString *)section {
1551 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1555 - (void) _removeSection:(NSString *)section {
1559 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1560 if ([sections containsObject:section]) {
1561 [sections removeObject:section];
1566 - (bool) removeSection:(NSString *)section {
1570 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1575 [Sources_ removeObjectForKey:[self key]];
1580 bool value(record_ != nil);
1581 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1585 - (NSDictionary *) record {
1593 - (NSString *) uri {
1597 - (NSString *) distribution {
1598 return distribution_;
1601 - (NSString *) type {
1605 - (NSString *) base {
1609 - (NSString *) key {
1610 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1613 - (NSString *) host {
1617 - (NSString *) name {
1618 return origin_.empty() ? (id) authority_ : origin_;
1621 - (NSString *) shortDescription {
1622 return description_;
1625 - (NSString *) label {
1626 return label_.empty() ? (id) authority_ : label_;
1629 - (NSString *) origin {
1633 - (NSString *) version {
1637 - (NSString *) defaultIcon {
1638 return defaultIcon_;
1643 /* CydiaOperation Class {{{ */
1644 @interface CydiaOperation : NSObject {
1645 _H<NSString> operator_;
1646 _H<NSString> value_;
1649 - (NSString *) operator;
1650 - (NSString *) value;
1654 @implementation CydiaOperation
1656 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1657 if ((self = [super init]) != nil) {
1658 operator_ = [NSString stringWithUTF8String:_operator];
1659 value_ = [NSString stringWithUTF8String:value];
1663 + (NSArray *) _attributeKeys {
1664 return [NSArray arrayWithObjects:
1670 - (NSArray *) attributeKeys {
1671 return [[self class] _attributeKeys];
1674 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1675 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1678 - (NSString *) operator {
1682 - (NSString *) value {
1688 /* CydiaClause Class {{{ */
1689 @interface CydiaClause : NSObject {
1690 _H<NSString> package_;
1691 _H<CydiaOperation> version_;
1694 - (NSString *) package;
1695 - (CydiaOperation *) version;
1699 @implementation CydiaClause
1701 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1702 if ((self = [super init]) != nil) {
1703 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1705 if (const char *version = dep.TargetVer())
1706 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1708 version_ = (id) [NSNull null];
1712 + (NSArray *) _attributeKeys {
1713 return [NSArray arrayWithObjects:
1719 - (NSArray *) attributeKeys {
1720 return [[self class] _attributeKeys];
1723 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1724 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1727 - (NSString *) package {
1731 - (CydiaOperation *) version {
1737 /* CydiaRelation Class {{{ */
1738 @interface CydiaRelation : NSObject {
1739 _H<NSString> relationship_;
1740 _H<NSMutableArray> clauses_;
1743 - (NSString *) relationship;
1744 - (NSArray *) clauses;
1748 @implementation CydiaRelation
1750 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1751 if ((self = [super init]) != nil) {
1752 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1753 clauses_ = [NSMutableArray arrayWithCapacity:8];
1755 pkgCache::DepIterator start;
1756 pkgCache::DepIterator end;
1757 dep.GlobOr(start, end); // ++dep
1760 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1762 // yes, seriously. (wtf?)
1770 + (NSArray *) _attributeKeys {
1771 return [NSArray arrayWithObjects:
1777 - (NSArray *) attributeKeys {
1778 return [[self class] _attributeKeys];
1781 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1782 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1785 - (NSString *) relationship {
1786 return relationship_;
1789 - (NSArray *) clauses {
1793 - (void) addClause:(CydiaClause *)clause {
1794 [clauses_ addObject:clause];
1799 /* Package Class {{{ */
1800 struct ParsedPackage {
1803 CYString architecture_;
1806 CYString depiction_;
1816 @interface Package : NSObject {
1819 uint32_t essential_ : 1;
1820 uint32_t obsolete_ : 1;
1821 uint32_t ignored_ : 1;
1827 _transient Database *database_;
1829 pkgCache::VerIterator version_;
1830 pkgCache::PkgIterator iterator_;
1831 pkgCache::VerFileIterator file_;
1837 CYString installed_;
1839 const char *section_;
1840 _transient NSString *section$_;
1844 PackageValue *metadata_;
1845 ParsedPackage *parsed_;
1847 _H<NSMutableArray> tags_;
1850 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1851 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1853 - (pkgCache::PkgIterator) iterator;
1856 - (NSString *) section;
1857 - (NSString *) simpleSection;
1859 - (NSString *) longSection;
1860 - (NSString *) shortSection;
1864 - (MIMEAddress *) maintainer;
1866 - (NSString *) longDescription;
1867 - (NSString *) shortDescription;
1870 - (PackageValue *) metadata;
1873 - (bool) subscribed;
1874 - (bool) setSubscribed:(bool)subscribed;
1878 - (NSString *) latest;
1879 - (NSString *) installed;
1880 - (BOOL) uninstalled;
1883 - (BOOL) upgradableAndEssential:(BOOL)essential;
1886 - (BOOL) unfiltered;
1890 - (BOOL) halfConfigured;
1891 - (BOOL) halfInstalled;
1893 - (NSString *) mode;
1896 - (NSString *) name;
1898 - (NSString *) homepage;
1899 - (NSString *) depiction;
1900 - (MIMEAddress *) author;
1902 - (NSString *) support;
1904 - (NSArray *) files;
1905 - (NSArray *) warnings;
1906 - (NSArray *) applications;
1908 - (Source *) source;
1911 - (BOOL) matches:(NSArray *)query;
1913 - (bool) hasSupportingRole;
1914 - (BOOL) hasTag:(NSString *)tag;
1915 - (NSString *) primaryPurpose;
1916 - (NSArray *) purposes;
1917 - (bool) isCommercial;
1919 - (void) setIndex:(size_t)index;
1921 - (CYString &) cyname;
1923 - (uint32_t) compareBySection:(NSArray *)sections;
1928 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1929 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1930 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1931 - (bool) isVisibleInSection:(NSString *)section;
1932 - (bool) isVisibleInSource:(Source *)source;
1936 uint32_t PackageChangesRadix(Package *self, void *) {
1941 uint32_t timestamp : 30;
1942 uint32_t ignored : 1;
1943 uint32_t upgradable : 1;
1947 bool upgradable([self upgradableAndEssential:YES]);
1948 value.bits.upgradable = upgradable ? 1 : 0;
1951 value.bits.timestamp = 0;
1952 value.bits.ignored = [self ignored] ? 0 : 1;
1953 value.bits.upgradable = 1;
1955 value.bits.timestamp = [self seen] >> 2;
1956 value.bits.ignored = 0;
1957 value.bits.upgradable = 0;
1960 return _not(uint32_t) - value.key;
1963 uint32_t PackagePrefixRadix(Package *self, void *context) {
1964 size_t offset(reinterpret_cast<size_t>(context));
1965 CYString &name([self cyname]);
1967 size_t size(name.size());
1970 char *text(name.data());
1973 if (!isdigit(text[0]))
1977 while (size != digits && isdigit(text[digits]))
1985 if (offset == 0 && zeros != 0) {
1986 memset(data, '0', zeros);
1987 memcpy(data + zeros, text, 4 - zeros);
1989 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1990 if (size <= offset - zeros)
1993 text += offset - zeros;
1994 size -= offset - zeros;
1997 memcpy(data, text, 4);
1999 memcpy(data, text, size);
2000 memset(data + size, 0, 4 - size);
2003 for (size_t i(0); i != 4; ++i)
2004 if (isalpha(data[i]))
2012 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2014 /* XXX: ntohl may be more honest */
2015 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2018 CYString &(*PackageName)(Package *self, SEL sel);
2020 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2021 _profile(PackageNameCompare)
2022 CYString &lhi(PackageName(lhs, @selector(cyname)));
2023 CYString &rhi(PackageName(rhs, @selector(cyname)));
2024 CFStringRef lhn(lhi), rhn(rhi);
2027 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2028 else if (rhn == NULL)
2029 return NSOrderedDescending;
2031 _profile(PackageNameCompare$NumbersLast)
2032 if (!lhi.empty() && !rhi.empty()) {
2033 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2034 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2035 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2036 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2037 return lha ? NSOrderedAscending : NSOrderedDescending;
2041 CFIndex length = CFStringGetLength(lhn);
2043 _profile(PackageNameCompare$Compare)
2044 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2049 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2050 return PackageNameCompare(*lhs, *rhs, context);
2053 struct PackageNameOrdering :
2054 std::binary_function<Package *, Package *, bool>
2056 _finline bool operator ()(Package *lhs, Package *rhs) const {
2057 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2061 @implementation Package
2063 - (NSString *) description {
2064 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2068 if (parsed_ != NULL)
2073 + (NSString *) webScriptNameForSelector:(SEL)selector {
2075 else if (selector == @selector(clear))
2077 else if (selector == @selector(getField:))
2079 else if (selector == @selector(hasTag:))
2081 else if (selector == @selector(install))
2083 else if (selector == @selector(remove))
2089 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2090 return [self webScriptNameForSelector:selector] == nil;
2093 + (NSArray *) _attributeKeys {
2094 return [NSArray arrayWithObjects:
2114 @"shortDescription",
2127 - (NSArray *) attributeKeys {
2128 return [[self class] _attributeKeys];
2131 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2132 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2135 - (NSArray *) relations {
2136 @synchronized (database_) {
2137 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2138 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2139 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2143 - (NSString *) architecture {
2145 @synchronized (database_) {
2146 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2149 - (NSString *) getField:(NSString *)name {
2150 @synchronized (database_) {
2151 if ([database_ era] != era_ || file_.end())
2154 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2156 const char *start, *end;
2157 if (!parser.Find([name UTF8String], start, end))
2158 return (NSString *) [NSNull null];
2160 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2164 if (parsed_ != NULL)
2166 @synchronized (database_) {
2167 if ([database_ era] != era_ || file_.end())
2170 ParsedPackage *parsed(new ParsedPackage);
2173 _profile(Package$parse)
2174 pkgRecords::Parser *parser;
2176 _profile(Package$parse$Lookup)
2177 parser = &[database_ records]->Lookup(file_);
2182 _profile(Package$parse$Find)
2187 {"architecture", &parsed->architecture_},
2188 {"icon", &parsed->icon_},
2189 {"depiction", &parsed->depiction_},
2190 {"homepage", &parsed->homepage_},
2191 {"website", &website},
2192 {"bugs", &parsed->bugs_},
2193 {"support", &parsed->support_},
2194 {"sponsor", &parsed->sponsor_},
2195 {"author", &parsed->author_},
2198 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2199 const char *start, *end;
2201 if (parser->Find(names[i].name_, start, end)) {
2202 CYString &value(*names[i].value_);
2203 _profile(Package$parse$Value)
2204 value.set(pool_, start, end - start);
2210 _profile(Package$parse$Tagline)
2211 const char *start, *end;
2212 if (parser->ShortDesc(start, end)) {
2213 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2216 while (stop != start && stop[-1] == '\r')
2218 parsed->tagline_.set(pool_, start, stop - start);
2222 _profile(Package$parse$Retain)
2223 if (parsed->homepage_.empty())
2224 parsed->homepage_ = website;
2225 if (parsed->homepage_ == parsed->depiction_)
2226 parsed->homepage_.clear();
2231 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2232 if ((self = [super init]) != nil) {
2233 _profile(Package$initWithVersion)
2236 database_ = database;
2237 era_ = [database era];
2241 pkgCache::PkgIterator iterator(version.ParentPkg());
2242 iterator_ = iterator;
2244 _profile(Package$initWithVersion$Version)
2245 if (!version_.end())
2246 file_ = version_.FileList();
2248 pkgCache &cache([database_ cache]);
2249 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2253 _profile(Package$initWithVersion$Cache)
2254 name_.set(NULL, iterator.Display());
2256 latest_.set(NULL, StripVersion_(version_.VerStr()));
2258 pkgCache::VerIterator current(iterator.CurrentVer());
2260 installed_.set(NULL, StripVersion_(current.VerStr()));
2263 _profile(Package$initWithVersion$Tags)
2264 pkgCache::TagIterator tag(iterator.TagList());
2266 tags_ = [NSMutableArray arrayWithCapacity:8];
2268 const char *name(tag.Name());
2269 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2271 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2272 if (strcmp(name + 6, "enduser") == 0)
2274 else if (strcmp(name + 6, "hacker") == 0)
2276 else if (strcmp(name + 6, "developer") == 0)
2278 else if (strcmp(name + 6, "cydia") == 0)
2284 if (strncmp(name, "cydia::", 7) == 0) {
2285 if (strcmp(name + 7, "essential") == 0)
2287 else if (strcmp(name + 7, "obsolete") == 0)
2292 } while (!tag.end());
2296 _profile(Package$initWithVersion$Metadata)
2297 const char *mixed(iterator.Name());
2298 size_t size(strlen(mixed));
2299 char lower[size + 1];
2301 for (size_t i(0); i != size; ++i)
2302 lower[i] = mixed[i] | 0x20;
2305 PackageValue *metadata(PackageFind(lower, size));
2306 metadata_ = metadata;
2308 id_.set(NULL, metadata->name_, size);
2310 const char *latest(version_.VerStr());
2311 size_t length(strlen(latest));
2313 uint16_t vhash(hashlittle(latest, length));
2315 size_t capped(std::min<size_t>(8, length));
2316 latest = latest + length - capped;
2318 if (metadata->first_ == 0)
2319 metadata->first_ = now_;
2321 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2322 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2323 metadata->vhash_ = vhash;
2324 metadata->last_ = now_;
2325 } else if (metadata->last_ == 0)
2326 metadata->last_ = metadata->first_;
2329 _profile(Package$initWithVersion$Section)
2330 section_ = iterator.Section();
2333 _profile(Package$initWithVersion$Flags)
2334 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2335 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2340 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2341 pkgCache::VerIterator version;
2343 _profile(Package$packageWithIterator$GetCandidateVer)
2344 version = [database policy]->GetCandidateVer(iterator);
2352 _profile(Package$packageWithIterator$Allocate)
2353 package = [Package allocWithZone:zone];
2356 _profile(Package$packageWithIterator$Initialize)
2358 initWithVersion:version
2365 _profile(Package$packageWithIterator$Autorelease)
2366 package = [package autorelease];
2372 - (pkgCache::PkgIterator) iterator {
2376 - (NSString *) section {
2377 if (section$_ == nil) {
2378 if (section_ == NULL)
2381 _profile(Package$section$mappedSectionForPointer)
2382 section$_ = [database_ mappedSectionForPointer:section_];
2387 - (NSString *) simpleSection {
2388 if (NSString *section = [self section])
2389 return Simplify(section);
2394 - (NSString *) longSection {
2395 return LocalizeSection([self section]);
2398 - (NSString *) shortSection {
2399 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2402 - (NSString *) uri {
2405 pkgIndexFile *index;
2406 pkgCache::PkgFileIterator file(file_.File());
2407 if (![database_ list].FindIndex(file, index))
2409 return [NSString stringWithUTF8String:iterator_->Path];
2410 //return [NSString stringWithUTF8String:file.Site()];
2411 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2415 - (MIMEAddress *) maintainer {
2416 @synchronized (database_) {
2417 if ([database_ era] != era_ || file_.end())
2420 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2421 const std::string &maintainer(parser->Maintainer());
2422 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2426 @synchronized (database_) {
2427 if ([database_ era] != era_ || version_.end())
2430 return version_->InstalledSize;
2433 - (NSString *) longDescription {
2434 @synchronized (database_) {
2435 if ([database_ era] != era_ || file_.end())
2438 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2439 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2441 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2442 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2443 if ([lines count] < 2)
2446 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2447 for (size_t i(1), e([lines count]); i != e; ++i) {
2448 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2449 [trimmed addObject:trim];
2452 return [trimmed componentsJoinedByString:@"\n"];
2455 - (NSString *) shortDescription {
2456 if (parsed_ != NULL)
2457 return static_cast<NSString *>(parsed_->tagline_);
2459 @synchronized (database_) {
2460 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2462 const char *start, *end;
2463 if (!parser.ShortDesc(start, end))
2466 if (end - start > 200)
2470 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2473 while (end != start && end[-1] == '\r')
2477 return [(id) CYStringCreate(start, end - start) autorelease];
2481 _profile(Package$index)
2482 CFStringRef name((CFStringRef) [self name]);
2483 if (CFStringGetLength(name) == 0)
2485 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2486 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2488 return toupper(character);
2492 - (PackageValue *) metadata {
2497 PackageValue *metadata([self metadata]);
2498 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2501 - (bool) subscribed {
2502 return [self metadata]->subscribed_;
2505 - (bool) setSubscribed:(bool)subscribed {
2506 PackageValue *metadata([self metadata]);
2507 if (metadata->subscribed_ == subscribed)
2509 metadata->subscribed_ = subscribed;
2517 - (NSString *) latest {
2521 - (NSString *) installed {
2525 - (BOOL) uninstalled {
2526 return installed_.empty();
2530 return !version_.end();
2533 - (BOOL) upgradableAndEssential:(BOOL)essential {
2534 _profile(Package$upgradableAndEssential)
2535 pkgCache::VerIterator current(iterator_.CurrentVer());
2537 return essential && essential_;
2539 return !version_.end() && version_ != current;
2543 - (BOOL) essential {
2548 return [database_ cache][iterator_].InstBroken();
2551 - (BOOL) unfiltered {
2552 _profile(Package$unfiltered$obsolete)
2553 if (_unlikely(obsolete_))
2557 _profile(Package$unfiltered$hasSupportingRole)
2558 if (_unlikely(![self hasSupportingRole]))
2566 if (![self unfiltered])
2571 _profile(Package$visible$section)
2572 section = [self section];
2575 _profile(Package$visible$isSectionVisible)
2576 if (!isSectionVisible(section))
2584 unsigned char current(iterator_->CurrentState);
2585 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2588 - (BOOL) halfConfigured {
2589 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2592 - (BOOL) halfInstalled {
2593 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2597 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2598 return state.Mode != pkgDepCache::ModeKeep;
2601 - (NSString *) mode {
2602 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2604 switch (state.Mode) {
2605 case pkgDepCache::ModeDelete:
2606 if ((state.iFlags & pkgDepCache::Purge) != 0)
2610 case pkgDepCache::ModeKeep:
2611 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2612 return @"REINSTALL";
2613 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2617 case pkgDepCache::ModeInstall:
2618 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2619 return @"REINSTALL";
2620 else*/ switch (state.Status) {
2622 return @"DOWNGRADE";
2628 return @"NEW_INSTALL";
2639 - (NSString *) name {
2640 return name_.empty() ? id_ : name_;
2643 - (UIImage *) icon {
2644 NSString *section = [self simpleSection];
2647 if (parsed_ != NULL)
2648 if (NSString *href = parsed_->icon_)
2649 if ([href hasPrefix:@"file:///"])
2650 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2651 if (icon == nil) if (section != nil)
2652 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2653 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2654 if ([dicon hasPrefix:@"file:///"])
2655 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2657 icon = [UIImage applicationImageNamed:@"unknown.png"];
2661 - (NSString *) homepage {
2662 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2665 - (NSString *) depiction {
2666 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2669 - (MIMEAddress *) sponsor {
2670 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2673 - (MIMEAddress *) author {
2674 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2677 - (NSString *) support {
2678 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2681 - (NSArray *) files {
2682 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2683 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2686 fin.open([path UTF8String]);
2691 while (std::getline(fin, line))
2692 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2697 - (NSString *) state {
2698 @synchronized (database_) {
2699 if ([database_ era] != era_ || file_.end())
2702 switch (iterator_->CurrentState) {
2703 case pkgCache::State::NotInstalled:
2704 return @"NotInstalled";
2705 case pkgCache::State::UnPacked:
2707 case pkgCache::State::HalfConfigured:
2708 return @"HalfConfigured";
2709 case pkgCache::State::HalfInstalled:
2710 return @"HalfInstalled";
2711 case pkgCache::State::ConfigFiles:
2712 return @"ConfigFiles";
2713 case pkgCache::State::Installed:
2714 return @"Installed";
2715 case pkgCache::State::TriggersAwaited:
2716 return @"TriggersAwaited";
2717 case pkgCache::State::TriggersPending:
2718 return @"TriggersPending";
2721 return (NSString *) [NSNull null];
2724 - (NSString *) selection {
2725 @synchronized (database_) {
2726 if ([database_ era] != era_ || file_.end())
2729 switch (iterator_->SelectedState) {
2730 case pkgCache::State::Unknown:
2732 case pkgCache::State::Install:
2734 case pkgCache::State::Hold:
2736 case pkgCache::State::DeInstall:
2737 return @"DeInstall";
2738 case pkgCache::State::Purge:
2742 return (NSString *) [NSNull null];
2745 - (NSArray *) warnings {
2746 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2747 const char *name(iterator_.Name());
2749 size_t length(strlen(name));
2750 if (length < 2) invalid:
2751 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2752 else for (size_t i(0); i != length; ++i)
2754 /* XXX: technically this is not allowed */
2755 (name[i] < 'A' || name[i] > 'Z') &&
2756 (name[i] < 'a' || name[i] > 'z') &&
2757 (name[i] < '0' || name[i] > '9') &&
2758 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2761 if (strcmp(name, "cydia") != 0) {
2764 bool _private = false;
2767 bool repository = [[self section] isEqualToString:@"Repositories"];
2769 if (NSArray *files = [self files])
2770 for (NSString *file in files)
2771 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2773 else if (!user && [file isEqualToString:@"/User"])
2775 else if (!_private && [file isEqualToString:@"/private"])
2777 else if (!stash && [file isEqualToString:@"/var/stash"])
2780 /* XXX: this is not sensitive enough. only some folders are valid. */
2781 if (cydia && !repository)
2782 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2784 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2786 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2788 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2791 return [warnings count] == 0 ? nil : warnings;
2794 - (NSArray *) applications {
2795 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2797 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2799 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2800 if (NSArray *files = [self files])
2801 for (NSString *file in files)
2802 if (application_r(file)) {
2803 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2804 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2805 if ([id isEqualToString:me])
2808 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2810 display = application_r[1];
2812 NSString *bundle([file stringByDeletingLastPathComponent]);
2813 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2814 if (icon == nil || [icon length] == 0)
2816 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2818 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2819 [applications addObject:application];
2821 [application addObject:id];
2822 [application addObject:display];
2823 [application addObject:url];
2826 return [applications count] == 0 ? nil : applications;
2829 - (Source *) source {
2830 if (source_ == nil) {
2831 @synchronized (database_) {
2832 if ([database_ era] != era_ || file_.end())
2833 source_ = (Source *) [NSNull null];
2835 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2839 return source_ == (Source *) [NSNull null] ? nil : source_;
2846 - (BOOL) matches:(NSArray *)query {
2847 if (query == nil || [query count] == 0)
2856 string = [self name];
2857 length = [string length];
2859 for (NSString *term in query) {
2860 range = [string rangeOfString:term options:MatchCompareOptions_];
2861 if (range.location != NSNotFound)
2862 rank_ -= 6 * 1000000 / length;
2867 length = [string length];
2869 for (NSString *term in query) {
2870 range = [string rangeOfString:term options:MatchCompareOptions_];
2871 if (range.location != NSNotFound)
2872 rank_ -= 6 * 1000000 / length;
2876 string = [self shortDescription];
2877 length = [string length];
2878 NSUInteger stop(std::min<NSUInteger>(length, 200));
2880 for (NSString *term in query) {
2881 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2882 if (range.location != NSNotFound)
2883 rank_ -= 2 * 100000;
2889 - (bool) hasSupportingRole {
2894 if ([Role_ isEqualToString:@"User"])
2898 if ([Role_ isEqualToString:@"Hacker"])
2902 if ([Role_ isEqualToString:@"Developer"])
2907 - (NSArray *) tags {
2911 - (BOOL) hasTag:(NSString *)tag {
2912 return tags_ == nil ? NO : [tags_ containsObject:tag];
2915 - (NSString *) primaryPurpose {
2916 for (NSString *tag in (NSArray *) tags_)
2917 if ([tag hasPrefix:@"purpose::"])
2918 return [tag substringFromIndex:9];
2922 - (NSArray *) purposes {
2923 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2924 for (NSString *tag in (NSArray *) tags_)
2925 if ([tag hasPrefix:@"purpose::"])
2926 [purposes addObject:[tag substringFromIndex:9]];
2927 return [purposes count] == 0 ? nil : purposes;
2930 - (bool) isCommercial {
2931 return [self hasTag:@"cydia::commercial"];
2934 - (void) setIndex:(size_t)index {
2935 if (metadata_->index_ != index)
2936 metadata_->index_ = index;
2939 - (CYString &) cyname {
2940 return name_.empty() ? id_ : name_;
2943 - (uint32_t) compareBySection:(NSArray *)sections {
2944 NSString *section([self section]);
2945 for (size_t i(0), e([sections count]); i != e; ++i) {
2946 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2950 return _not(uint32_t);
2954 @synchronized (database_) {
2955 pkgProblemResolver *resolver = [database_ resolver];
2956 resolver->Clear(iterator_);
2958 pkgCacheFile &cache([database_ cache]);
2959 cache->SetReInstall(iterator_, false);
2960 cache->MarkKeep(iterator_, false);
2964 @synchronized (database_) {
2965 pkgProblemResolver *resolver = [database_ resolver];
2966 resolver->Clear(iterator_);
2967 resolver->Protect(iterator_);
2969 pkgCacheFile &cache([database_ cache]);
2970 cache->SetReInstall(iterator_, false);
2971 cache->MarkInstall(iterator_, false);
2973 pkgDepCache::StateCache &state((*cache)[iterator_]);
2974 if (!state.Install())
2975 cache->SetReInstall(iterator_, true);
2979 @synchronized (database_) {
2980 pkgProblemResolver *resolver = [database_ resolver];
2981 resolver->Clear(iterator_);
2982 resolver->Remove(iterator_);
2983 resolver->Protect(iterator_);
2985 pkgCacheFile &cache([database_ cache]);
2986 cache->SetReInstall(iterator_, false);
2987 cache->MarkDelete(iterator_, true);
2990 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
2991 _profile(Package$isUnfilteredAndSearchedForBy)
2994 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2995 value &= [self unfiltered];
2998 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2999 value &= [self matches:query];
3006 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3007 if ([search length] == 0)
3010 _profile(Package$isUnfilteredAndSelectedForBy)
3013 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3014 value &= [self unfiltered];
3017 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3018 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3025 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3026 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3029 - (bool) isVisibleInSection:(NSString *)name {
3030 NSString *section([self section]);
3034 section == nil && [name length] == 0 ||
3035 [name isEqualToString:section]
3036 ) && [self visible];
3039 - (bool) isVisibleInSource:(Source *)source {
3040 return [self source] == source && [self visible];
3045 /* Section Class {{{ */
3046 @interface Section : NSObject {
3051 _H<NSString> localized_;
3054 - (NSComparisonResult) compareByLocalized:(Section *)section;
3055 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3056 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3057 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3058 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3059 - (NSString *) name;
3066 - (void) addToCount;
3068 - (void) setCount:(size_t)count;
3069 - (NSString *) localized;
3073 @implementation Section
3075 - (NSComparisonResult) compareByLocalized:(Section *)section {
3076 NSString *lhs(localized_);
3077 NSString *rhs([section localized]);
3079 /*if ([lhs length] != 0 && [rhs length] != 0) {
3080 unichar lhc = [lhs characterAtIndex:0];
3081 unichar rhc = [rhs characterAtIndex:0];
3083 if (isalpha(lhc) && !isalpha(rhc))
3084 return NSOrderedAscending;
3085 else if (!isalpha(lhc) && isalpha(rhc))
3086 return NSOrderedDescending;
3089 return [lhs compare:rhs options:LaxCompareOptions_];
3092 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3093 if ((self = [self initWithName:name localize:NO]) != nil) {
3094 if (localized != nil)
3095 localized_ = localized;
3099 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3100 return [self initWithName:name row:0 localize:localize];
3103 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3104 if ((self = [super init]) != nil) {
3109 localized_ = LocalizeSection(name_);
3113 /* XXX: localize the index thingees */
3114 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3115 if ((self = [super init]) != nil) {
3116 name_ = [NSString stringWithCharacters:&index length:1];
3122 - (NSString *) name {
3142 - (void) addToCount {
3146 - (void) setCount:(size_t)count {
3150 - (NSString *) localized {
3157 class CydiaLogCleaner :
3158 public pkgArchiveCleaner
3161 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3166 /* Database Implementation {{{ */
3167 @implementation Database
3169 + (Database *) sharedInstance {
3170 static _H<Database> instance;
3171 if (instance == nil)
3172 instance = [[[Database alloc] init] autorelease];
3180 - (void) releasePackages {
3181 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3182 CFArrayRemoveAllValues(packages_);
3186 // XXX: actually implement this thing
3188 [self releasePackages];
3189 apr_pool_destroy(pool_);
3190 NSRecycleZone(zone_);
3194 - (void) _readCydia:(NSNumber *)fd {
3195 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3196 std::istream is(&ib);
3199 static Pcre finish_r("^finish:([^:]*)$");
3201 while (std::getline(is, line)) {
3202 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3204 const char *data(line.c_str());
3205 size_t size = line.size();
3206 lprintf("C:%s\n", data);
3208 if (finish_r(data, size)) {
3209 NSString *finish = finish_r[1];
3210 int index = [Finishes_ indexOfObject:finish];
3211 if (index != INT_MAX && index > Finish_)
3221 - (void) _readStatus:(NSNumber *)fd {
3222 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3223 std::istream is(&ib);
3226 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3227 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3229 while (std::getline(is, line)) {
3230 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3232 const char *data(line.c_str());
3233 size_t size(line.size());
3234 lprintf("S:%s\n", data);
3236 if (conffile_r(data, size)) {
3237 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3238 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3239 } else if (strncmp(data, "status: ", 8) == 0) {
3240 // status: <package>: {unpacked,half-configured,installed}
3241 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3242 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3243 } else if (strncmp(data, "processing: ", 12) == 0) {
3244 // processing: configure: config-test
3245 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3246 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3247 } else if (pmstatus_r(data, size)) {
3248 std::string type([pmstatus_r[1] UTF8String]);
3250 NSString *package = pmstatus_r[2];
3251 if ([package isEqualToString:@"dpkg-exec"])
3254 float percent([pmstatus_r[3] floatValue]);
3255 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3257 NSString *string = pmstatus_r[4];
3259 if (type == "pmerror") {
3260 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3261 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3262 } else if (type == "pmstatus") {
3263 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3264 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3265 } else if (type == "pmconffile")
3266 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3268 lprintf("E:unknown pmstatus\n");
3270 lprintf("E:unknown status\n");
3278 - (void) _readOutput:(NSNumber *)fd {
3279 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3280 std::istream is(&ib);
3283 while (std::getline(is, line)) {
3284 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3286 lprintf("O:%s\n", line.c_str());
3288 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3289 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3301 - (Package *) packageWithName:(NSString *)name {
3304 @synchronized (self) {
3305 if (static_cast<pkgDepCache *>(cache_) == NULL)
3307 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3308 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3312 if ((self = [super init]) != nil) {
3319 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3320 apr_pool_create(&pool_, NULL);
3322 size_t capacity(MetaFile_->active_);
3328 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3329 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3333 _assert(pipe(fds) != -1);
3336 _config->Set("APT::Keep-Fds::", cydiafd_);
3337 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3340 detachNewThreadSelector:@selector(_readCydia:)
3342 withObject:[NSNumber numberWithInt:fds[0]]
3345 _assert(pipe(fds) != -1);
3349 detachNewThreadSelector:@selector(_readStatus:)
3351 withObject:[NSNumber numberWithInt:fds[0]]
3354 _assert(pipe(fds) != -1);
3355 _assert(dup2(fds[0], 0) != -1);
3356 _assert(close(fds[0]) != -1);
3358 input_ = fdopen(fds[1], "a");
3360 _assert(pipe(fds) != -1);
3361 _assert(dup2(fds[1], 1) != -1);
3362 _assert(close(fds[1]) != -1);
3365 detachNewThreadSelector:@selector(_readOutput:)
3367 withObject:[NSNumber numberWithInt:fds[0]]
3372 - (pkgCacheFile &) cache {
3376 - (pkgDepCache::Policy *) policy {
3380 - (pkgRecords *) records {
3384 - (pkgProblemResolver *) resolver {
3388 - (pkgAcquire &) fetcher {
3392 - (pkgSourceList &) list {
3396 - (NSArray *) packages {
3397 return (NSArray *) packages_;
3400 - (NSArray *) sources {
3404 - (Source *) sourceWithKey:(NSString *)key {
3405 for (Source *source in [self sources]) {
3406 if ([[source key] isEqualToString:key])
3411 - (bool) popErrorWithTitle:(NSString *)title {
3414 while (!_error->empty()) {
3416 bool warning(!_error->PopMessage(error));
3421 size_t size(error.size());
3422 if (size == 0 || error[size - 1] != '\n')
3424 error.resize(size - 1);
3427 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3429 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3435 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3436 return [self popErrorWithTitle:title] || !success;
3439 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3440 @synchronized (self) {
3443 [self releasePackages];
3446 [sourceList_ removeAllObjects];
3466 apr_pool_clear(pool_);
3468 NSRecycleZone(zone_);
3469 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3471 int chk(creat("/tmp/cydia.chk", 0644));
3475 if (invocation != nil)
3476 [invocation invoke];
3478 NSString *title(UCLocalize("DATABASE"));
3481 OpProgress progress;
3482 while (!cache_.Open(progress, true)) { pop:
3484 bool warning(!_error->PopMessage(error));
3485 lprintf("cache_.Open():[%s]\n", error.c_str());
3487 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3488 [delegate_ repairWithSelector:@selector(configure)];
3489 else if (error == "The package lists or status file could not be parsed or opened.")
3490 [delegate_ repairWithSelector:@selector(update)];
3491 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3492 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3493 // else if (error == "Malformed Status line")
3494 // else if (error == "The list of sources could not be read.")
3496 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3506 unlink("/tmp/cydia.chk");
3508 now_ = [[NSDate date] timeIntervalSince1970];
3510 policy_ = new pkgDepCache::Policy();
3511 records_ = new pkgRecords(cache_);
3512 resolver_ = new pkgProblemResolver(cache_);
3513 fetcher_ = new pkgAcquire(&status_);
3516 list_ = new pkgSourceList();
3517 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3520 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3521 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3525 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3528 if (cache_->BrokenCount() != 0) {
3529 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3532 if (cache_->BrokenCount() != 0) {
3533 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3537 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3541 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3542 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3543 [sourceList_ addObject:object];
3545 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3546 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3547 // XXX: this could be more intelligent
3548 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3549 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3551 sourceMap_[cached->ID] = object;
3556 /*std::vector<Package *> packages;
3557 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3562 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3563 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3564 //packages.push_back(package);
3565 CFArrayAppendValue(packages_, CFRetain(package));
3569 /*if (packages.empty())
3570 packages_ = [[NSArray alloc] init];
3572 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3575 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3576 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3577 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3585 /*if (!packages.empty())
3586 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3587 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3589 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3591 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3593 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3597 size_t count(CFArrayGetCount(packages_));
3598 MetaFile_->active_ = count;
3600 for (size_t index(0); index != count; ++index)
3601 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3608 @synchronized (self) {
3610 resolver_ = new pkgProblemResolver(cache_);
3612 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3613 if (!cache_[iterator].Keep())
3614 cache_->MarkKeep(iterator, false);
3615 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3616 cache_->SetReInstall(iterator, false);
3619 - (void) configure {
3620 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3622 system([dpkg UTF8String]);
3627 // XXX: I don't remember this condition
3632 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3634 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3636 if ([self popErrorWithTitle:title])
3640 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3642 CydiaLogCleaner cleaner;
3643 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3650 fetcher_->Shutdown();
3652 pkgRecords records(cache_);
3654 lock_ = new FileFd();
3655 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3657 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3659 if ([self popErrorWithTitle:title])
3663 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3666 manager_ = (_system->CreatePM(cache_));
3667 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3674 bool substrate(RestartSubstrate_);
3675 RestartSubstrate_ = false;
3677 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3679 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3681 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3683 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3684 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3687 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3689 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3691 [self popErrorWithTitle:title];
3695 bool failed = false;
3696 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3697 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3699 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3705 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3713 RestartSubstrate_ = true;
3716 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3718 if (_error->PendingError()) {
3723 if (result == pkgPackageManager::Failed) {
3728 if (result != pkgPackageManager::Completed) {
3733 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3735 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3737 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3738 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3741 if (![before isEqualToArray:after])
3746 NSString *title(UCLocalize("UPGRADE"));
3747 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3753 [self updateWithStatus:status_];
3756 - (void) updateWithStatus:(Status &)status {
3757 NSString *title(UCLocalize("REFRESHING_DATA"));
3760 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3764 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3765 if ([self popErrorWithTitle:title])
3768 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3770 bool success(ListUpdate(status, list, PulseInterval_));
3771 if (status.WasCancelled())
3774 [self popErrorWithTitle:title forOperation:success];
3775 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3779 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3782 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3783 delegate_ = delegate;
3786 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3787 progress_ = delegate;
3788 status_.setDelegate(delegate);
3791 - (NSObject<ProgressDelegate> *) progressDelegate {
3795 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3796 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3797 return i == sourceMap_.end() ? nil : i->second;
3800 - (NSString *) mappedSectionForPointer:(const char *)section {
3801 _H<NSString> *mapped;
3803 _profile(Database$mappedSectionForPointer$Cache)
3804 mapped = §ions_[section];
3807 if (*mapped == NULL) {
3808 size_t length(strlen(section));
3809 char spaced[length + 1];
3811 _profile(Database$mappedSectionForPointer$Replace)
3812 for (size_t index(0); index != length; ++index)
3813 spaced[index] = section[index] == '_' ? ' ' : section[index];
3814 spaced[length] = '\0';
3819 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3820 string = [NSString stringWithUTF8String:spaced];
3823 _profile(Database$mappedSectionForPointer$Map)
3824 string = [SectionMap_ objectForKey:string] ?: string;
3834 static _H<NSMutableSet> Diversions_;
3836 @interface Diversion : NSObject {
3839 _H<NSString> format_;
3844 @implementation Diversion
3846 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3847 if ((self = [super init]) != nil) {
3848 pattern_ = [from UTF8String];
3854 - (NSString *) divert:(NSString *)url {
3855 return !pattern_(url) ? nil : pattern_->*format_;
3858 + (NSURL *) divertURL:(NSURL *)url {
3860 NSString *href([url absoluteString]);
3862 for (Diversion *diversion in (id) Diversions_)
3863 if (NSString *diverted = [diversion divert:href]) {
3865 NSLog(@"div: %@", diverted);
3867 url = [NSURL URLWithString:diverted];
3874 - (NSString *) key {
3878 - (NSUInteger) hash {
3882 - (BOOL) isEqual:(Diversion *)object {
3883 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3888 @interface CydiaObject : NSObject {
3889 _H<IndirectDelegate> indirect_;
3890 _transient id delegate_;
3893 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3897 @interface CydiaWebViewController : CyteWebViewController {
3898 _H<CydiaObject> cydia_;
3901 + (void) addDiversion:(Diversion *)diversion;
3905 /* Web Scripting {{{ */
3906 @implementation CydiaObject
3908 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3909 if ((self = [super init]) != nil) {
3910 indirect_ = indirect;
3914 - (void) setDelegate:(id)delegate {
3915 delegate_ = delegate;
3918 + (NSArray *) _attributeKeys {
3919 return [NSArray arrayWithObjects:
3936 - (NSArray *) attributeKeys {
3937 return [[self class] _attributeKeys];
3940 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3941 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3944 - (NSString *) version {
3948 - (NSString *) device {
3949 return [[UIDevice currentDevice] uniqueIdentifier];
3952 - (NSString *) firmware {
3953 return [[UIDevice currentDevice] systemVersion];
3956 - (NSString *) hostname {
3957 return [[UIDevice currentDevice] name];
3960 - (NSString *) idiom {
3961 return (id) Idiom_ ?: [NSNull null];
3964 - (NSString *) plmn {
3965 return (id) PLMN_ ?: [NSNull null];
3968 - (NSString *) bbsnum {
3969 return (id) BBSNum_ ?: [NSNull null];
3972 - (NSString *) ecid {
3973 return (id) ChipID_ ?: [NSNull null];
3976 - (NSString *) serial {
3977 return SerialNumber_;
3980 - (NSString *) role {
3981 return (id) Role_ ?: [NSNull null];
3984 - (NSString *) model {
3985 return [NSString stringWithUTF8String:Machine_];
3988 - (NSString *) token {
3989 return (id) Token_ ?: [NSNull null];
3992 + (NSString *) webScriptNameForSelector:(SEL)selector {
3994 else if (selector == @selector(addBridgedHost:))
3995 return @"addBridgedHost";
3996 else if (selector == @selector(addInsecureHost:))
3997 return @"addInsecureHost";
3998 else if (selector == @selector(addInternalRedirect::))
3999 return @"addInternalRedirect";
4000 else if (selector == @selector(addPipelinedHost:scheme:))
4001 return @"addPipelinedHost";
4002 else if (selector == @selector(addSource:::))
4003 return @"addSource";
4004 else if (selector == @selector(addTokenHost:))
4005 return @"addTokenHost";
4006 else if (selector == @selector(addTrivialSource:))
4007 return @"addTrivialSource";
4008 else if (selector == @selector(close))
4010 else if (selector == @selector(du:))
4012 else if (selector == @selector(stringWithFormat:arguments:))
4014 else if (selector == @selector(getAllSources))
4015 return @"getAllSourcs";
4016 else if (selector == @selector(getKernelNumber:))
4017 return @"getKernelNumber";
4018 else if (selector == @selector(getKernelString:))
4019 return @"getKernelString";
4020 else if (selector == @selector(getInstalledPackages))
4021 return @"getInstalledPackages";
4022 else if (selector == @selector(getIORegistryEntry::))
4023 return @"getIORegistryEntry";
4024 else if (selector == @selector(getLocaleIdentifier))
4025 return @"getLocaleIdentifier";
4026 else if (selector == @selector(getPreferredLanguages))
4027 return @"getPreferredLanguages";
4028 else if (selector == @selector(getPackageById:))
4029 return @"getPackageById";
4030 else if (selector == @selector(getMetadataKeys))
4031 return @"getMetadataKeys";
4032 else if (selector == @selector(getMetadataValue:))
4033 return @"getMetadataValue";
4034 else if (selector == @selector(getSessionValue:))
4035 return @"getSessionValue";
4036 else if (selector == @selector(installPackages:))
4037 return @"installPackages";
4038 else if (selector == @selector(localizedStringForKey:value:table:))
4040 else if (selector == @selector(popViewController:))
4041 return @"popViewController";
4042 else if (selector == @selector(refreshSources))
4043 return @"refreshSources";
4044 else if (selector == @selector(removeButton))
4045 return @"removeButton";
4046 else if (selector == @selector(saveConfig))
4047 return @"saveConfig";
4048 else if (selector == @selector(setCydiaSource:))
4049 return @"setCydiaSource";
4050 else if (selector == @selector(setMetadataValue::))
4051 return @"setMetadataValue";
4052 else if (selector == @selector(setSessionValue::))
4053 return @"setSessionValue";
4054 else if (selector == @selector(substitutePackageNames:))
4055 return @"substitutePackageNames";
4056 else if (selector == @selector(scrollToBottom:))
4057 return @"scrollToBottom";
4058 else if (selector == @selector(setAllowsNavigationAction:))
4059 return @"setAllowsNavigationAction";
4060 else if (selector == @selector(setBadgeValue:))
4061 return @"setBadgeValue";
4062 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4063 return @"setButtonImage";
4064 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4065 return @"setButtonTitle";
4066 else if (selector == @selector(setHidesBackButton:))
4067 return @"setHidesBackButton";
4068 else if (selector == @selector(setHidesNavigationBar:))
4069 return @"setHidesNavigationBar";
4070 else if (selector == @selector(setNavigationBarStyle:))
4071 return @"setNavigationBarStyle";
4072 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4073 return @"setNavigationBarTintColor";
4074 else if (selector == @selector(setPasteboardString:))
4075 return @"setPasteboardString";
4076 else if (selector == @selector(setPasteboardURL:))
4077 return @"setPasteboardURL";
4078 else if (selector == @selector(setToken:))
4080 else if (selector == @selector(setViewportWidth:))
4081 return @"setViewportWidth";
4082 else if (selector == @selector(statfs:))
4084 else if (selector == @selector(supports:))
4086 else if (selector == @selector(unload))
4092 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4093 return [self webScriptNameForSelector:selector] == nil;
4096 - (BOOL) supports:(NSString *)feature {
4097 return [feature isEqualToString:@"window.open"];
4101 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4104 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4105 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4108 - (NSNumber *) getKernelNumber:(NSString *)name {
4109 const char *string([name UTF8String]);
4112 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4113 return (id) [NSNull null];
4115 if (size != sizeof(int))
4116 return (id) [NSNull null];
4119 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4120 return (id) [NSNull null];
4122 return [NSNumber numberWithInt:value];
4125 - (NSString *) getKernelString:(NSString *)name {
4126 const char *string([name UTF8String]);
4129 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4130 return (id) [NSNull null];
4132 char value[size + 1];
4133 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4134 return (id) [NSNull null];
4136 // XXX: just in case you request something ludicrous
4139 return [NSString stringWithCString:value];
4142 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4143 NSObject *value(CYIOGetValue([path UTF8String], entry));
4146 if ([value isKindOfClass:[NSData class]])
4147 value = CYHex((NSData *) value);
4152 - (void) _setCydiaSource:(NSString *)source {
4153 @synchronized (HostConfig_) {
4154 CydiaSource_ = source;
4155 [Metadata_ setObject:source forKey:@"CydiaSource"];
4161 - (void) setCydiaSource:(NSString *)source {
4162 [self performSelectorOnMainThread:@selector(_setCydiaSource:) withObject:source waitUntilDone:NO];
4165 - (NSString *) cydiaSource {
4166 @synchronized (HostConfig_) {
4167 return (id) CydiaSource_ ?: [NSNull null];
4171 - (NSArray *) getMetadataKeys {
4172 @synchronized (Values_) {
4173 return [Values_ allKeys];
4176 - (id) getMetadataValue:(NSString *)key {
4177 @synchronized (Values_) {
4178 return [Values_ objectForKey:key];
4181 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4182 @synchronized (Values_) {
4183 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4184 [Values_ removeObjectForKey:key];
4186 [Values_ setObject:value forKey:key];
4188 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4191 - (id) getSessionValue:(NSString *)key {
4192 @synchronized (SessionData_) {
4193 return [SessionData_ objectForKey:key];
4196 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4197 @synchronized (SessionData_) {
4198 if (value == (id) [WebUndefined undefined])
4199 [SessionData_ removeObjectForKey:key];
4201 [SessionData_ setObject:value forKey:key];
4204 - (void) addBridgedHost:(NSString *)host {
4205 @synchronized (HostConfig_) {
4206 [BridgedHosts_ addObject:host];
4209 - (void) addInsecureHost:(NSString *)host {
4210 @synchronized (HostConfig_) {
4211 [InsecureHosts_ addObject:host];
4214 - (void) addTokenHost:(NSString *)host {
4215 @synchronized (HostConfig_) {
4216 [TokenHosts_ addObject:host];
4219 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4220 @synchronized (HostConfig_) {
4221 if (scheme != (id) [WebUndefined undefined])
4222 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4224 [PipelinedHosts_ addObject:host];
4227 - (void) popViewController:(NSNumber *)value {
4228 if (value == (id) [WebUndefined undefined])
4229 value = [NSNumber numberWithBool:YES];
4230 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4233 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4234 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4236 for (NSString *section in sections)
4237 [array addObject:section];
4239 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4242 distribution, @"Distribution",
4244 nil] waitUntilDone:NO];
4247 - (void) addTrivialSource:(NSString *)href {
4248 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4251 - (void) refreshSources {
4252 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4255 - (void) saveConfig {
4256 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4259 - (NSArray *) getAllSources {
4260 return [[Database sharedInstance] sources];
4263 - (NSArray *) getInstalledPackages {
4264 Database *database([Database sharedInstance]);
4265 @synchronized (database) {
4266 NSArray *packages([database packages]);
4267 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4268 for (Package *package in packages)
4269 if (![package uninstalled])
4270 [installed addObject:package];
4274 - (Package *) getPackageById:(NSString *)id {
4275 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4279 return (Package *) [NSNull null];
4282 - (NSString *) getLocaleIdentifier {
4283 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4286 - (NSArray *) getPreferredLanguages {
4290 - (NSArray *) statfs:(NSString *)path {
4293 if (path == nil || statfs([path UTF8String], &stat) == -1)
4296 return [NSArray arrayWithObjects:
4297 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4298 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4299 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4303 - (NSNumber *) du:(NSString *)path {
4304 NSNumber *value(nil);
4307 _assert(pipe(fds) != -1);
4309 pid_t pid(ExecFork());
4311 _assert(dup2(fds[1], 1) != -1);
4312 _assert(close(fds[0]) != -1);
4313 _assert(close(fds[1]) != -1);
4314 /* XXX: this should probably not use du */
4315 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4320 _assert(close(fds[1]) != -1);
4322 if (FILE *du = fdopen(fds[0], "r")) {
4324 while (fgets(line, sizeof(line), du) != NULL) {
4325 size_t length(strlen(line));
4326 while (length != 0 && line[length - 1] == '\n')
4327 line[--length] = '\0';
4328 if (char *tab = strchr(line, '\t')) {
4330 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4335 } else _assert(close(fds[0]));
4339 if (waitpid(pid, &status, 0) == -1)
4342 else _assert(false);
4348 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4351 - (void) installPackages:(NSArray *)packages {
4352 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4355 - (NSString *) substitutePackageNames:(NSString *)message {
4356 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4357 for (size_t i(0), e([words count]); i != e; ++i) {
4358 NSString *word([words objectAtIndex:i]);
4359 if (Package *package = [[Database sharedInstance] packageWithName:word])
4360 [words replaceObjectAtIndex:i withObject:[package name]];
4363 return [words componentsJoinedByString:@" "];
4366 - (void) removeButton {
4367 [indirect_ removeButton];
4370 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4371 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4374 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4375 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4378 - (void) setBadgeValue:(id)value {
4379 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4382 - (void) setAllowsNavigationAction:(NSString *)value {
4383 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4386 - (void) setHidesBackButton:(NSString *)value {
4387 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4390 - (void) setHidesNavigationBar:(NSString *)value {
4391 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4394 - (void) setNavigationBarStyle:(NSString *)value {
4395 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4398 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4399 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4400 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4401 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4404 - (void) setPasteboardString:(NSString *)value {
4405 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4408 - (void) setPasteboardURL:(NSString *)value {
4409 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4412 - (void) _setToken:(NSString *)token {
4416 [Metadata_ removeObjectForKey:@"Token"];
4418 [Metadata_ setObject:Token_ forKey:@"Token"];
4423 - (void) setToken:(NSString *)token {
4424 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4427 - (void) scrollToBottom:(NSNumber *)animated {
4428 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4431 - (void) setViewportWidth:(float)width {
4432 [indirect_ setViewportWidthOnMainThread:width];
4435 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4436 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4437 unsigned count([arguments count]);
4439 for (unsigned i(0); i != count; ++i)
4440 values[i] = [arguments objectAtIndex:i];
4441 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4444 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4445 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4447 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4449 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4455 @interface NSURL (CydiaSecure)
4458 @implementation NSURL (CydiaSecure)
4460 - (bool) isCydiaSecure {
4461 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4464 @synchronized (HostConfig_) {
4465 if ([InsecureHosts_ containsObject:[self host]])
4474 /* Cydia Browser Controller {{{ */
4475 @implementation CydiaWebViewController
4477 - (NSURL *) navigationURL {
4478 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4481 + (void) initialize {
4482 Diversions_ = [NSMutableSet setWithCapacity:0];
4485 + (void) addDiversion:(Diversion *)diversion {
4486 [Diversions_ addObject:diversion];
4489 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4490 [super webView:view didClearWindowObject:window forFrame:frame];
4492 WebDataSource *source([frame dataSource]);
4493 NSURLResponse *response([source response]);
4494 NSURL *url([response URL]);
4495 NSString *scheme([[url scheme] lowercaseString]);
4497 bool bridged(false);
4499 @synchronized (HostConfig_) {
4500 if ([scheme isEqualToString:@"file"])
4502 else if ([scheme isEqualToString:@"https"])
4503 if ([BridgedHosts_ containsObject:[url host]])
4508 [window setValue:cydia_ forKey:@"cydia"];
4511 - (void) _setupMail:(MFMailComposeViewController *)controller {
4512 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4514 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4515 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4518 - (NSURL *) URLWithURL:(NSURL *)url {
4519 return [Diversion divertURL:url];
4522 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4523 NSURL *url([request URL]);
4524 NSString *host([url host]);
4526 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4528 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4529 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4530 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4531 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4534 @synchronized (HostConfig_) {
4535 token = [TokenHosts_ containsObject:host] || [BridgedHosts_ containsObject:host];
4538 if ([url isCydiaSecure] && token) {
4539 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4540 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4546 - (void) setDelegate:(id)delegate {
4547 [super setDelegate:delegate];
4548 [cydia_ setDelegate:delegate];
4551 - (NSString *) applicationNameForUserAgent {
4552 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4555 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4557 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4558 if (Product_ != nil)
4559 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4565 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4566 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4572 @interface AppCacheController : CydiaWebViewController {
4577 @implementation AppCacheController
4579 - (void) didReceiveMemoryWarning {
4586 @interface NSObject (CydiaScript)
4587 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4590 @implementation NSObject (CydiaScript)
4592 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4598 @implementation NSArray (CydiaScript)
4600 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4601 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4602 for (size_t i(0), e([self count]); i != e; ++i)
4603 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4609 @implementation NSDictionary (CydiaScript)
4611 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4612 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4614 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4621 /* Confirmation Controller {{{ */
4622 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4623 if (!iterator.end())
4624 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4625 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4627 pkgCache::PkgIterator package(dep.TargetPkg());
4630 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4637 @protocol ConfirmationControllerDelegate
4638 - (void) cancelAndClear:(bool)clear;
4639 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4643 @interface ConfirmationController : CydiaWebViewController {
4644 _transient Database *database_;
4646 _H<UIAlertView> essential_;
4648 _H<NSDictionary> changes_;
4649 _H<NSMutableArray> issues_;
4650 _H<NSDictionary> sizes_;
4655 - (id) initWithDatabase:(Database *)database;
4659 @implementation ConfirmationController
4663 RestartSubstrate_ = true;
4664 [delegate_ confirmWithNavigationController:[self navigationController]];
4667 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4668 NSString *context([alert context]);
4670 if ([context isEqualToString:@"remove"]) {
4671 if (button == [alert cancelButtonIndex])
4672 [self dismissModalViewControllerAnimated:YES];
4673 else if (button == [alert firstOtherButtonIndex]) {
4677 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4678 } else if ([context isEqualToString:@"unable"]) {
4679 [self dismissModalViewControllerAnimated:YES];
4680 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4682 [super alertView:alert clickedButtonAtIndex:button];
4686 - (void) _doContinue {
4687 [delegate_ cancelAndClear:NO];
4688 [self dismissModalViewControllerAnimated:YES];
4691 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4692 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4696 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4697 [super webView:view didClearWindowObject:window forFrame:frame];
4699 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4700 (id) changes_, @"changes",
4701 (id) issues_, @"issues",
4702 (id) sizes_, @"sizes",
4704 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4707 - (id) initWithDatabase:(Database *)database {
4708 if ((self = [super init]) != nil) {
4709 database_ = database;
4711 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4712 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4713 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4714 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4715 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4719 pkgCacheFile &cache([database_ cache]);
4720 NSArray *packages([database_ packages]);
4721 pkgDepCache::Policy *policy([database_ policy]);
4723 issues_ = [NSMutableArray arrayWithCapacity:4];
4725 for (Package *package in packages) {
4726 pkgCache::PkgIterator iterator([package iterator]);
4727 NSString *name([package id]);
4729 if ([package broken]) {
4730 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4732 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4734 reasons, @"reasons",
4737 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4741 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4742 pkgCache::DepIterator start;
4743 pkgCache::DepIterator end;
4744 dep.GlobOr(start, end); // ++dep
4746 if (!cache->IsImportantDep(end))
4748 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4751 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4753 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4754 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4755 clauses, @"clauses",
4759 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4761 pkgCache::PkgIterator target(start.TargetPkg());
4762 if (target->ProvidesList != 0)
4763 reason = @"missing";
4765 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4767 reason = @"installed";
4768 installed = [NSString stringWithUTF8String:ver.VerStr()];
4769 } else if (!cache[target].CandidateVerIter(cache).end())
4770 reason = @"uninstalled";
4771 else if (target->ProvidesList == 0)
4772 reason = @"uninstallable";
4774 reason = @"virtual";
4777 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4778 [NSString stringWithUTF8String:start.CompType()], @"operator",
4779 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4782 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4783 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4784 version, @"version",
4786 installed, @"installed",
4789 // yes, seriously. (wtf?)
4797 pkgDepCache::StateCache &state(cache[iterator]);
4799 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4801 if (state.NewInstall())
4802 [installs addObject:name];
4803 // XXX: else if (state.Install())
4804 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4805 [reinstalls addObject:name];
4806 // XXX: move before previous if
4807 else if (state.Upgrade())
4808 [upgrades addObject:name];
4809 else if (state.Downgrade())
4810 [downgrades addObject:name];
4811 else if (!state.Delete())
4812 // XXX: _assert(state.Keep());
4814 else if (special_r(name))
4815 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4816 [NSNull null], @"package",
4817 [NSArray arrayWithObjects:
4818 [NSDictionary dictionaryWithObjectsAndKeys:
4819 @"Conflicts", @"relationship",
4820 [NSArray arrayWithObjects:
4821 [NSDictionary dictionaryWithObjectsAndKeys:
4823 [NSNull null], @"version",
4824 @"installed", @"reason",
4831 if ([package essential])
4833 [removes addObject:name];
4836 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4837 substrate_ |= DepSubstrate(iterator.CurrentVer());
4842 else if (Advanced_) {
4843 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4845 essential_ = [[[UIAlertView alloc]
4846 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4847 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4849 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4851 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4855 [essential_ setContext:@"remove"];
4857 essential_ = [[[UIAlertView alloc]
4858 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4859 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4861 cancelButtonTitle:UCLocalize("OKAY")
4862 otherButtonTitles:nil
4865 [essential_ setContext:@"unable"];
4868 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4869 installs, @"installs",
4870 reinstalls, @"reinstalls",
4871 upgrades, @"upgrades",
4872 downgrades, @"downgrades",
4873 removes, @"removes",
4876 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4877 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4878 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4881 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4885 - (UIBarButtonItem *) leftButton {
4886 return [[[UIBarButtonItem alloc]
4887 initWithTitle:UCLocalize("CANCEL")
4888 style:UIBarButtonItemStylePlain
4890 action:@selector(cancelButtonClicked)
4895 - (void) applyRightButton {
4896 if ([issues_ count] == 0 && ![self isLoading])
4897 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4898 initWithTitle:UCLocalize("CONFIRM")
4899 style:UIBarButtonItemStyleDone
4901 action:@selector(confirmButtonClicked)
4904 [[self navigationItem] setRightBarButtonItem:nil];
4908 - (void) cancelButtonClicked {
4909 [self dismissModalViewControllerAnimated:YES];
4910 [delegate_ cancelAndClear:YES];
4914 - (void) confirmButtonClicked {
4915 if (essential_ != nil)
4925 /* Progress Data {{{ */
4926 @interface CydiaProgressData : NSObject {
4927 _transient id delegate_;
4936 _H<NSMutableArray> events_;
4937 _H<NSString> title_;
4939 _H<NSString> status_;
4940 _H<NSString> finish_;
4945 @implementation CydiaProgressData
4947 + (NSArray *) _attributeKeys {
4948 return [NSArray arrayWithObjects:
4960 - (NSArray *) attributeKeys {
4961 return [[self class] _attributeKeys];
4964 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4965 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4969 if ((self = [super init]) != nil) {
4970 events_ = [NSMutableArray arrayWithCapacity:32];
4974 - (void) setDelegate:(id)delegate {
4975 delegate_ = delegate;
4978 - (void) setPercent:(float)value {
4982 - (NSNumber *) percent {
4983 return [NSNumber numberWithFloat:percent_];
4986 - (void) setCurrent:(float)value {
4990 - (NSNumber *) current {
4991 return [NSNumber numberWithFloat:current_];
4994 - (void) setTotal:(float)value {
4998 - (NSNumber *) total {
4999 return [NSNumber numberWithFloat:total_];
5002 - (void) setSpeed:(float)value {
5006 - (NSNumber *) speed {
5007 return [NSNumber numberWithFloat:speed_];
5010 - (NSArray *) events {
5014 - (void) removeAllEvents {
5015 [events_ removeAllObjects];
5018 - (void) addEvent:(CydiaProgressEvent *)event {
5019 [events_ addObject:event];
5022 - (void) setTitle:(NSString *)text {
5026 - (NSString *) title {
5030 - (void) setFinish:(NSString *)text {
5034 - (NSString *) finish {
5035 return (id) finish_ ?: [NSNull null];
5038 - (void) setRunning:(bool)running {
5042 - (NSNumber *) running {
5043 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5048 /* Progress Controller {{{ */
5049 @interface ProgressController : CydiaWebViewController <
5052 _transient Database *database_;
5053 _H<CydiaProgressData, 1> progress_;
5057 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5059 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5061 - (void) setTitle:(NSString *)title;
5062 - (void) setCancellable:(bool)cancellable;
5066 @implementation ProgressController
5069 [database_ setProgressDelegate:nil];
5073 - (UIBarButtonItem *) leftButton {
5074 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5075 initWithTitle:UCLocalize("CANCEL")
5076 style:UIBarButtonItemStylePlain
5078 action:@selector(cancel)
5079 ] autorelease] : nil;
5082 - (void) updateCancel {
5083 [super applyLeftButton];
5086 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5087 if ((self = [super init]) != nil) {
5088 database_ = database;
5089 delegate_ = delegate;
5091 [database_ setProgressDelegate:self];
5093 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5094 [progress_ setDelegate:self];
5096 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5098 [scroller_ setBackgroundColor:[UIColor blackColor]];
5100 [[self navigationItem] setHidesBackButton:YES];
5102 [self updateCancel];
5106 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5107 [super webView:view didClearWindowObject:window forFrame:frame];
5108 [window setValue:progress_ forKey:@"cydiaProgress"];
5111 - (void) updateProgress {
5112 [self dispatchEvent:@"CydiaProgressUpdate"];
5115 - (void) viewWillAppear:(BOOL)animated {
5116 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5117 [super viewWillAppear:animated];
5121 UpdateExternalStatus(0);
5124 [delegate_ saveState];
5128 [delegate_ returnToCydia];
5132 [delegate_ terminateWithSuccess];
5133 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5134 [delegate_ suspendWithAnimation:YES];
5136 [delegate_ suspend];*/
5148 system("/usr/bin/sbreload");
5154 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5155 SBReboot(SBSSpringBoardServerPort());
5157 reboot2(RB_AUTOBOOT);
5164 - (void) setTitle:(NSString *)title {
5165 [progress_ setTitle:title];
5166 [self updateProgress];
5169 - (UIBarButtonItem *) rightButton {
5170 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5171 initWithTitle:UCLocalize("CLOSE")
5172 style:UIBarButtonItemStylePlain
5174 action:@selector(close)
5178 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5179 UpdateExternalStatus(1);
5181 [progress_ setRunning:true];
5182 [self setTitle:title];
5183 // implicit updateProgress
5185 SHA1SumValue notifyconf; {
5187 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5190 MMap mmap(file, MMap::ReadOnly);
5192 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5193 notifyconf = sha1.Result();
5197 SHA1SumValue springlist; {
5199 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5202 MMap mmap(file, MMap::ReadOnly);
5204 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5205 springlist = sha1.Result();
5209 if (invocation != nil) {
5210 [invocation yieldToSelector:@selector(invoke)];
5211 [self setTitle:@"COMPLETE"];
5216 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5219 MMap mmap(file, MMap::ReadOnly);
5221 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5222 if (!(notifyconf == sha1.Result()))
5229 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5232 MMap mmap(file, MMap::ReadOnly);
5234 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5235 if (!(springlist == sha1.Result()))
5241 if (RestartSubstrate_)
5245 RestartSubstrate_ = false;
5248 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5249 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5250 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5251 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5252 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5256 system("su -c /usr/bin/uicache mobile");
5259 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5261 [progress_ setRunning:false];
5262 [self updateProgress];
5264 [self applyRightButton];
5267 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5268 [progress_ addEvent:event];
5269 [self updateProgress];
5272 - (bool) isProgressCancelled {
5273 return cancel_ == 2;
5278 [self updateCancel];
5281 - (void) setCancellable:(bool)cancellable {
5282 unsigned cancel(cancel_);
5286 else if (cancel_ == 0)
5289 if (cancel != cancel_)
5290 [self updateCancel];
5293 - (void) setProgressCancellable:(NSNumber *)cancellable {
5294 [self setCancellable:[cancellable boolValue]];
5297 - (void) setProgressPercent:(NSNumber *)percent {
5298 [progress_ setPercent:[percent floatValue]];
5299 [self updateProgress];
5302 - (void) setProgressStatus:(NSDictionary *)status {
5303 if (status == nil) {
5304 [progress_ setCurrent:0];
5305 [progress_ setTotal:0];
5306 [progress_ setSpeed:0];
5308 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5310 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5311 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5312 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5315 [self updateProgress];
5321 /* Package Cell {{{ */
5322 @interface PackageCell : CyteTableViewCell <
5323 CyteTableViewCellDelegate
5327 _H<NSString> description_;
5329 _H<NSString> source_;
5331 _H<UIImage> placard_;
5335 - (PackageCell *) init;
5336 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5338 - (void) drawContentRect:(CGRect)rect;
5342 @implementation PackageCell
5344 - (PackageCell *) init {
5345 CGRect frame(CGRectMake(0, 0, 320, 74));
5346 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5347 UIView *content([self contentView]);
5348 CGRect bounds([content bounds]);
5350 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5351 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5352 [content addSubview:content_];
5354 [content_ setDelegate:self];
5355 [content_ setOpaque:YES];
5359 - (NSString *) accessibilityLabel {
5360 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5363 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5364 summarized_ = summary;
5374 [content_ setBackgroundColor:[UIColor whiteColor]];
5378 Source *source = [package source];
5380 icon_ = [package icon];
5382 if (NSString *name = [package name])
5383 name_ = [NSString stringWithString:name];
5385 NSString *description(nil);
5387 if (description == nil && IsWildcat_)
5388 description = [package longDescription];
5389 if (description == nil)
5390 description = [package shortDescription];
5392 if (description != nil)
5393 description_ = [NSString stringWithString:description];
5395 commercial_ = [package isCommercial];
5397 NSString *label = nil;
5398 bool trusted = false;
5400 if (source != nil) {
5401 label = [source label];
5402 trusted = [source trusted];
5403 } else if ([[package id] isEqualToString:@"firmware"])
5404 label = UCLocalize("APPLE");
5406 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5408 NSString *from(label);
5410 NSString *section = [package simpleSection];
5411 if (section != nil && ![section isEqualToString:label]) {
5412 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5413 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5416 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5418 if (NSString *purpose = [package primaryPurpose])
5419 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5424 if (NSString *mode = [package mode]) {
5425 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5426 color = RemovingColor_;
5427 //placard = @"removing";
5429 color = InstallingColor_;
5430 //placard = @"installing";
5433 // XXX: the removing/installing placards are not @2x
5436 color = [UIColor whiteColor];
5438 if ([package installed] != nil)
5439 placard = @"installed";
5444 [content_ setBackgroundColor:color];
5447 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5450 [self setNeedsDisplay];
5451 [content_ setNeedsDisplay];
5454 - (void) drawSummaryContentRect:(CGRect)rect {
5455 bool highlighted(highlighted_);
5456 float width([self bounds].size.width);
5460 rect.size = [(UIImage *) icon_ size];
5462 rect.size.width /= 4;
5463 rect.size.height /= 4;
5465 rect.origin.x = 14 - rect.size.width / 4;
5466 rect.origin.y = 14 - rect.size.height / 4;
5468 [icon_ drawInRect:rect];
5471 if (badge_ != nil) {
5473 rect.size = [(UIImage *) badge_ size];
5475 rect.size.width /= 4;
5476 rect.size.height /= 4;
5478 rect.origin.x = 20 - rect.size.width / 4;
5479 rect.origin.y = 20 - rect.size.height / 4;
5481 [badge_ drawInRect:rect];
5488 UISetColor(commercial_ ? Purple_ : Black_);
5489 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5491 if (placard_ != nil)
5492 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5495 - (void) drawNormalContentRect:(CGRect)rect {
5496 bool highlighted(highlighted_);
5497 float width([self bounds].size.width);
5501 rect.size = [(UIImage *) icon_ size];
5503 rect.size.width /= 2;
5504 rect.size.height /= 2;
5506 rect.origin.x = 25 - rect.size.width / 2;
5507 rect.origin.y = 25 - rect.size.height / 2;
5509 [icon_ drawInRect:rect];
5512 if (badge_ != nil) {
5514 rect.size = [(UIImage *) badge_ size];
5516 rect.size.width /= 2;
5517 rect.size.height /= 2;
5519 rect.origin.x = 36 - rect.size.width / 2;
5520 rect.origin.y = 36 - rect.size.height / 2;
5522 [badge_ drawInRect:rect];
5529 UISetColor(commercial_ ? Purple_ : Black_);
5530 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5531 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5534 UISetColor(commercial_ ? Purplish_ : Gray_);
5535 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5537 if (placard_ != nil)
5538 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5541 - (void) drawContentRect:(CGRect)rect {
5543 [self drawSummaryContentRect:rect];
5545 [self drawNormalContentRect:rect];
5550 /* Section Cell {{{ */
5551 @interface SectionCell : CyteTableViewCell <
5552 CyteTableViewCellDelegate
5554 _H<NSString> basic_;
5555 _H<NSString> section_;
5557 _H<NSString> count_;
5559 _H<UISwitch> switch_;
5563 - (void) setSection:(Section *)section editing:(BOOL)editing;
5567 @implementation SectionCell
5569 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5570 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5571 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5572 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5573 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5575 UIView *content([self contentView]);
5576 CGRect bounds([content bounds]);
5578 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5579 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5580 [content addSubview:content_];
5581 [content_ setBackgroundColor:[UIColor whiteColor]];
5583 [content_ setDelegate:self];
5587 - (void) onSwitch:(id)sender {
5588 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5589 if (metadata == nil) {
5590 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5591 [Sections_ setObject:metadata forKey:basic_];
5594 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5598 - (void) setSection:(Section *)section editing:(BOOL)editing {
5599 if (editing != editing_) {
5601 [switch_ removeFromSuperview];
5603 [self addSubview:switch_];
5612 if (section == nil) {
5613 name_ = UCLocalize("ALL_PACKAGES");
5616 basic_ = [section name];
5617 section_ = [section localized];
5619 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5620 count_ = [NSString stringWithFormat:@"%d", [section count]];
5623 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5626 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5627 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5629 [content_ setNeedsDisplay];
5632 - (void) setFrame:(CGRect)frame {
5633 [super setFrame:frame];
5635 CGRect rect([switch_ frame]);
5636 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5639 - (NSString *) accessibilityLabel {
5643 - (void) drawContentRect:(CGRect)rect {
5644 bool highlighted(highlighted_ && !editing_);
5646 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5651 float width(rect.size.width);
5657 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5659 CGSize size = [count_ sizeWithFont:Font14_];
5663 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5669 /* File Table {{{ */
5670 @interface FileTable : CyteViewController <
5671 UITableViewDataSource,
5674 _transient Database *database_;
5675 _H<Package> package_;
5677 _H<NSMutableArray> files_;
5678 _H<UITableView, 2> list_;
5681 - (id) initWithDatabase:(Database *)database;
5682 - (void) setPackage:(Package *)package;
5686 @implementation FileTable
5688 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5689 return files_ == nil ? 0 : [files_ count];
5692 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5696 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5697 static NSString *reuseIdentifier = @"Cell";
5699 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5701 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5702 [cell setFont:[UIFont systemFontOfSize:16]];
5704 [cell setText:[files_ objectAtIndex:indexPath.row]];
5705 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5710 - (NSURL *) navigationURL {
5711 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5715 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5717 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5718 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5719 [list_ setRowHeight:24.0f];
5720 [(UITableView *) list_ setDataSource:self];
5721 [list_ setDelegate:self];
5722 [[self view] addSubview:list_];
5725 - (void) viewDidLoad {
5726 [super viewDidLoad];
5728 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5731 - (void) releaseSubviews {
5734 [super releaseSubviews];
5737 - (id) initWithDatabase:(Database *)database {
5738 if ((self = [super init]) != nil) {
5739 database_ = database;
5741 files_ = [NSMutableArray arrayWithCapacity:32];
5745 - (void) setPackage:(Package *)package {
5749 [files_ removeAllObjects];
5751 if (package != nil) {
5753 name_ = [package id];
5755 if (NSArray *files = [package files])
5756 [files_ addObjectsFromArray:files];
5758 if ([files_ count] != 0) {
5759 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5760 [files_ removeObjectAtIndex:0];
5761 [files_ sortUsingSelector:@selector(compareByPath:)];
5763 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5764 [stack addObject:@"/"];
5766 for (int i(0), e([files_ count]); i != e; ++i) {
5767 NSString *file = [files_ objectAtIndex:i];
5768 while (![file hasPrefix:[stack lastObject]])
5769 [stack removeLastObject];
5770 NSString *directory = [stack lastObject];
5771 [stack addObject:[file stringByAppendingString:@"/"]];
5772 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5773 ([stack count] - 2) * 3, "",
5774 [file substringFromIndex:[directory length]]
5783 - (void) reloadData {
5786 [self setPackage:[database_ packageWithName:name_]];
5791 /* Package Controller {{{ */
5792 @interface CYPackageController : CydiaWebViewController <
5793 UIActionSheetDelegate
5795 _transient Database *database_;
5796 _H<Package> package_;
5799 _H<NSMutableArray> buttons_;
5800 _H<UIBarButtonItem> button_;
5803 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5807 @implementation CYPackageController
5809 - (NSURL *) navigationURL {
5810 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5813 /* XXX: this is not safe at all... localization of /fail/ */
5814 - (void) _clickButtonWithName:(NSString *)name {
5815 if ([name isEqualToString:UCLocalize("CLEAR")])
5816 [delegate_ clearPackage:package_];
5817 else if ([name isEqualToString:UCLocalize("INSTALL")])
5818 [delegate_ installPackage:package_];
5819 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5820 [delegate_ installPackage:package_];
5821 else if ([name isEqualToString:UCLocalize("REMOVE")])
5822 [delegate_ removePackage:package_];
5823 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5824 [delegate_ installPackage:package_];
5825 else _assert(false);
5828 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5829 NSString *context([sheet context]);
5831 if ([context isEqualToString:@"modify"]) {
5832 if (button != [sheet cancelButtonIndex]) {
5833 NSString *buttonName = [buttons_ objectAtIndex:button];
5834 [self _clickButtonWithName:buttonName];
5837 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5841 - (bool) _allowJavaScriptPanel {
5846 - (void) _customButtonClicked {
5847 int count([buttons_ count]);
5852 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5854 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5855 [buttons addObjectsFromArray:buttons_];
5857 UIActionSheet *sheet = [[[UIActionSheet alloc]
5860 cancelButtonTitle:nil
5861 destructiveButtonTitle:nil
5862 otherButtonTitles:nil
5865 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5867 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5868 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5870 [sheet setContext:@"modify"];
5872 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5876 // We don't want to allow non-commercial packages to do custom things to the install button,
5877 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5878 - (void) customButtonClicked {
5880 [super customButtonClicked];
5882 [self _customButtonClicked];
5885 - (void) reloadButtonClicked {
5886 // Don't reload a commerical package by tapping the loading button,
5887 // but if it's not an Install button, we should forward it on.
5888 if (![package_ uninstalled])
5889 [self _customButtonClicked];
5892 - (void) applyLoadingTitle {
5893 // Don't show "Loading" as the title. Ever.
5896 - (UIBarButtonItem *) rightButton {
5901 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5902 if ((self = [super init]) != nil) {
5903 database_ = database;
5904 buttons_ = [NSMutableArray arrayWithCapacity:4];
5905 name_ = name == nil ? @"" : [NSString stringWithString:name];
5906 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5910 - (void) reloadData {
5913 package_ = [database_ packageWithName:name_];
5915 [buttons_ removeAllObjects];
5917 if (package_ != nil) {
5918 [(Package *) package_ parse];
5920 commercial_ = [package_ isCommercial];
5922 if ([package_ mode] != nil)
5923 [buttons_ addObject:UCLocalize("CLEAR")];
5924 if ([package_ source] == nil);
5925 else if ([package_ upgradableAndEssential:NO])
5926 [buttons_ addObject:UCLocalize("UPGRADE")];
5927 else if ([package_ uninstalled])
5928 [buttons_ addObject:UCLocalize("INSTALL")];
5930 [buttons_ addObject:UCLocalize("REINSTALL")];
5931 if (![package_ uninstalled])
5932 [buttons_ addObject:UCLocalize("REMOVE")];
5936 switch ([buttons_ count]) {
5937 case 0: title = nil; break;
5938 case 1: title = [buttons_ objectAtIndex:0]; break;
5939 default: title = UCLocalize("MODIFY"); break;
5942 button_ = [[[UIBarButtonItem alloc]
5944 style:UIBarButtonItemStylePlain
5946 action:@selector(customButtonClicked)
5950 - (bool) isLoading {
5951 return commercial_ ? [super isLoading] : false;
5957 /* Package List Controller {{{ */
5958 @interface PackageListController : CyteViewController <
5959 UITableViewDataSource,
5962 _transient Database *database_;
5964 _H<NSArray> packages_;
5965 _H<NSMutableArray> sections_;
5966 _H<UITableView, 2> list_;
5967 _H<NSMutableArray> index_;
5968 _H<NSMutableDictionary> indices_;
5969 _H<NSString> title_;
5970 unsigned reloading_;
5973 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5974 - (void) setDelegate:(id)delegate;
5975 - (void) resetCursor;
5980 @implementation PackageListController
5982 - (bool) isSummarized {
5986 - (bool) showsSections {
5990 - (void) deselectWithAnimation:(BOOL)animated {
5991 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5994 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5995 CGRect base = [[self view] bounds];
5996 base.size.height -= bounds.size.height;
5997 base.origin = [list_ frame].origin;
5999 [UIView beginAnimations:nil context:NULL];
6000 [UIView setAnimationBeginsFromCurrentState:YES];
6001 [UIView setAnimationCurve:curve];
6002 [UIView setAnimationDuration:duration];
6003 [list_ setFrame:base];
6004 [UIView commitAnimations];
6007 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6008 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6011 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6012 [self resizeForKeyboardBounds:bounds duration:0];
6015 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6016 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6017 *curve = UIViewAnimationCurveEaseInOut;
6019 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6021 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6024 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6027 - (void) keyboardWillShow:(NSNotification *)notification {
6030 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6031 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6033 NSTimeInterval duration;
6034 UIViewAnimationCurve curve;
6035 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6037 CGRect kbframe = CGRectMake(round(center.x - bounds.size.width / 2.0), round(center.y - bounds.size.height / 2.0), bounds.size.width, bounds.size.height);
6038 UIViewController *base = self;
6039 while ([base parentViewController] != nil)
6040 base = [base parentViewController];
6041 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6042 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6044 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6045 intersection.size.height += CYStatusBarHeight([self interfaceOrientation]);
6047 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6050 - (void) keyboardWillHide:(NSNotification *)notification {
6051 NSTimeInterval duration;
6052 UIViewAnimationCurve curve;
6053 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6055 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6058 - (void) viewWillAppear:(BOOL)animated {
6059 [super viewWillAppear:animated];
6061 [self resizeForKeyboardBounds:CGRectZero];
6062 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6063 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6066 - (void) viewWillDisappear:(BOOL)animated {
6067 [super viewWillDisappear:animated];
6069 [self resizeForKeyboardBounds:CGRectZero];
6070 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6071 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6074 - (void) viewDidAppear:(BOOL)animated {
6075 [super viewDidAppear:animated];
6076 [self deselectWithAnimation:animated];
6079 - (void) didSelectPackage:(Package *)package {
6080 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6081 [view setDelegate:delegate_];
6082 [[self navigationController] pushViewController:view animated:YES];
6085 #if TryIndexedCollation
6086 + (BOOL) hasIndexedCollation {
6087 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6091 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6092 NSInteger count([sections_ count]);
6093 return count == 0 ? 1 : count;
6096 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6097 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6099 return [[sections_ objectAtIndex:section] name];
6102 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6103 if ([sections_ count] == 0)
6105 return [[sections_ objectAtIndex:section] count];
6108 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6109 @synchronized (database_) {
6110 if ([database_ era] != era_)
6113 Section *section([sections_ objectAtIndex:[path section]]);
6114 NSInteger row([path row]);
6115 Package *package([packages_ objectAtIndex:([section row] + row)]);
6116 return [[package retain] autorelease];
6119 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6120 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6122 cell = [[[PackageCell alloc] init] autorelease];
6124 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6125 [cell setPackage:package asSummary:[self isSummarized]];
6129 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6130 Package *package([self packageAtIndexPath:path]);
6131 package = [database_ packageWithName:[package id]];
6132 [self didSelectPackage:package];
6135 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6136 if (![self showsSections])
6142 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6143 #if TryIndexedCollation
6144 if ([[self class] hasIndexedCollation]) {
6145 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6152 - (void) updateHeight {
6153 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6156 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6157 if ((self = [super init]) != nil) {
6158 database_ = database;
6159 title_ = [title copy];
6160 [[self navigationItem] setTitle:title_];
6162 #if TryIndexedCollation
6163 if ([[self class] hasIndexedCollation])
6164 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6167 index_ = [NSMutableArray arrayWithCapacity:32];
6169 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6171 packages_ = [NSArray array];
6172 sections_ = [NSMutableArray arrayWithCapacity:16];
6177 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6179 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6180 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6181 [[self view] addSubview:list_];
6183 // XXX: is 20 the most optimal number here?
6184 [list_ setSectionIndexMinimumDisplayRowCount:20];
6186 [(UITableView *) list_ setDataSource:self];
6187 [list_ setDelegate:self];
6189 [self updateHeight];
6192 - (void) releaseSubviews {
6195 [super releaseSubviews];
6198 - (void) setDelegate:(id)delegate {
6199 delegate_ = delegate;
6202 - (bool) shouldYield {
6206 - (bool) shouldBlock {
6210 - (NSMutableArray *) _reloadPackages {
6211 @synchronized (database_) {
6212 era_ = [database_ era];
6213 NSArray *packages([database_ packages]);
6215 return [NSMutableArray arrayWithArray:packages];
6218 - (void) _reloadData {
6219 if (reloading_ != 0) {
6226 if ([self shouldYield]) {
6230 if (![self shouldBlock])
6233 hud = [delegate_ addProgressHUD];
6234 [hud setText:UCLocalize("LOADING")];
6238 packages = [self yieldToSelector:@selector(_reloadPackages)];
6241 [delegate_ removeProgressHUD:hud];
6242 } while (reloading_ == 2);
6246 packages = [self _reloadPackages];
6249 packages_ = packages;
6251 [indices_ removeAllObjects];
6252 [sections_ removeAllObjects];
6254 Section *section = nil;
6256 #if TryIndexedCollation
6257 if ([[self class] hasIndexedCollation]) {
6258 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6259 NSArray *titles = [collation sectionIndexTitles];
6262 _profile(PackageTable$reloadData$Section)
6263 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6267 _profile(PackageTable$reloadData$Section$Package)
6268 package = [packages_ objectAtIndex:offset];
6269 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6272 while (secidx < index) {
6275 _profile(PackageTable$reloadData$Section$Allocate)
6276 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6279 _profile(PackageTable$reloadData$Section$Add)
6280 [sections_ addObject:section];
6284 [section addToCount];
6290 [index_ removeAllObjects];
6292 bool sectioned([self showsSections]);
6294 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6295 [sections_ addObject:section];
6298 _profile(PackageTable$reloadData$Section)
6299 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6303 _profile(PackageTable$reloadData$Section$Package)
6304 package = [packages_ objectAtIndex:offset];
6305 index = [package index];
6308 if (sectioned && (section == nil || [section index] != index)) {
6309 _profile(PackageTable$reloadData$Section$Allocate)
6310 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6313 [index_ addObject:[section name]];
6314 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6316 _profile(PackageTable$reloadData$Section$Add)
6317 [sections_ addObject:section];
6321 [section addToCount];
6326 [self updateHeight];
6328 _profile(PackageTable$reloadData$List)
6329 [(UITableView *) list_ setDataSource:self];
6334 - (void) reloadData {
6336 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6339 - (void) resetCursor {
6340 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6343 - (void) clearData {
6344 [self updateHeight];
6346 [list_ setDataSource:nil];
6354 /* Filtered Package List Controller {{{ */
6355 @interface FilteredPackageListController : PackageListController {
6358 _H<NSObject> object_;
6361 - (void) setObject:(id)object;
6362 - (void) setObject:(id)object forFilter:(SEL)filter;
6365 - (void) setFilter:(SEL)filter;
6367 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6371 @implementation FilteredPackageListController
6377 - (void) setFilter:(SEL)filter {
6378 @synchronized (self) {
6381 /* XXX: this is an unsafe optimization of doomy hell */
6382 Method method(class_getInstanceMethod([Package class], filter));
6383 _assert(method != NULL);
6384 imp_ = method_getImplementation(method);
6385 _assert(imp_ != NULL);
6388 - (void) setObject:(id)object {
6389 @synchronized (self) {
6393 - (void) setObject:(id)object forFilter:(SEL)filter {
6394 @synchronized (self) {
6395 [self setFilter:filter];
6396 [self setObject:object];
6399 - (NSMutableArray *) _reloadPackages {
6400 @synchronized (database_) {
6401 era_ = [database_ era];
6402 NSArray *packages([database_ packages]);
6404 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6408 _H<NSObject> object;
6410 @synchronized (self) {
6416 _profile(PackageTable$reloadData$Filter)
6417 for (Package *package in packages)
6418 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6419 [filtered addObject:package];
6425 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6426 if ((self = [super initWithDatabase:database title:title]) != nil) {
6427 [self setFilter:filter];
6428 [self setObject:object];
6435 /* Home Controller {{{ */
6436 @interface HomeController : CydiaWebViewController {
6441 @implementation HomeController
6444 if ((self = [super init]) != nil) {
6445 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6450 - (NSURL *) navigationURL {
6451 return [NSURL URLWithString:@"cydia://home"];
6454 - (void) didReceiveMemoryWarning {
6457 - (void) aboutButtonClicked {
6458 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6460 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6461 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6462 [alert setCancelButtonIndex:0];
6465 @"Copyright \u00a9 2008-2011\n"
6468 "Jay Freeman (saurik)\n"
6469 "saurik@saurik.com\n"
6470 "http://www.saurik.com/"
6476 - (UIBarButtonItem *) leftButton {
6477 return [[[UIBarButtonItem alloc]
6478 initWithTitle:UCLocalize("ABOUT")
6479 style:UIBarButtonItemStylePlain
6481 action:@selector(aboutButtonClicked)
6487 /* Manage Controller {{{ */
6488 @interface ManageController : CydiaWebViewController {
6491 - (void) queueStatusDidChange;
6495 @implementation ManageController
6498 if ((self = [super init]) != nil) {
6499 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6503 - (NSURL *) navigationURL {
6504 return [NSURL URLWithString:@"cydia://manage"];
6507 - (UIBarButtonItem *) leftButton {
6508 return [[[UIBarButtonItem alloc]
6509 initWithTitle:UCLocalize("SETTINGS")
6510 style:UIBarButtonItemStylePlain
6512 action:@selector(settingsButtonClicked)
6516 - (void) settingsButtonClicked {
6517 [delegate_ showSettings];
6520 - (void) queueButtonClicked {
6524 - (UIBarButtonItem *) customButton {
6525 return Queuing_ ? [[[UIBarButtonItem alloc]
6526 initWithTitle:UCLocalize("QUEUE")
6527 style:UIBarButtonItemStyleDone
6529 action:@selector(queueButtonClicked)
6530 ] autorelease] : [super customButton];
6533 - (void) queueStatusDidChange {
6534 [self applyRightButton];
6537 - (bool) isLoading {
6538 return !Queuing_ && [super isLoading];
6544 /* Refresh Bar {{{ */
6545 @interface RefreshBar : UINavigationBar {
6546 _H<UIProgressIndicator> indicator_;
6547 _H<UITextLabel> prompt_;
6548 _H<UIProgressBar> progress_;
6549 _H<UINavigationButton> cancel_;
6554 @implementation RefreshBar
6556 - (void) positionViews {
6557 CGRect frame = [cancel_ frame];
6558 frame.size = [cancel_ sizeThatFits:frame.size];
6559 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6560 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6561 [cancel_ setFrame:frame];
6563 CGSize prgsize = {75, 100};
6565 [self frame].size.width - prgsize.width - 10,
6566 ([self frame].size.height - prgsize.height) / 2
6568 [progress_ setFrame:prgrect];
6570 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6571 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6572 CGRect indrect = {{indoffset, indoffset}, indsize};
6573 [indicator_ setFrame:indrect];
6575 CGSize prmsize = {215, indsize.height + 4};
6577 indoffset * 2 + indsize.width,
6578 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6580 [prompt_ setFrame:prmrect];
6583 - (void) setFrame:(CGRect)frame {
6584 [super setFrame:frame];
6585 [self positionViews];
6588 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6589 if ((self = [super initWithFrame:frame]) != nil) {
6590 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6592 [self setBarStyle:UIBarStyleBlack];
6594 UIBarStyle barstyle([self _barStyle:NO]);
6595 bool ugly(barstyle == UIBarStyleDefault);
6597 UIProgressIndicatorStyle style = ugly ?
6598 UIProgressIndicatorStyleMediumBrown :
6599 UIProgressIndicatorStyleMediumWhite;
6601 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6602 [(UIProgressIndicator *) indicator_ setStyle:style];
6603 [indicator_ startAnimation];
6604 [self addSubview:indicator_];
6606 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6607 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6608 [prompt_ setBackgroundColor:[UIColor clearColor]];
6609 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6610 [self addSubview:prompt_];
6612 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6613 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6614 [(UIProgressBar *) progress_ setStyle:0];
6615 [self addSubview:progress_];
6617 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6618 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6619 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6620 [cancel_ setBarStyle:barstyle];
6622 [self positionViews];
6626 - (void) setCancellable:(bool)cancellable {
6628 [self addSubview:cancel_];
6630 [cancel_ removeFromSuperview];
6634 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6635 [progress_ setProgress:0];
6639 [self setCancellable:NO];
6642 - (void) setPrompt:(NSString *)prompt {
6643 [prompt_ setText:prompt];
6646 - (void) setProgress:(float)progress {
6647 [progress_ setProgress:progress];
6653 /* Cydia Navigation Controller Interface {{{ */
6654 @interface UINavigationController (Cydia)
6656 - (NSArray *) navigationURLCollection;
6657 - (void) unloadData;
6662 /* Cydia Tab Bar Controller {{{ */
6663 @interface CYTabBarController : UITabBarController <
6664 UITabBarControllerDelegate,
6667 _transient Database *database_;
6668 _H<RefreshBar, 1> refreshbar_;
6672 // XXX: ok, "updatedelegate_"?...
6673 _transient NSObject<CydiaDelegate> *updatedelegate_;
6675 _H<UIViewController> remembered_;
6676 _transient UIViewController *transient_;
6679 - (NSArray *) navigationURLCollection;
6680 - (void) dropBar:(BOOL)animated;
6681 - (void) beginUpdate;
6682 - (void) raiseBar:(BOOL)animated;
6684 - (void) unloadData;
6688 @implementation CYTabBarController
6690 - (void) setUnselectedViewController:(UIViewController *)transient {
6691 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6692 if (transient != nil) {
6693 if (transient_ == nil)
6694 remembered_ = [controllers objectAtIndex:0];
6695 transient_ = transient;
6696 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6697 [controllers replaceObjectAtIndex:0 withObject:transient_];
6698 [self setSelectedIndex:0];
6699 [self setViewControllers:controllers];
6700 [self concealTabBarSelection];
6701 } else if (remembered_ != nil) {
6702 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6703 transient_ = transient;
6704 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6706 [self setViewControllers:controllers];
6707 [self revealTabBarSelection];
6711 - (UIViewController *) unselectedViewController {
6715 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6716 if ([self unselectedViewController])
6717 [self setUnselectedViewController:nil];
6720 - (NSArray *) navigationURLCollection {
6721 NSMutableArray *items([NSMutableArray array]);
6723 // XXX: Should this deal with transient view controllers?
6724 for (id navigation in [self viewControllers]) {
6725 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6727 [items addObject:stack];
6733 - (void) unloadData {
6736 for (UINavigationController *controller in [self viewControllers])
6737 [controller unloadData];
6739 if (UIViewController *selected = [self selectedViewController])
6740 [selected reloadData];
6742 if (UIViewController *unselected = [self unselectedViewController]) {
6743 [unselected unloadData];
6744 [unselected reloadData];
6749 [[NSNotificationCenter defaultCenter] removeObserver:self];
6754 - (id) initWithDatabase:(Database *)database {
6755 if ((self = [super init]) != nil) {
6756 database_ = database;
6757 [self setDelegate:self];
6759 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6760 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6762 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6766 - (void) setUpdate:(NSDate *)date {
6770 - (void) beginUpdate {
6771 [(RefreshBar *) refreshbar_ start];
6774 [updatedelegate_ retainNetworkActivityIndicator];
6778 detachNewThreadSelector:@selector(performUpdate)
6784 - (void) performUpdate {
6785 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6788 status.setDelegate(self);
6789 [database_ updateWithStatus:status];
6792 performSelectorOnMainThread:@selector(completeUpdate)
6800 - (void) stopUpdateWithSelector:(SEL)selector {
6802 [updatedelegate_ releaseNetworkActivityIndicator];
6804 [self raiseBar:YES];
6807 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6810 - (void) completeUpdate {
6813 [self stopUpdateWithSelector:@selector(reloadData)];
6816 - (void) cancelUpdate {
6817 [self stopUpdateWithSelector:@selector(updateData)];
6820 - (void) cancelPressed {
6821 [self cancelUpdate];
6828 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6829 [refreshbar_ setPrompt:[event compoundMessage]];
6832 - (bool) isProgressCancelled {
6836 - (void) setProgressCancellable:(NSNumber *)cancellable {
6837 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6840 - (void) setProgressPercent:(NSNumber *)percent {
6841 [refreshbar_ setProgress:[percent floatValue]];
6844 - (void) setProgressStatus:(NSDictionary *)status {
6846 [self setProgressPercent:[status objectForKey:@"Percent"]];
6849 - (void) setUpdateDelegate:(id)delegate {
6850 updatedelegate_ = delegate;
6853 - (UIView *) transitionView {
6854 if ([self respondsToSelector:@selector(_transitionView)])
6855 return [self _transitionView];
6857 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6860 - (void) dropBar:(BOOL)animated {
6865 UIView *transition([self transitionView]);
6866 [[self view] addSubview:refreshbar_];
6868 CGRect barframe([refreshbar_ frame]);
6870 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6871 barframe.origin.y = CYStatusBarHeight([self interfaceOrientation]);
6873 barframe.origin.y = 0;
6875 [refreshbar_ setFrame:barframe];
6878 [UIView beginAnimations:nil context:NULL];
6880 CGRect viewframe = [transition frame];
6881 viewframe.origin.y += barframe.size.height;
6882 viewframe.size.height -= barframe.size.height;
6883 [transition setFrame:viewframe];
6886 [UIView commitAnimations];
6888 // Ensure bar has the proper width for our view, it might have changed
6889 barframe.size.width = viewframe.size.width;
6890 [refreshbar_ setFrame:barframe];
6893 - (void) raiseBar:(BOOL)animated {
6898 UIView *transition([self transitionView]);
6899 [refreshbar_ removeFromSuperview];
6901 CGRect barframe([refreshbar_ frame]);
6904 [UIView beginAnimations:nil context:NULL];
6906 CGRect viewframe = [transition frame];
6907 viewframe.origin.y -= barframe.size.height;
6908 viewframe.size.height += barframe.size.height;
6909 [transition setFrame:viewframe];
6912 [UIView commitAnimations];
6915 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6916 bool dropped(dropped_);
6921 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6927 - (void) statusBarFrameChanged:(NSNotification *)notification {
6937 /* Cydia Navigation Controller Implementation {{{ */
6938 @implementation UINavigationController (Cydia)
6940 - (NSArray *) navigationURLCollection {
6941 NSMutableArray *stack([NSMutableArray array]);
6943 for (CyteViewController *controller in [self viewControllers]) {
6944 NSString *url = [[controller navigationURL] absoluteString];
6946 [stack addObject:url];
6952 - (void) reloadData {
6955 UIViewController *visible([self visibleViewController]);
6957 [visible reloadData];
6959 // on the iPad, this view controller is ALSO visible. :(
6961 if (UIViewController *top = [self topViewController])
6966 - (void) unloadData {
6967 for (CyteViewController *page in [self viewControllers])
6976 /* Cydia:// Protocol {{{ */
6977 @interface CydiaURLProtocol : NSURLProtocol {
6982 @implementation CydiaURLProtocol
6984 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6985 NSURL *url([request URL]);
6989 NSString *scheme([[url scheme] lowercaseString]);
6990 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6992 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6998 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7002 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7003 id<NSURLProtocolClient> client([self client]);
7005 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7007 NSData *data(UIImagePNGRepresentation(icon));
7009 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7010 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7011 [client URLProtocol:self didLoadData:data];
7012 [client URLProtocolDidFinishLoading:self];
7016 - (void) startLoading {
7017 id<NSURLProtocolClient> client([self client]);
7018 NSURLRequest *request([self request]);
7020 NSURL *url([request URL]);
7021 NSString *href([url absoluteString]);
7022 NSString *scheme([[url scheme] lowercaseString]);
7026 if ([scheme isEqualToString:@"cydia"])
7027 path = [href substringFromIndex:8];
7028 else if ([scheme isEqualToString:@"about"])
7029 path = [href substringFromIndex:12];
7030 else _assert(false);
7032 NSRange slash([path rangeOfString:@"/"]);
7035 if (slash.location == NSNotFound) {
7039 command = [path substringToIndex:slash.location];
7040 path = [path substringFromIndex:(slash.location + 1)];
7043 Database *database([Database sharedInstance]);
7045 if ([command isEqualToString:@"package-icon"]) {
7048 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7049 Package *package([database packageWithName:path]);
7053 UIImage *icon([package icon]);
7054 [self _returnPNGWithImage:icon forRequest:request];
7055 } else if ([command isEqualToString:@"source-icon"]) {
7058 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7059 NSString *source(Simplify(path));
7060 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7062 icon = [UIImage applicationImageNamed:@"unknown.png"];
7063 [self _returnPNGWithImage:icon forRequest:request];
7064 } else if ([command isEqualToString:@"uikit-image"]) {
7067 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7068 UIImage *icon(_UIImageWithName(path));
7069 [self _returnPNGWithImage:icon forRequest:request];
7070 } else if ([command isEqualToString:@"section-icon"]) {
7073 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7074 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7076 icon = [UIImage applicationImageNamed:@"unknown.png"];
7077 [self _returnPNGWithImage:icon forRequest:request];
7079 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7083 - (void) stopLoading {
7089 /* Section Controller {{{ */
7090 @interface SectionController : FilteredPackageListController {
7091 _H<NSString> section_;
7094 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7098 @implementation SectionController
7100 - (NSURL *) navigationURL {
7101 NSString *name = section_;
7105 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7108 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7111 title = UCLocalize("ALL_PACKAGES");
7112 else if (![name isEqual:@""])
7113 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7115 title = UCLocalize("NO_SECTION");
7117 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7124 /* Sections Controller {{{ */
7125 @interface SectionsController : CyteViewController <
7126 UITableViewDataSource,
7129 _transient Database *database_;
7130 _H<NSMutableArray> sections_;
7131 _H<NSMutableArray> filtered_;
7132 _H<UITableView, 2> list_;
7135 - (id) initWithDatabase:(Database *)database;
7136 - (void) editButtonClicked;
7140 @implementation SectionsController
7142 - (NSURL *) navigationURL {
7143 return [NSURL URLWithString:@"cydia://sections"];
7146 - (void) updateNavigationItem {
7147 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7148 if ([sections_ count] == 0) {
7149 [[self navigationItem] setRightBarButtonItem:nil];
7151 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7152 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7154 action:@selector(editButtonClicked)
7155 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7159 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7160 [super setEditing:editing animated:animated];
7165 [delegate_ updateData];
7167 [self updateNavigationItem];
7170 - (void) viewDidAppear:(BOOL)animated {
7171 [super viewDidAppear:animated];
7172 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7175 - (void) viewWillDisappear:(BOOL)animated {
7176 [super viewWillDisappear:animated];
7177 if ([self isEditing]) [self setEditing:NO];
7180 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7181 Section *section = nil;
7182 int index = [indexPath row];
7183 if (![self isEditing]) {
7186 section = [filtered_ objectAtIndex:index];
7188 section = [sections_ objectAtIndex:index];
7193 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7194 if ([self isEditing])
7195 return [sections_ count];
7197 return [filtered_ count] + 1;
7200 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7204 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7205 static NSString *reuseIdentifier = @"SectionCell";
7207 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7209 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7211 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7216 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7217 if ([self isEditing])
7220 Section *section = [self sectionAtIndexPath:indexPath];
7222 SectionController *controller = [[[SectionController alloc]
7223 initWithDatabase:database_
7224 section:[section name]
7226 [controller setDelegate:delegate_];
7228 [[self navigationController] pushViewController:controller animated:YES];
7232 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7234 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7235 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7236 [list_ setRowHeight:45.0f];
7237 [(UITableView *) list_ setDataSource:self];
7238 [list_ setDelegate:self];
7239 [[self view] addSubview:list_];
7242 - (void) viewDidLoad {
7243 [super viewDidLoad];
7245 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7248 - (void) releaseSubviews {
7251 [super releaseSubviews];
7254 - (id) initWithDatabase:(Database *)database {
7255 if ((self = [super init]) != nil) {
7256 database_ = database;
7258 sections_ = [NSMutableArray arrayWithCapacity:16];
7259 filtered_ = [NSMutableArray arrayWithCapacity:16];
7263 - (void) reloadData {
7266 NSArray *packages = [database_ packages];
7268 [sections_ removeAllObjects];
7269 [filtered_ removeAllObjects];
7271 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7274 for (Package *package in packages) {
7275 NSString *name([package section]);
7276 NSString *key(name == nil ? @"" : name);
7280 _profile(SectionsView$reloadData$Section)
7281 section = [sections objectForKey:key];
7282 if (section == nil) {
7283 _profile(SectionsView$reloadData$Section$Allocate)
7284 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7285 [sections setObject:section forKey:key];
7290 [section addToCount];
7292 _profile(SectionsView$reloadData$Filter)
7293 if (![package valid] || ![package visible])
7301 [sections_ addObjectsFromArray:[sections allValues]];
7303 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7305 for (Section *section in (id) sections_) {
7306 size_t count([section row]);
7310 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7311 [section setCount:count];
7312 [filtered_ addObject:section];
7315 [self updateNavigationItem];
7320 - (void) editButtonClicked {
7321 [self setEditing:![self isEditing] animated:YES];
7327 /* Changes Controller {{{ */
7328 @interface ChangesController : CyteViewController <
7329 UITableViewDataSource,
7332 _transient Database *database_;
7334 _H<NSArray> packages_;
7335 _H<NSMutableArray> sections_;
7336 _H<UITableView, 2> list_;
7340 - (id) initWithDatabase:(Database *)database;
7344 @implementation ChangesController
7346 - (NSURL *) navigationURL {
7347 return [NSURL URLWithString:@"cydia://changes"];
7350 - (void) viewDidAppear:(BOOL)animated {
7351 [super viewDidAppear:animated];
7352 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7355 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7356 NSInteger count([sections_ count]);
7357 return count == 0 ? 1 : count;
7360 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7361 if ([sections_ count] == 0)
7363 return [[sections_ objectAtIndex:section] name];
7366 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7367 if ([sections_ count] == 0)
7369 return [[sections_ objectAtIndex:section] count];
7372 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7373 @synchronized (database_) {
7374 if ([database_ era] != era_)
7377 NSUInteger sectionIndex([path section]);
7378 if (sectionIndex >= [sections_ count])
7380 Section *section([sections_ objectAtIndex:sectionIndex]);
7381 NSInteger row([path row]);
7382 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7385 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7386 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7388 cell = [[[PackageCell alloc] init] autorelease];
7390 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7391 [cell setPackage:package asSummary:false];
7395 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7396 Package *package([self packageAtIndexPath:path]);
7397 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7398 [view setDelegate:delegate_];
7399 [[self navigationController] pushViewController:view animated:YES];
7403 - (void) refreshButtonClicked {
7404 [delegate_ beginUpdate];
7405 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7408 - (void) upgradeButtonClicked {
7409 [delegate_ distUpgrade];
7410 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7414 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7416 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7417 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7418 [list_ setRowHeight:73];
7419 [(UITableView *) list_ setDataSource:self];
7420 [list_ setDelegate:self];
7421 [[self view] addSubview:list_];
7424 - (void) viewDidLoad {
7425 [super viewDidLoad];
7427 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7430 - (void) releaseSubviews {
7433 [super releaseSubviews];
7436 - (id) initWithDatabase:(Database *)database {
7437 if ((self = [super init]) != nil) {
7438 database_ = database;
7440 packages_ = [NSArray array];
7441 sections_ = [NSMutableArray arrayWithCapacity:16];
7445 - (NSMutableArray *) _reloadPackages {
7446 @synchronized (database_) {
7447 era_ = [database_ era];
7448 NSArray *packages([database_ packages]);
7450 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7453 _profile(ChangesController$_reloadPackages$Filter)
7454 for (Package *package in packages)
7455 if ([package upgradableAndEssential:YES] || [package visible])
7456 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7459 _profile(ChangesController$_reloadPackages$radixSort)
7460 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7467 - (void) _reloadData {
7472 UIProgressHUD *hud([delegate_ addProgressHUD]);
7473 [hud setText:UCLocalize("LOADING")];
7474 //NSLog(@"HUD:%@::%@", delegate_, hud);
7475 packages = [self yieldToSelector:@selector(_reloadPackages)];
7476 [delegate_ removeProgressHUD:hud];
7478 packages = [self _reloadPackages];
7481 @synchronized (database_) {
7482 if (era_ != [database_ era])
7485 packages_ = packages;
7486 [sections_ removeAllObjects];
7488 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7489 Section *ignored = nil;
7490 Section *section = nil;
7494 bool unseens = false;
7496 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7498 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7499 Package *package = [packages_ objectAtIndex:offset];
7501 BOOL uae = [package upgradableAndEssential:YES];
7505 time_t seen([package seen]);
7507 if (section == nil || last != seen) {
7511 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7514 _profile(ChangesController$reloadData$Allocate)
7515 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7516 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7517 [sections_ addObject:section];
7521 [section addToCount];
7522 } else if ([package ignored]) {
7523 if (ignored == nil) {
7524 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7526 [ignored addToCount];
7529 [upgradable addToCount];
7534 CFRelease(formatter);
7537 Section *last = [sections_ lastObject];
7538 size_t count = [last count];
7539 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7540 [sections_ removeLastObject];
7543 if ([ignored count] != 0)
7544 [sections_ insertObject:ignored atIndex:0];
7546 [sections_ insertObject:upgradable atIndex:0];
7550 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7551 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7552 style:UIBarButtonItemStylePlain
7554 action:@selector(upgradeButtonClicked)
7555 ] autorelease]) animated:YES];
7557 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7558 initWithTitle:UCLocalize("REFRESH")
7559 style:UIBarButtonItemStylePlain
7561 action:@selector(refreshButtonClicked)
7562 ] autorelease]) animated:YES];
7567 - (void) reloadData {
7569 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7574 /* Search Controller {{{ */
7575 @interface SearchController : FilteredPackageListController <
7578 _H<UISearchBar, 1> search_;
7582 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7583 - (void) reloadData;
7587 @implementation SearchController
7589 - (NSURL *) navigationURL {
7590 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7591 return [NSURL URLWithString:@"cydia://search"];
7593 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7596 - (void) useSearch {
7597 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7602 - (void) viewWillAppear:(BOOL)animated {
7603 [super viewWillAppear:animated];
7605 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7609 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7610 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7615 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7616 [search_ resignFirstResponder];
7620 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7621 [search_ setText:@""];
7622 [self searchBarButtonClicked:searchBar];
7625 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7626 [self searchBarButtonClicked:searchBar];
7629 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7630 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7634 - (bool) shouldYield {
7638 - (bool) shouldBlock {
7639 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7642 - (bool) isSummarized {
7643 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7646 - (bool) showsSections {
7650 - (NSMutableArray *) _reloadPackages {
7651 NSMutableArray *packages([super _reloadPackages]);
7652 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7653 [packages radixSortUsingSelector:@selector(rank)];
7657 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7658 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7659 search_ = [[[UISearchBar alloc] init] autorelease];
7660 [search_ setDelegate:self];
7663 [search_ setText:query];
7667 - (void) viewDidAppear:(BOOL)animated {
7668 [super viewDidAppear:animated];
7670 if (!searchloaded_) {
7671 searchloaded_ = YES;
7672 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7673 [search_ layoutSubviews];
7674 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7676 UITextField *textField;
7677 if ([search_ respondsToSelector:@selector(searchField)])
7678 textField = [search_ searchField];
7680 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7682 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7683 [textField setEnablesReturnKeyAutomatically:NO];
7684 [[self navigationItem] setTitleView:textField];
7688 - (void) reloadData {
7689 id object([search_ text]);
7690 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7691 object = [object componentsSeparatedByString:@" "];
7693 [self setObject:object];
7699 - (void) didSelectPackage:(Package *)package {
7700 [search_ resignFirstResponder];
7701 [super didSelectPackage:package];
7706 /* Package Settings Controller {{{ */
7707 @interface PackageSettingsController : CyteViewController <
7708 UITableViewDataSource,
7711 _transient Database *database_;
7713 _H<Package> package_;
7714 _H<UITableView, 2> table_;
7715 _H<UISwitch> subscribedSwitch_;
7716 _H<UISwitch> ignoredSwitch_;
7717 _H<UITableViewCell> subscribedCell_;
7718 _H<UITableViewCell> ignoredCell_;
7721 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7725 @implementation PackageSettingsController
7727 - (NSURL *) navigationURL {
7728 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7731 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7732 if (package_ == nil)
7735 if ([package_ installed] == nil)
7741 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7742 if (package_ == nil)
7745 // both sections contain just one item right now.
7749 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7753 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7755 return UCLocalize("SHOW_ALL_CHANGES_EX");
7757 return UCLocalize("IGNORE_UPGRADES_EX");
7760 - (void) onSubscribed:(id)control {
7761 bool value([control isOn]);
7762 if (package_ == nil)
7764 if ([package_ setSubscribed:value])
7765 [delegate_ updateData];
7768 - (void) _updateIgnored {
7769 const char *package([name_ UTF8String]);
7770 bool on([ignoredSwitch_ isOn]);
7772 pid_t pid(ExecFork());
7774 FILE *dpkg(popen("dpkg --set-selections", "w"));
7775 fwrite(package, strlen(package), 1, dpkg);
7778 fwrite(" hold\n", 6, 1, dpkg);
7780 fwrite(" install\n", 9, 1, dpkg);
7790 int result(waitpid(pid, &status, 0));
7793 _assert(result == pid);
7799 - (void) onIgnored:(id)control {
7800 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7801 [invocation setTarget:self];
7802 [invocation setSelector:@selector(_updateIgnored)];
7804 [delegate_ reloadDataWithInvocation:invocation];
7807 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7808 if (package_ == nil)
7811 switch ([indexPath section]) {
7812 case 0: return subscribedCell_;
7813 case 1: return ignoredCell_;
7822 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7824 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7825 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7826 [(UITableView *) table_ setDataSource:self];
7827 [table_ setDelegate:self];
7828 [[self view] addSubview:table_];
7830 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7831 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7832 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7834 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7835 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7836 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7838 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7839 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7840 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7841 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7843 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7844 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7845 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7846 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7849 - (void) viewDidLoad {
7850 [super viewDidLoad];
7852 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7855 - (void) releaseSubviews {
7857 subscribedCell_ = nil;
7859 ignoredSwitch_ = nil;
7860 subscribedSwitch_ = nil;
7862 [super releaseSubviews];
7865 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7866 if ((self = [super init]) != nil) {
7867 database_ = database;
7872 - (void) reloadData {
7875 package_ = [database_ packageWithName:name_];
7877 if (package_ != nil) {
7878 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7879 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7880 } // XXX: what now, G?
7882 [table_ reloadData];
7888 /* Installed Controller {{{ */
7889 @interface InstalledController : FilteredPackageListController {
7893 - (id) initWithDatabase:(Database *)database;
7895 - (void) updateRoleButton;
7896 - (void) queueStatusDidChange;
7900 @implementation InstalledController
7902 - (NSURL *) navigationURL {
7903 return [NSURL URLWithString:@"cydia://installed"];
7906 - (id) initWithDatabase:(Database *)database {
7907 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7908 [self updateRoleButton];
7909 [self queueStatusDidChange];
7914 - (void) queueButtonClicked {
7919 - (void) queueStatusDidChange {
7923 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7924 initWithTitle:UCLocalize("QUEUE")
7925 style:UIBarButtonItemStyleDone
7927 action:@selector(queueButtonClicked)
7930 [[self navigationItem] setLeftBarButtonItem:nil];
7936 - (void) updateRoleButton {
7937 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7938 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7939 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7940 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7942 action:@selector(roleButtonClicked)
7946 - (void) roleButtonClicked {
7947 [self setObject:[NSNumber numberWithBool:expert_]];
7951 [self updateRoleButton];
7957 /* Source Cell {{{ */
7958 @interface SourceCell : CyteTableViewCell <
7959 CyteTableViewCellDelegate
7962 _H<NSString> origin_;
7963 _H<NSString> label_;
7966 - (void) setSource:(Source *)source;
7970 @implementation SourceCell
7972 - (void) _setImage:(UIImage *)image {
7974 [content_ setNeedsDisplay];
7977 - (void) _setSource:(Source *)source {
7978 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7980 if (NSString *base = [source base])
7981 if ([base length] != 0) {
7982 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
7984 if (NSData *data = [NSURLConnection
7985 sendSynchronousRequest:[NSURLRequest
7987 //cachePolicy:NSURLRequestUseProtocolCachePolicy
7991 returningResponse:NULL
7994 if (UIImage *image = [UIImage imageWithData:data])
7995 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
8001 - (void) setSource:(Source *)source {
8002 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8004 origin_ = [source name];
8005 label_ = [source uri];
8007 [content_ setNeedsDisplay];
8009 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
8012 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8013 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8014 UIView *content([self contentView]);
8015 CGRect bounds([content bounds]);
8017 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8018 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8019 [content_ setBackgroundColor:[UIColor whiteColor]];
8020 [content addSubview:content_];
8022 [content_ setDelegate:self];
8023 [content_ setOpaque:YES];
8027 - (NSString *) accessibilityLabel {
8031 - (void) drawContentRect:(CGRect)rect {
8032 bool highlighted(highlighted_);
8033 float width(rect.size.width);
8036 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8043 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8047 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8052 /* Source Controller {{{ */
8053 @interface SourceController : FilteredPackageListController {
8054 _transient Source *source_;
8058 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8062 @implementation SourceController
8064 - (NSURL *) navigationURL {
8065 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8068 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8069 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8071 key_ = [source key];
8075 - (void) reloadData {
8076 source_ = [database_ sourceWithKey:key_];
8077 key_ = [source_ key];
8078 [self setObject:source_];
8080 [[self navigationItem] setTitle:[source_ label]];
8087 /* Sources Controller {{{ */
8088 @interface SourcesController : CyteViewController <
8089 UITableViewDataSource,
8092 _transient Database *database_;
8093 _H<UITableView, 2> list_;
8094 _H<NSMutableArray> sources_;
8098 _H<UIProgressHUD> hud_;
8101 //NSURLConnection *installer_;
8102 NSURLConnection *trivial_;
8103 NSURLConnection *trivial_bz2_;
8104 NSURLConnection *trivial_gz_;
8105 //NSURLConnection *automatic_;
8110 - (id) initWithDatabase:(Database *)database;
8111 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8115 @implementation SourcesController
8117 - (void) _releaseConnection:(NSURLConnection *)connection {
8118 if (connection != nil) {
8119 [connection cancel];
8120 //[connection setDelegate:nil];
8121 [connection release];
8126 //[self _releaseConnection:installer_];
8127 [self _releaseConnection:trivial_];
8128 [self _releaseConnection:trivial_gz_];
8129 [self _releaseConnection:trivial_bz2_];
8130 //[self _releaseConnection:automatic_];
8135 - (NSURL *) navigationURL {
8136 return [NSURL URLWithString:@"cydia://sources"];
8139 - (void) viewDidAppear:(BOOL)animated {
8140 [super viewDidAppear:animated];
8141 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8144 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8145 return offset_ == 0 ? 1 : 2;
8148 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8149 switch (section + (offset_ == 0 ? 1 : 0)) {
8150 case 0: return UCLocalize("ENTERED_BY_USER");
8151 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8157 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8158 int count = [sources_ count];
8160 case 0: return (offset_ == 0 ? count : offset_);
8161 case 1: return count - offset_;
8167 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8169 switch (indexPath.section) {
8170 case 0: idx = indexPath.row; break;
8171 case 1: idx = indexPath.row + offset_; break;
8175 return [sources_ objectAtIndex:idx];
8178 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8179 static NSString *cellIdentifier = @"SourceCell";
8181 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8182 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8183 [cell setSource:[self sourceAtIndexPath:indexPath]];
8184 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8189 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8190 Source *source = [self sourceAtIndexPath:indexPath];
8192 SourceController *controller = [[[SourceController alloc]
8193 initWithDatabase:database_
8197 [controller setDelegate:delegate_];
8199 [[self navigationController] pushViewController:controller animated:YES];
8202 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8203 Source *source = [self sourceAtIndexPath:indexPath];
8204 return [source record] != nil;
8207 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8208 if (editingStyle == UITableViewCellEditingStyleDelete) {
8209 Source *source = [self sourceAtIndexPath:indexPath];
8210 [Sources_ removeObjectForKey:[source key]];
8211 [delegate_ syncData];
8216 [delegate_ addTrivialSource:href_];
8217 [delegate_ syncData];
8220 - (NSString *) getWarning {
8221 NSString *href(href_);
8222 NSRange colon([href rangeOfString:@"://"]);
8223 if (colon.location != NSNotFound)
8224 href = [href substringFromIndex:(colon.location + 3)];
8225 href = [href stringByAddingPercentEscapes];
8226 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8227 href = [href stringByCachingURLWithCurrentCDN];
8229 NSURL *url([NSURL URLWithString:href]);
8231 NSStringEncoding encoding;
8232 NSError *error(nil);
8234 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8235 return [warning length] == 0 ? nil : warning;
8239 - (void) _endConnection:(NSURLConnection *)connection {
8240 // XXX: the memory management in this method is horribly awkward
8242 NSURLConnection **field = NULL;
8243 if (connection == trivial_)
8245 else if (connection == trivial_bz2_)
8246 field = &trivial_bz2_;
8247 else if (connection == trivial_gz_)
8248 field = &trivial_gz_;
8249 _assert(field != NULL);
8250 [connection release];
8255 trivial_bz2_ == nil &&
8258 [delegate_ releaseNetworkActivityIndicator];
8260 [delegate_ removeProgressHUD:hud_];
8266 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8269 UIAlertView *alert = [[[UIAlertView alloc]
8270 initWithTitle:UCLocalize("SOURCE_WARNING")
8273 cancelButtonTitle:UCLocalize("CANCEL")
8275 UCLocalize("ADD_ANYWAY"),
8279 [alert setContext:@"warning"];
8280 [alert setNumberOfRows:1];
8284 } else if (error_ != nil) {
8285 UIAlertView *alert = [[[UIAlertView alloc]
8286 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8287 message:[error_ localizedDescription]
8289 cancelButtonTitle:UCLocalize("OK")
8290 otherButtonTitles:nil
8293 [alert setContext:@"urlerror"];
8296 UIAlertView *alert = [[[UIAlertView alloc]
8297 initWithTitle:UCLocalize("NOT_REPOSITORY")
8298 message:UCLocalize("NOT_REPOSITORY_EX")
8300 cancelButtonTitle:UCLocalize("OK")
8301 otherButtonTitles:nil
8304 [alert setContext:@"trivial"];
8313 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8314 switch ([response statusCode]) {
8320 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8321 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8323 [self _endConnection:connection];
8326 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8327 [self _endConnection:connection];
8330 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8331 NSURL *url([NSURL URLWithString:href]);
8333 NSMutableURLRequest *request = [NSMutableURLRequest
8335 cachePolicy:NSURLRequestUseProtocolCachePolicy
8336 timeoutInterval:120.0
8339 [request setHTTPMethod:method];
8341 if (Machine_ != NULL)
8342 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8344 if ([url isCydiaSecure]) {
8345 if (UniqueID_ != nil)
8346 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8349 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8352 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8353 NSString *context([alert context]);
8355 if ([context isEqualToString:@"source"]) {
8358 NSString *href = [[alert textField] text];
8360 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8362 if (![href hasSuffix:@"/"])
8363 href_ = [href stringByAppendingString:@"/"];
8367 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8368 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8369 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8370 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8374 // XXX: this is stupid
8375 hud_ = [delegate_ addProgressHUD];
8376 [hud_ setText:UCLocalize("VERIFYING_URL")];
8377 [delegate_ retainNetworkActivityIndicator];
8386 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8387 } else if ([context isEqualToString:@"trivial"])
8388 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8389 else if ([context isEqualToString:@"urlerror"])
8390 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8391 else if ([context isEqualToString:@"warning"]) {
8405 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8410 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8412 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8413 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8414 [list_ setRowHeight:56];
8415 [(UITableView *) list_ setDataSource:self];
8416 [list_ setDelegate:self];
8417 [[self view] addSubview:list_];
8420 - (void) viewDidLoad {
8421 [super viewDidLoad];
8423 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8424 [self updateButtonsForEditingStatus:NO animated:NO];
8427 - (void) releaseSubviews {
8430 [super releaseSubviews];
8433 - (id) initWithDatabase:(Database *)database {
8434 if ((self = [super init]) != nil) {
8435 database_ = database;
8436 sources_ = [NSMutableArray arrayWithCapacity:16];
8440 - (void) reloadData {
8444 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8447 [sources_ removeAllObjects];
8448 [sources_ addObjectsFromArray:[database_ sources]];
8450 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8453 int count([sources_ count]);
8455 for (int i = 0; i != count; i++) {
8456 if ([[sources_ objectAtIndex:i] record] == nil)
8461 [list_ setEditing:NO];
8462 [self updateButtonsForEditingStatus:NO animated:NO];
8466 - (void) showAddSourcePrompt {
8467 UIAlertView *alert = [[[UIAlertView alloc]
8468 initWithTitle:UCLocalize("ENTER_APT_URL")
8471 cancelButtonTitle:UCLocalize("CANCEL")
8473 UCLocalize("ADD_SOURCE"),
8477 [alert setContext:@"source"];
8479 [alert setNumberOfRows:1];
8480 [alert addTextFieldWithValue:@"http://" label:@""];
8482 UITextInputTraits *traits = [[alert textField] textInputTraits];
8483 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8484 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8485 [traits setKeyboardType:UIKeyboardTypeURL];
8486 // XXX: UIReturnKeyDone
8487 [traits setReturnKeyType:UIReturnKeyNext];
8492 - (void) addButtonClicked {
8493 [self showAddSourcePrompt];
8496 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8497 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8498 initWithTitle:UCLocalize("ADD")
8499 style:UIBarButtonItemStylePlain
8501 action:@selector(addButtonClicked)
8502 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8504 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8505 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8506 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8508 action:@selector(editButtonClicked)
8509 ] autorelease] animated:animated];
8511 if (IsWildcat_ && !editing)
8512 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8513 initWithTitle:UCLocalize("SETTINGS")
8514 style:UIBarButtonItemStylePlain
8516 action:@selector(settingsButtonClicked)
8520 - (void) settingsButtonClicked {
8521 [delegate_ showSettings];
8524 - (void) editButtonClicked {
8525 [list_ setEditing:![list_ isEditing] animated:YES];
8527 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8533 /* Settings Controller {{{ */
8534 @interface SettingsController : CyteViewController <
8535 UITableViewDataSource,
8538 _transient Database *database_;
8539 // XXX: ok, "roledelegate_"?...
8540 _transient id roledelegate_;
8541 _H<UITableView, 2> table_;
8542 _H<UISegmentedControl> segment_;
8543 _H<UIView> container_;
8546 - (void) showDoneButton;
8547 - (void) resizeSegmentedControl;
8551 @implementation SettingsController
8554 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8556 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8557 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8558 [table_ setDelegate:self];
8559 [(UITableView *) table_ setDataSource:self];
8560 [[self view] addSubview:table_];
8562 NSArray *items = [NSArray arrayWithObjects:
8564 UCLocalize("HACKER"),
8565 UCLocalize("DEVELOPER"),
8567 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8568 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8569 [container_ addSubview:segment_];
8572 - (void) viewDidLoad {
8573 [super viewDidLoad];
8575 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8578 if ([Role_ isEqualToString:@"User"]) index = 0;
8579 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8580 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8582 [segment_ setSelectedSegmentIndex:index];
8583 [self showDoneButton];
8586 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8587 [self resizeSegmentedControl];
8590 - (void) releaseSubviews {
8595 [super releaseSubviews];
8598 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8599 if ((self = [super init]) != nil) {
8600 database_ = database;
8601 roledelegate_ = delegate;
8605 - (void) resizeSegmentedControl {
8606 CGFloat width = [[self view] frame].size.width;
8607 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8610 - (void) viewWillAppear:(BOOL)animated {
8611 [super viewWillAppear:animated];
8613 [self resizeSegmentedControl];
8616 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8617 [self resizeSegmentedControl];
8620 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8621 [self resizeSegmentedControl];
8625 NSString *role(nil);
8627 switch ([segment_ selectedSegmentIndex]) {
8628 case 0: role = @"User"; break;
8629 case 1: role = @"Hacker"; break;
8630 case 2: role = @"Developer"; break;
8635 if (![role isEqualToString:Role_]) {
8636 bool rolling(Role_ == nil);
8639 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8643 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8647 [roledelegate_ loadData];
8649 [roledelegate_ updateData];
8653 - (void) segmentChanged:(UISegmentedControl *)control {
8654 [self showDoneButton];
8657 - (void) saveAndClose {
8660 [[self navigationItem] setRightBarButtonItem:nil];
8661 [[self navigationController] dismissModalViewControllerAnimated:YES];
8664 - (void) doneButtonClicked {
8665 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8666 [spinner startAnimating];
8667 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8668 [[self navigationItem] setRightBarButtonItem:spinItem];
8670 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8673 - (void) showDoneButton {
8674 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8675 initWithTitle:UCLocalize("DONE")
8676 style:UIBarButtonItemStyleDone
8678 action:@selector(doneButtonClicked)
8679 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8682 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8683 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8687 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8691 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8692 return nil; // This method is required by the protocol.
8695 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8697 return UCLocalize("ROLE_EX");
8699 return [NSString stringWithFormat:
8700 @"%@: %@\n%@: %@\n%@: %@",
8701 UCLocalize("USER"), UCLocalize("USER_EX"),
8702 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8703 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8708 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8709 return section == 3 ? 44.0f : 0;
8712 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8713 return section == 3 ? container_ : nil;
8716 - (void) reloadData {
8719 [table_ reloadData];
8724 /* Stash Controller {{{ */
8725 @interface StashController : CyteViewController {
8726 _H<UIActivityIndicatorView> spinner_;
8727 _H<UILabel> status_;
8728 _H<UILabel> caption_;
8733 @implementation StashController
8736 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8737 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8739 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8740 CGRect spinrect = [spinner_ frame];
8741 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8742 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8743 [spinner_ setFrame:spinrect];
8744 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8745 [[self view] addSubview:spinner_];
8746 [spinner_ startAnimating];
8749 captrect.size.width = [[self view] frame].size.width;
8750 captrect.size.height = 40.0f;
8751 captrect.origin.x = 0;
8752 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8753 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8754 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8755 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8756 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8757 [caption_ setTextColor:[UIColor whiteColor]];
8758 [caption_ setBackgroundColor:[UIColor clearColor]];
8759 [caption_ setShadowColor:[UIColor blackColor]];
8760 [caption_ setTextAlignment:UITextAlignmentCenter];
8761 [[self view] addSubview:caption_];
8764 statusrect.size.width = [[self view] frame].size.width;
8765 statusrect.size.height = 30.0f;
8766 statusrect.origin.x = 0;
8767 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8768 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8769 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8770 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8771 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8772 [status_ setTextColor:[UIColor whiteColor]];
8773 [status_ setBackgroundColor:[UIColor clearColor]];
8774 [status_ setShadowColor:[UIColor blackColor]];
8775 [status_ setTextAlignment:UITextAlignmentCenter];
8776 [[self view] addSubview:status_];
8779 - (void) releaseSubviews {
8784 [super releaseSubviews];
8790 @interface CYURLCache : SDURLCache {
8795 @implementation CYURLCache
8797 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8800 else if ([event isEqualToString:@"no-cache"])
8802 else if ([event isEqualToString:@"store"])
8804 else if ([event isEqualToString:@"invalid"])
8806 else if ([event isEqualToString:@"memory"])
8808 else if ([event isEqualToString:@"disk"])
8810 else if ([event isEqualToString:@"miss"])
8813 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8817 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8818 if (NSURLResponse *response = [cached response])
8819 if (NSString *mime = [response MIMEType])
8820 if ([mime isEqualToString:@"text/cache-manifest"]) {
8821 NSURL *url([response URL]);
8824 NSLog(@"###: %@", [url absoluteString]);
8827 @synchronized (HostConfig_) {
8828 [CachedURLs_ addObject:url];
8832 [super storeCachedResponse:cached forRequest:request];
8837 @interface Cydia : UIApplication <
8838 ConfirmationControllerDelegate,
8841 UINavigationControllerDelegate,
8842 UITabBarControllerDelegate
8844 _H<UIWindow> window_;
8845 _H<CYTabBarController> tabbar_;
8846 _H<CydiaLoadingViewController> emulated_;
8848 _H<NSMutableArray> essential_;
8849 _H<NSMutableArray> broken_;
8851 Database *database_;
8853 _H<NSURL> starturl_;
8858 _H<StashController> stash_;
8867 @implementation Cydia
8869 - (void) beginUpdate {
8870 [tabbar_ beginUpdate];
8874 return [tabbar_ updating];
8878 if ([broken_ count] != 0) {
8879 int count = [broken_ count];
8881 UIAlertView *alert = [[[UIAlertView alloc]
8882 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8883 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8885 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8887 UCLocalize("TEMPORARY_IGNORE"),
8891 [alert setContext:@"fixhalf"];
8892 [alert setNumberOfRows:2];
8894 } else if (!Ignored_ && [essential_ count] != 0) {
8895 int count = [essential_ count];
8897 UIAlertView *alert = [[[UIAlertView alloc]
8898 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8899 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8901 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8903 UCLocalize("UPGRADE_ESSENTIAL"),
8904 UCLocalize("COMPLETE_UPGRADE"),
8908 [alert setContext:@"upgrade"];
8913 - (void) returnToCydia {
8917 - (void) _saveConfig {
8923 NSString *error(nil);
8925 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8927 NSError *error(nil);
8928 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8929 NSLog(@"failure to save metadata data: %@", error);
8934 NSLog(@"failure to serialize metadata: %@", error);
8941 // Navigation controller for the queuing badge.
8942 - (UINavigationController *) queueNavigationController {
8943 NSArray *controllers = [tabbar_ viewControllers];
8944 return [controllers objectAtIndex:3];
8947 - (void) unloadData {
8948 [tabbar_ unloadData];
8951 - (void) _updateData {
8955 UINavigationController *navigation = [self queueNavigationController];
8957 id queuedelegate = nil;
8958 if ([[navigation viewControllers] count] > 0)
8959 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8961 [queuedelegate queueStatusDidChange];
8962 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8965 - (void) _refreshIfPossible:(NSDate *)update {
8966 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8968 bool recently = false;
8969 if (update != nil) {
8970 NSTimeInterval interval([update timeIntervalSinceNow]);
8971 if (interval <= 0 && interval > -(15*60))
8975 // Don't automatic refresh if:
8976 // - We already refreshed recently.
8977 // - We already auto-refreshed this launch.
8978 // - Auto-refresh is disabled.
8979 if (recently || loaded_ || ManualRefresh) {
8980 // If we are cancelling, we need to make sure it knows it's already loaded.
8983 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8985 // We are going to load, so remember that.
8988 SCNetworkReachabilityFlags flags; {
8989 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8990 SCNetworkReachabilityGetFlags(reachability, &flags);
8991 CFRelease(reachability);
8994 // XXX: this elaborate mess is what Apple is using to determine this? :(
8995 // XXX: do we care if the user has to intervene? maybe that's ok?
8997 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8998 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8999 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9000 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9001 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9002 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9006 // If we can reach the server, auto-refresh!
9008 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9014 - (void) refreshIfPossible {
9015 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9018 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9019 @synchronized (self) {
9020 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9021 [hud setText:UCLocalize("RELOADING_DATA")];
9023 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9026 [self removeProgressHUD:hud];
9030 [essential_ removeAllObjects];
9031 [broken_ removeAllObjects];
9033 NSArray *packages([database_ packages]);
9034 for (Package *package in packages) {
9036 [broken_ addObject:package];
9037 if ([package upgradableAndEssential:NO]) {
9038 if ([package essential])
9039 [essential_ addObject:package];
9044 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9047 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9048 [changesItem setBadgeValue:badge];
9049 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9050 [self setApplicationIconBadgeNumber:changes];
9053 [changesItem setBadgeValue:nil];
9054 [changesItem setAnimatedBadge:NO];
9055 [self setApplicationIconBadgeNumber:0];
9061 - (void) updateData {
9067 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9070 - (void) disemulate {
9071 if (emulated_ == nil)
9074 [window_ addSubview:[tabbar_ view]];
9075 [[emulated_ view] removeFromSuperview];
9077 [window_ setUserInteractionEnabled:YES];
9080 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9081 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9083 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9085 UIViewController *parent;
9086 if (emulated_ == nil)
9095 [parent presentModalViewController:navigation animated:YES];
9098 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9099 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9101 if (navigation != nil)
9102 [navigation pushViewController:progress animated:YES];
9104 [self presentModalViewController:progress force:YES];
9106 [progress invoke:invocation withTitle:title];
9110 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9111 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9114 - (void) repairWithInvocation:(NSInvocation *)invocation {
9116 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9120 - (void) repairWithSelector:(SEL)selector {
9121 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9124 - (void) reloadData {
9125 [self reloadDataWithInvocation:nil];
9126 if ([database_ progressDelegate] == nil)
9132 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9135 - (void) addSource:(NSDictionary *) source {
9139 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9140 AddSource(href, distribution, sections);
9143 - (void) addTrivialSource:(NSString *)href {
9144 AddSource(href, @"./");
9147 - (void) updateValues {
9152 pkgProblemResolver *resolver = [database_ resolver];
9154 resolver->InstallProtect();
9155 if (!resolver->Resolve(true))
9160 // XXX: this is a really crappy way of doing this.
9161 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9162 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9163 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9164 if ([tabbar_ updating])
9165 [tabbar_ cancelUpdate];
9167 if (![database_ prepare])
9170 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9171 [page setDelegate:self];
9172 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9175 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9176 [tabbar_ presentModalViewController:confirm_ animated:YES];
9182 @synchronized (self) {
9187 - (void) clearPackage:(Package *)package {
9188 @synchronized (self) {
9195 - (void) installPackages:(NSArray *)packages {
9196 @synchronized (self) {
9197 for (Package *package in packages)
9204 - (void) installPackage:(Package *)package {
9205 @synchronized (self) {
9212 - (void) removePackage:(Package *)package {
9213 @synchronized (self) {
9220 - (void) distUpgrade {
9221 @synchronized (self) {
9222 if (![database_ upgrade])
9229 [database_ perform];
9230 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9233 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9236 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9238 [self refreshIfPossible];
9241 - (void) showSettings {
9242 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9245 - (void) retainNetworkActivityIndicator {
9246 if (activity_++ == 0)
9247 [self setNetworkActivityIndicatorVisible:YES];
9250 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9254 - (void) releaseNetworkActivityIndicator {
9255 if (--activity_ == 0)
9256 [self setNetworkActivityIndicatorVisible:NO];
9259 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9264 - (void) cancelAndClear:(bool)clear {
9265 @synchronized (self) {
9277 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9278 NSString *context([alert context]);
9280 if ([context isEqualToString:@"conffile"]) {
9281 FILE *input = [database_ input];
9282 if (button == [alert cancelButtonIndex])
9283 fprintf(input, "N\n");
9284 else if (button == [alert firstOtherButtonIndex])
9285 fprintf(input, "Y\n");
9288 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9289 } else if ([context isEqualToString:@"fixhalf"]) {
9290 if (button == [alert cancelButtonIndex]) {
9291 @synchronized (self) {
9292 for (Package *broken in (id) broken_) {
9295 NSString *id = [broken id];
9296 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9297 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9298 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9299 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9305 } else if (button == [alert firstOtherButtonIndex]) {
9306 [broken_ removeAllObjects];
9310 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9311 } else if ([context isEqualToString:@"upgrade"]) {
9312 if (button == [alert firstOtherButtonIndex]) {
9313 @synchronized (self) {
9314 for (Package *essential in (id) essential_)
9315 [essential install];
9320 } else if (button == [alert firstOtherButtonIndex] + 1) {
9322 } else if (button == [alert cancelButtonIndex]) {
9326 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9330 - (void) system:(NSString *)command {
9331 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9334 system([command UTF8String]);
9340 - (void) applicationWillSuspend {
9342 [super applicationWillSuspend];
9345 - (BOOL) isSafeToSuspend {
9348 NSLog(@"isSafeToSuspend: locked_ != 0");
9353 // Use external process status API internally.
9354 // This is probably a really bad idea.
9355 // XXX: what is the point of this? does this solve anything at all?
9356 uint64_t status = 0;
9358 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9359 notify_get_state(notify_token, &status);
9360 notify_cancel(notify_token);
9365 NSLog(@"isSafeToSuspend: status != 0");
9371 NSLog(@"isSafeToSuspend: -> true");
9376 - (void) applicationSuspend:(__GSEvent *)event {
9377 if ([self isSafeToSuspend])
9378 [super applicationSuspend:event];
9381 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9382 if ([self isSafeToSuspend])
9383 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9386 - (void) _setSuspended:(BOOL)value {
9387 if ([self isSafeToSuspend])
9388 [super _setSuspended:value];
9391 - (UIProgressHUD *) addProgressHUD {
9392 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9393 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9395 [window_ setUserInteractionEnabled:NO];
9397 UIViewController *target(tabbar_);
9398 if (UIViewController *modal = [target modalViewController])
9401 UIView *view([target view]);
9402 [view addSubview:hud];
9404 [hud showInView:[tabbar_ view]];
9410 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9413 [hud removeFromSuperview];
9414 [window_ setUserInteractionEnabled:YES];
9417 - (CyteViewController *) pageForPackage:(NSString *)name {
9418 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9421 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9422 NSString *scheme([[url scheme] lowercaseString]);
9423 if ([[url absoluteString] length] <= [scheme length] + 3)
9425 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9426 NSArray *components([path pathComponents]);
9428 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9429 return [self pageForPackage:[components objectAtIndex:1]];
9431 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9434 NSString *base([components objectAtIndex:0]);
9436 CyteViewController *controller = nil;
9438 if ([base isEqualToString:@"url"]) {
9439 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9440 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9441 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9442 } else if (!external && [components count] == 1) {
9443 if ([base isEqualToString:@"manage"]) {
9444 controller = [[[ManageController alloc] init] autorelease];
9447 if ([base isEqualToString:@"sources"]) {
9448 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9451 if ([base isEqualToString:@"home"]) {
9452 controller = [[[HomeController alloc] init] autorelease];
9455 if ([base isEqualToString:@"sections"]) {
9456 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9459 if ([base isEqualToString:@"search"]) {
9460 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9463 if ([base isEqualToString:@"changes"]) {
9464 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9467 if ([base isEqualToString:@"installed"]) {
9468 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9470 } else if ([components count] == 2) {
9471 NSString *argument = [components objectAtIndex:1];
9473 if ([base isEqualToString:@"package"]) {
9474 controller = [self pageForPackage:argument];
9477 if (!external && [base isEqualToString:@"search"]) {
9478 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9481 if (!external && [base isEqualToString:@"sections"]) {
9482 if ([argument isEqualToString:@"all"])
9484 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9487 if (!external && [base isEqualToString:@"sources"]) {
9488 if ([argument isEqualToString:@"add"]) {
9489 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9490 [(SourcesController *)controller showAddSourcePrompt];
9492 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9493 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9497 if (!external && [base isEqualToString:@"launch"]) {
9498 [self launchApplicationWithIdentifier:argument suspended:NO];
9501 } else if (!external && [components count] == 3) {
9502 NSString *arg1 = [components objectAtIndex:1];
9503 NSString *arg2 = [components objectAtIndex:2];
9505 if ([base isEqualToString:@"package"]) {
9506 if ([arg2 isEqualToString:@"settings"]) {
9507 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9508 } else if ([arg2 isEqualToString:@"files"]) {
9509 if (Package *package = [database_ packageWithName:arg1]) {
9510 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9511 [(FileTable *)controller setPackage:package];
9517 [controller setDelegate:self];
9521 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9522 CyteViewController *page([self pageForURL:url forExternal:external]);
9525 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9526 [nav setViewControllers:[NSArray arrayWithObject:page]];
9527 [tabbar_ setUnselectedViewController:nav];
9533 - (void) applicationOpenURL:(NSURL *)url {
9534 [super applicationOpenURL:url];
9539 [self openCydiaURL:url forExternal:YES];
9542 - (void) applicationWillResignActive:(UIApplication *)application {
9543 // Stop refreshing if you get a phone call or lock the device.
9544 if ([tabbar_ updating])
9545 [tabbar_ cancelUpdate];
9547 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9548 [super applicationWillResignActive:application];
9551 - (void) saveState {
9552 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9553 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9554 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9560 - (void) applicationWillTerminate:(UIApplication *)application {
9564 - (void) setConfigurationData:(NSString *)data {
9565 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9567 if (!conffile_r(data)) {
9568 lprintf("E:invalid conffile\n");
9572 NSString *ofile = conffile_r[1];
9573 //NSString *nfile = conffile_r[2];
9575 UIAlertView *alert = [[[UIAlertView alloc]
9576 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9577 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9579 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9581 UCLocalize("ACCEPT_NEW_COPY"),
9582 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9586 [alert setContext:@"conffile"];
9587 [alert setNumberOfRows:2];
9591 - (void) addStashController {
9593 stash_ = [[[StashController alloc] init] autorelease];
9594 [window_ addSubview:[stash_ view]];
9597 - (void) removeStashController {
9598 [[stash_ view] removeFromSuperview];
9604 [self setIdleTimerDisabled:YES];
9606 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9607 UpdateExternalStatus(1);
9608 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9609 UpdateExternalStatus(0);
9611 [self removeStashController];
9613 if (ExecFork() == 0) {
9614 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9615 perror("launchctl stop");
9619 - (void) setupViewControllers {
9620 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9622 NSMutableArray *items([NSMutableArray arrayWithObjects:
9623 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9624 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9625 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9626 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9630 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9631 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9633 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9636 NSMutableArray *controllers([NSMutableArray array]);
9637 for (UITabBarItem *item in items) {
9638 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9639 [controller setTabBarItem:item];
9640 [controllers addObject:controller];
9642 [tabbar_ setViewControllers:controllers];
9644 [tabbar_ setUpdateDelegate:self];
9647 - (void) _sendMemoryWarningNotification {
9648 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9651 - (void) _sendMemoryWarningNotifications {
9653 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9658 - (void) applicationDidFinishLaunching:(id)unused {
9659 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9662 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9663 [self setApplicationSupportsShakeToEdit:NO];
9665 @synchronized (HostConfig_) {
9666 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9669 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9670 initWithMemoryCapacity:524288
9671 diskCapacity:10485760
9672 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9675 [CydiaWebViewController _initialize];
9677 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9679 // this would disallow http{,s} URLs from accessing this data
9680 //[WebView registerURLSchemeAsLocal:@"cydia"];
9682 Font12_ = [UIFont systemFontOfSize:12];
9683 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9684 Font14_ = [UIFont systemFontOfSize:14];
9685 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9686 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9688 essential_ = [NSMutableArray arrayWithCapacity:4];
9689 broken_ = [NSMutableArray arrayWithCapacity:4];
9691 // XXX: I really need this thing... like, seriously... I'm sorry
9692 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9694 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9695 [window_ orderFront:self];
9696 [window_ makeKey:self];
9697 [window_ setHidden:NO];
9700 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9701 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9702 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9703 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9704 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9705 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9706 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9707 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9708 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9711 [self addStashController];
9712 // XXX: this would be much cleaner as a yieldToSelector:
9713 // that way the removeStashController could happen right here inline
9714 // we also could no longer require the useless stash_ field anymore
9715 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9719 database_ = [Database sharedInstance];
9720 [database_ setDelegate:self];
9722 [window_ setUserInteractionEnabled:NO];
9723 [self setupViewControllers];
9725 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9726 [window_ addSubview:[emulated_ view]];
9728 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9732 - (NSArray *) defaultStartPages {
9733 NSMutableArray *standard = [NSMutableArray array];
9734 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9735 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9736 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9738 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9740 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9741 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9743 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9750 [window_ setUserInteractionEnabled:YES];
9751 [self showSettings];
9754 if ([emulated_ modalViewController] != nil)
9755 [emulated_ dismissModalViewControllerAnimated:YES];
9756 [window_ setUserInteractionEnabled:NO];
9759 [self reloadDataWithInvocation:nil];
9760 [self refreshIfPossible];
9765 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9766 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9767 int standardIndex = 0;
9768 NSArray *standard = [self defaultStartPages];
9775 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9776 if (valid && closed != nil) {
9777 NSTimeInterval interval([closed timeIntervalSinceNow]);
9778 // XXX: Is 15 minutes the optimal time here?
9779 if (interval > 0 && interval <= -(15*60))
9783 if (valid && [saved count] != [standard count])
9787 for (unsigned int i = 0; i < [standard count]; i++) {
9788 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9789 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9790 // but it's good enough for now.
9791 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9798 NSArray *items = nil;
9800 [tabbar_ setSelectedIndex:savedIndex];
9803 [tabbar_ setSelectedIndex:standardIndex];
9807 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9808 NSArray *stack = [items objectAtIndex:tab];
9809 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9810 NSMutableArray *current = [NSMutableArray array];
9812 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9813 NSString *addr = [stack objectAtIndex:nav];
9814 NSURL *url = [NSURL URLWithString:addr];
9815 CyteViewController *page = [self pageForURL:url forExternal:NO];
9817 [current addObject:page];
9820 [navigation setViewControllers:current];
9823 // (Try to) show the startup URL.
9824 if (starturl_ != nil) {
9825 [self openCydiaURL:starturl_ forExternal:NO];
9830 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9831 if (item != nil && IsWildcat_) {
9832 [sheet showFromBarButtonItem:item animated:YES];
9834 [sheet showInView:window_];
9838 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9839 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9840 [progress setTitle:task];
9841 [progress addProgressEvent:event];
9844 - (void) addProgressEventForTask:(NSArray *)data {
9845 CydiaProgressEvent *event([data objectAtIndex:0]);
9846 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9847 [self addProgressEvent:event forTask:task];
9850 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9851 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9857 id Alloc_(id self, SEL selector) {
9858 id object = alloc_(self, selector);
9859 lprintf("[%s]A-%p\n", self->isa->name, object);
9864 id Dealloc_(id self, SEL selector) {
9865 id object = dealloc_(self, selector);
9866 lprintf("[%s]D-%p\n", self->isa->name, object);
9870 Class $WebDefaultUIKitDelegate;
9872 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9873 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9874 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9875 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9878 static NSSet *MobilizedFiles_;
9880 static NSURL *MobilizeURL(NSURL *url) {
9881 NSString *path([url path]);
9882 if ([path hasPrefix:@"/var/root/"]) {
9883 NSString *file([path substringFromIndex:10]);
9884 if ([MobilizedFiles_ containsObject:file])
9885 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9891 Class $CFXPreferencesPropertyListSource;
9892 @class CFXPreferencesPropertyListSource;
9894 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9895 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9896 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9897 url = MobilizeURL(url);
9898 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9899 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9905 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9906 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9907 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9908 url = MobilizeURL(url);
9909 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9910 //NSLog(@"%@ %@", [url absoluteString], value);
9916 Class $NSURLConnection;
9918 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9919 NSMutableURLRequest *copy([request mutableCopy]);
9921 NSURL *url([copy URL]);
9923 NSString *href([url absoluteString]);
9924 NSString *host([url host]);
9925 NSString *scheme([[url scheme] lowercaseString]);
9927 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9929 @synchronized (HostConfig_) {
9930 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9931 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9932 [copy setHTTPShouldUsePipelining:YES];
9934 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9935 if ([control isEqualToString:@"max-age=0"])
9936 if ([CachedURLs_ containsObject:href]) {
9938 NSLog(@"~~~: %@", href);
9941 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9943 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9944 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9945 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9949 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9953 int main(int argc, char *argv[]) {
9954 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9958 UpdateExternalStatus(0);
9960 if (Class $UIDevice = objc_getClass("UIDevice")) {
9961 UIDevice *device([$UIDevice currentDevice]);
9962 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9966 UIScreen *screen([UIScreen mainScreen]);
9967 if ([screen respondsToSelector:@selector(scale)])
9968 ScreenScale_ = [screen scale];
9972 UIDevice *device([UIDevice currentDevice]);
9973 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9976 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9977 if (idiom == UIUserInterfaceIdiomPhone)
9979 else if (idiom == UIUserInterfaceIdiomPad)
9982 NSLog(@"unknown UIUserInterfaceIdiom!");
9985 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9987 HostConfig_ = [[[NSObject alloc] init] autorelease];
9988 @synchronized (HostConfig_) {
9989 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9990 TokenHosts_ = [NSMutableSet setWithCapacity:4];
9991 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9992 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9993 CachedURLs_ = [NSMutableSet setWithCapacity:32];
9996 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9998 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10000 MobilizedFiles_ = [NSMutableSet setWithObjects:
10001 @"Library/Preferences/com.apple.Accessibility.plist",
10002 @"Library/Preferences/com.apple.preferences.sounds.plist",
10005 /* Library Hacks {{{ */
10006 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10008 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10010 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10011 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10012 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10013 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10016 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10017 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10018 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10019 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10022 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10023 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10024 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10025 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10026 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10029 $NSURLConnection = objc_getClass("NSURLConnection");
10030 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10031 if (NSURLConnection$init$ != NULL) {
10032 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10033 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10036 /* Set Locale {{{ */
10037 Locale_ = CFLocaleCopyCurrent();
10038 Languages_ = [NSLocale preferredLanguages];
10040 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10041 //NSLog(@"%@", [Languages_ description]);
10044 if (Locale_ != NULL)
10045 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10046 else if (Languages_ != nil && [Languages_ count] != 0)
10047 lang = [[Languages_ objectAtIndex:0] UTF8String];
10049 // XXX: consider just setting to C and then falling through?
10052 if (lang != NULL) {
10053 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10054 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10057 NSLog(@"Setting Language: %s", lang);
10059 if (lang != NULL) {
10060 setenv("LANG", lang, true);
10061 std::setlocale(LC_ALL, lang);
10065 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10067 /* Parse Arguments {{{ */
10068 bool substrate(false);
10074 for (int argi(1); argi != argc; ++argi)
10075 if (strcmp(argv[argi], "--") == 0) {
10077 argv[argi] = argv[0];
10083 for (int argi(1); argi != arge; ++argi)
10084 if (strcmp(args[argi], "--substrate") == 0)
10087 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10091 App_ = [[NSBundle mainBundle] bundlePath];
10097 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10098 alloc_ = alloc->method_imp;
10099 alloc->method_imp = (IMP) &Alloc_;*/
10101 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10102 dealloc_ = dealloc->method_imp;
10103 dealloc->method_imp = (IMP) &Dealloc_;*/
10105 /* System Information {{{ */
10109 size = sizeof(maxproc);
10110 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10111 perror("sysctlbyname(\"kern.maxproc\", ?)");
10112 else if (maxproc < 64) {
10114 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10115 perror("sysctlbyname(\"kern.maxproc\", #)");
10118 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10119 char *osversion = new char[size];
10120 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10121 perror("sysctlbyname(\"kern.osversion\", ?)");
10123 System_ = [NSString stringWithUTF8String:osversion];
10125 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10126 char *machine = new char[size];
10127 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10128 perror("sysctlbyname(\"hw.machine\", ?)");
10130 Machine_ = machine;
10132 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10133 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10134 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10136 UniqueID_ = [device uniqueIdentifier];
10138 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10139 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10140 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10142 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10143 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10144 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10146 if (mcc != NULL && mnc != NULL)
10147 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10154 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10155 Build_ = [system objectForKey:@"ProductBuildVersion"];
10156 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10157 Product_ = [info objectForKey:@"SafariProductVersion"];
10158 Safari_ = [info objectForKey:@"CFBundleVersion"];
10161 /* Load Database {{{ */
10163 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10165 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10167 if (Metadata_ == NULL)
10168 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10170 Settings_ = [Metadata_ objectForKey:@"Settings"];
10172 Packages_ = [Metadata_ objectForKey:@"Packages"];
10174 Values_ = [Metadata_ objectForKey:@"Values"];
10175 Sections_ = [Metadata_ objectForKey:@"Sections"];
10176 Sources_ = [Metadata_ objectForKey:@"Sources"];
10178 Token_ = [Metadata_ objectForKey:@"Token"];
10180 Version_ = [Metadata_ objectForKey:@"Version"];
10182 @synchronized (HostConfig_) {
10183 CydiaSource_ = [Metadata_ objectForKey:@"CydiaSource"];
10187 if (Settings_ != nil)
10188 Role_ = [Settings_ objectForKey:@"Role"];
10190 if (Values_ == nil) {
10191 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10192 [Metadata_ setObject:Values_ forKey:@"Values"];
10195 if (Sections_ == nil) {
10196 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10197 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10200 if (Sources_ == nil) {
10201 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10202 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10205 if (Version_ == nil) {
10206 Version_ = [NSNumber numberWithUnsignedInt:0];
10207 [Metadata_ setObject:Version_ forKey:@"Version"];
10210 @synchronized (HostConfig_) {
10211 if (CydiaSource_ == nil) {
10212 CydiaSource_ = @"apt.saurik.com";
10213 [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
10217 if ([Version_ unsignedIntValue] == 0) {
10218 AddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10219 AddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10220 AddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10221 AddSource(@"http://repo666.ultrasn0w.com/", @"./");
10223 Version_ = [NSNumber numberWithUnsignedInt:1];
10224 [Metadata_ setObject:Version_ forKey:@"Version"];
10233 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10236 if (Packages_ != nil) {
10238 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10242 [Metadata_ removeObjectForKey:@"Packages"];
10248 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10250 #define MobileSubstrate_(name) \
10251 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10252 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10253 if (handle == NULL) \
10254 NSLog(@"%s", dlerror()); \
10257 MobileSubstrate_(Activator)
10258 MobileSubstrate_(libstatusbar)
10259 MobileSubstrate_(SimulatedKeyEvents)
10260 MobileSubstrate_(WinterBoard)
10262 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10263 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10265 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10267 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10268 unlink("/tmp/.cydia.fw");
10270 } else if (access("/User", F_OK) != 0 || version < 4) {
10273 system("/usr/libexec/cydia/firmware.sh");
10277 _assert([[NSFileManager defaultManager]
10278 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10279 withIntermediateDirectories:YES
10284 if (access("/tmp/cydia.chk", F_OK) == 0) {
10285 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10286 _assert(errno == ENOENT);
10287 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10288 _assert(errno == ENOENT);
10291 /* APT Initialization {{{ */
10292 _assert(pkgInitConfig(*_config));
10293 _assert(pkgInitSystem(*_config, _system));
10296 _config->Set("APT::Acquire::Translation", lang);
10298 // XXX: this timeout might be important :(
10299 //_config->Set("Acquire::http::Timeout", 15);
10301 _config->Set("Acquire::http::MaxParallel", 3);
10303 /* Color Choices {{{ */
10304 space_ = CGColorSpaceCreateDeviceRGB();
10306 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10307 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10308 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10309 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10310 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10311 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10312 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10313 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10314 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10316 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10317 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10319 /* UIKit Configuration {{{ */
10320 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10321 if ($GSFontSetUseLegacyFontMetrics != NULL)
10322 $GSFontSetUseLegacyFontMetrics(YES);
10324 // XXX: I have a feeling this was important
10325 //UIKeyboardDisableAutomaticAppearance();
10328 Colon_ = UCLocalize("COLON_DELIMITED");
10329 Elision_ = UCLocalize("ELISION");
10330 Error_ = UCLocalize("ERROR");
10331 Warning_ = UCLocalize("WARNING");
10334 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10336 CGColorSpaceRelease(space_);
10337 CFRelease(Locale_);