1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "CyteKit/UCPlatform.h"
45 #include "CyteKit/Localize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <QuartzCore/CALayer.h>
71 #include <WebCore/WebCoreThread.h>
78 #include <ext/stdio_filebuf.h>
82 #include <apt-pkg/acquire.h>
83 #include <apt-pkg/acquire-item.h>
84 #include <apt-pkg/algorithms.h>
85 #include <apt-pkg/cachefile.h>
86 #include <apt-pkg/clean.h>
87 #include <apt-pkg/configuration.h>
88 #include <apt-pkg/debindexfile.h>
89 #include <apt-pkg/debmetaindex.h>
90 #include <apt-pkg/error.h>
91 #include <apt-pkg/init.h>
92 #include <apt-pkg/mmap.h>
93 #include <apt-pkg/pkgrecords.h>
94 #include <apt-pkg/sha1.h>
95 #include <apt-pkg/sourcelist.h>
96 #include <apt-pkg/sptr.h>
97 #include <apt-pkg/strutl.h>
98 #include <apt-pkg/tagfile.h>
100 #include <apr-1/apr_pools.h>
102 #include <sys/types.h>
103 #include <sys/stat.h>
104 #include <sys/sysctl.h>
105 #include <sys/param.h>
106 #include <sys/mount.h>
107 #include <sys/reboot.h>
114 #include <mach-o/nlist.h>
123 #include <Cytore.hpp>
125 #include <CydiaSubstrate/CydiaSubstrate.h>
126 #include "Menes/Menes.h"
128 #include "CyteKit/PerlCompatibleRegEx.hpp"
129 #include "CyteKit/TableViewCell.h"
130 #include "CyteKit/WebScriptObject-Cyte.h"
131 #include "CyteKit/WebViewController.h"
132 #include "CyteKit/stringWithUTF8Bytes.h"
134 #include "Cydia/MIMEAddress.h"
135 #include "Cydia/LoadingViewController.h"
136 #include "Cydia/ProgressEvent.h"
138 #include "SDURLCache/SDURLCache.h"
145 #define _timestamp ({ \
147 gettimeofday(&tv, NULL); \
148 tv.tv_sec * 1000000 + tv.tv_usec; \
151 typedef std::vector<class ProfileTime *> TimeList;
161 ProfileTime(const char *name) :
165 times_.push_back(this);
168 void AddTime(uint64_t time) {
175 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
187 ProfileTimer(ProfileTime &time) :
194 time_.AddTime(_timestamp - start_);
199 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
201 std::cerr << "========" << std::endl;
204 #define _profile(name) { \
205 static ProfileTime name(#name); \
206 ProfileTimer _ ## name(name);
212 #define Cydia_ CYDIA_VERSION
214 #define lprintf(args...) fprintf(stderr, args)
217 #define TraceLogging (1 && !ForRelease)
218 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
219 #define ProfileTimes (0 && !ForRelease)
220 #define ForSaurik (0 && !ForRelease)
221 #define LogBrowser (0 && !ForRelease)
222 #define TrackResize (0 && !ForRelease)
223 #define ManualRefresh (1 && !ForRelease)
224 #define ShowInternals (0 && !ForRelease)
225 #define AlwaysReload (0 && !ForRelease)
226 #define TryIndexedCollation (0 && !ForRelease)
230 #define _trace(args...)
235 #define _profile(name) {
238 #define PrintTimes() do {} while (false)
241 // Hash Functions/Structures {{{
242 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
250 static NSString *Colon_;
252 static NSString *Error_;
253 static NSString *Warning_;
255 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
257 static _finline NSString *CydiaURL(NSString *path) {
259 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
260 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
261 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
262 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
263 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
265 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
268 static _finline void UpdateExternalStatus(uint64_t newStatus) {
270 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
271 notify_set_state(notify_token, newStatus);
272 notify_cancel(notify_token);
274 notify_post("com.saurik.Cydia.status");
277 static CGFloat CYStatusBarHeight(UIInterfaceOrientation orientation) {
278 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
279 return UIInterfaceOrientationIsPortrait(orientation) ? size.height : size.width;
282 /* NSForcedOrderingSearch doesn't work on the iPhone */
283 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
284 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
285 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
287 /* Insertion Sort {{{ */
289 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
290 const char *ptr = (const char *)list;
292 CFIndex half = count / 2;
293 const char *probe = ptr + elementSize * half;
294 CFComparisonResult cr = comparator(element, probe, context);
295 if (0 == cr) return (probe - (const char *)list) / elementSize;
296 ptr = (cr < 0) ? ptr : probe + elementSize;
297 count = (cr < 0) ? half : (half + (count & 1) - 1);
299 return (ptr - (const char *)list) / elementSize;
302 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
303 const char *ptr = (const char *)list;
305 CFIndex half = count / 2;
306 const char *probe = ptr + elementSize * half;
307 CFComparisonResult cr = comparator(element, probe, context);
308 if (0 == cr) return (probe - (const char *)list) / elementSize;
309 ptr = (cr < 0) ? ptr : probe + elementSize;
310 count = (cr < 0) ? half : (half + (count & 1) - 1);
312 return (ptr - (const char *)list) / elementSize;
315 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
316 if (range.length == 0)
318 const void **values(new const void *[range.length]);
319 CFArrayGetValues(array, range, values);
321 #if HistogramInsertionSort > 0
322 uint32_t total(0), *offsets(new uint32_t[range.length]);
325 for (CFIndex index(1); index != range.length; ++index) {
326 const void *value(values[index]);
327 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
328 CFIndex correct(index);
329 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
330 #if HistogramInsertionSort > 1
331 NSLog(@"%@ < %@", value, values[correct - 1]);
336 if (correct != index) {
337 size_t offset(index - correct);
338 #if HistogramInsertionSort
342 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
344 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
345 values[correct] = value;
349 CFArrayReplaceValues(array, range, values, range.length);
352 #if HistogramInsertionSort > 0
353 for (CFIndex index(0); index != range.length; ++index)
354 if (offsets[index] != 0)
355 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
356 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
363 /* Apple Bug Fixes {{{ */
364 @implementation UIWebDocumentView (Cydia)
366 - (void) _setScrollerOffset:(CGPoint)offset {
367 UIScroller *scroller([self _scroller]);
369 CGSize size([scroller contentSize]);
370 CGSize bounds([scroller bounds].size);
373 max.x = size.width - bounds.width;
374 max.y = size.height - bounds.height;
382 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
383 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
385 [scroller setOffset:offset];
391 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
392 size_t length([self length] - state->state);
395 else if (length > count)
397 for (size_t i(0); i != length; ++i)
398 objects[i] = [self item:state->state++];
399 state->itemsPtr = objects;
400 state->mutationsPtr = (unsigned long *) self;
404 /* Cydia NSString Additions {{{ */
405 @interface NSString (Cydia)
406 - (NSComparisonResult) compareByPath:(NSString *)other;
407 - (NSString *) stringByCachingURLWithCurrentCDN;
408 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
411 @implementation NSString (Cydia)
413 - (NSComparisonResult) compareByPath:(NSString *)other {
414 NSString *prefix = [self commonPrefixWithString:other options:0];
415 size_t length = [prefix length];
417 NSRange lrange = NSMakeRange(length, [self length] - length);
418 NSRange rrange = NSMakeRange(length, [other length] - length);
420 lrange = [self rangeOfString:@"/" options:0 range:lrange];
421 rrange = [other rangeOfString:@"/" options:0 range:rrange];
423 NSComparisonResult value;
425 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
426 value = NSOrderedSame;
427 else if (lrange.location == NSNotFound)
428 value = NSOrderedAscending;
429 else if (rrange.location == NSNotFound)
430 value = NSOrderedDescending;
432 value = NSOrderedSame;
434 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
435 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
436 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
437 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
439 NSComparisonResult result = [lpath compare:rpath];
440 return result == NSOrderedSame ? value : result;
443 - (NSString *) stringByCachingURLWithCurrentCDN {
445 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
446 withString:@"://cache.cydia.saurik.com/"
450 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
451 return [(id)CFURLCreateStringByAddingPercentEscapes(
456 kCFStringEncodingUTF8
463 /* C++ NSString Wrapper Cache {{{ */
464 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
465 return size == 0 ? NULL :
466 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
467 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
470 static _finline CFStringRef CYStringCreate(const char *data) {
471 return CYStringCreate(data, strlen(data));
480 _finline void clear_() {
481 if (cache_ != NULL) {
488 _finline bool empty() const {
492 _finline size_t size() const {
496 _finline char *data() const {
500 _finline void clear() {
505 _finline CYString() :
512 _finline ~CYString() {
516 void operator =(const CYString &rhs) {
520 if (rhs.cache_ == nil)
523 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
526 void copy(apr_pool_t *pool) {
527 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
528 memcpy(temp, data_, size_);
533 void set(apr_pool_t *pool, const char *data, size_t size) {
539 data_ = const_cast<char *>(data);
547 _finline void set(apr_pool_t *pool, const char *data) {
548 set(pool, data, data == NULL ? 0 : strlen(data));
551 _finline void set(apr_pool_t *pool, const std::string &rhs) {
552 set(pool, rhs.data(), rhs.size());
555 bool operator ==(const CYString &rhs) const {
556 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
559 _finline operator CFStringRef() {
561 cache_ = CYStringCreate(data_, size_);
565 _finline operator id() {
566 return (NSString *) static_cast<CFStringRef>(*this);
569 _finline operator const char *() {
570 return reinterpret_cast<const char *>(data_);
574 /* C++ NSString Algorithm Adapters {{{ */
576 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
579 struct NSStringMapHash :
580 std::unary_function<NSString *, size_t>
582 _finline size_t operator ()(NSString *value) const {
583 return CFStringHashNSString((CFStringRef) value);
587 struct NSStringMapLess :
588 std::binary_function<NSString *, NSString *, bool>
590 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
591 return [lhs compare:rhs] == NSOrderedAscending;
595 struct NSStringMapEqual :
596 std::binary_function<NSString *, NSString *, bool>
598 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
599 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
600 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
601 //[lhs isEqualToString:rhs];
606 /* CoreGraphics Primitives {{{ */
611 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
612 CGFloat color[] = {red, green, blue, alpha};
613 return CGColorCreate(space, color);
622 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
623 color_(Create_(space, red, green, blue, alpha))
625 Set(space, red, green, blue, alpha);
630 CGColorRelease(color_);
637 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
639 color_ = Create_(space, red, green, blue, alpha);
642 operator CGColorRef() {
648 /* Random Global Variables {{{ */
649 static const int PulseInterval_ = 50000;
651 static const NSString *UI_;
654 static bool RestartSubstrate_;
655 static NSArray *Finishes_;
657 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
658 #define NotifyConfig_ "/etc/notify.conf"
660 static bool Queuing_;
662 static CYColor Blue_;
663 static CYColor Blueish_;
664 static CYColor Black_;
666 static CYColor White_;
667 static CYColor Gray_;
668 static CYColor Green_;
669 static CYColor Purple_;
670 static CYColor Purplish_;
672 static UIColor *InstallingColor_;
673 static UIColor *RemovingColor_;
675 static NSString *App_;
677 static BOOL Advanced_;
678 static BOOL Ignored_;
680 static _H<UIFont> Font12_;
681 static _H<UIFont> Font12Bold_;
682 static _H<UIFont> Font14_;
683 static _H<UIFont> Font18Bold_;
684 static _H<UIFont> Font22Bold_;
686 static const char *Machine_ = NULL;
687 static NSString *System_ = nil;
688 static NSString *SerialNumber_ = nil;
689 static NSString *ChipID_ = nil;
690 static NSString *BBSNum_ = nil;
691 static _H<NSString> Token_;
692 static NSString *UniqueID_ = nil;
693 static NSString *PLMN_ = nil;
694 static NSString *Build_ = nil;
695 static NSString *Product_ = nil;
696 static NSString *Safari_ = nil;
698 static CFLocaleRef Locale_;
699 static NSArray *Languages_;
700 static CGColorSpaceRef space_;
702 static NSDictionary *SectionMap_;
703 static NSMutableDictionary *Metadata_;
704 static _transient NSMutableDictionary *Settings_;
705 static _transient NSString *Role_;
706 static _transient NSMutableDictionary *Packages_;
707 static _transient NSMutableDictionary *Values_;
708 static _transient NSMutableDictionary *Sections_;
709 static _transient NSMutableDictionary *Sources_;
710 static _transient NSNumber *Version_;
711 static _transient _H<NSString> CydiaSource_;
712 static bool Changed_;
716 static CGFloat ScreenScale_;
717 static NSString *Idiom_;
718 static NSString *Firmware_;
720 static _H<NSMutableDictionary> SessionData_;
721 static _H<NSObject> HostConfig_;
722 static _H<NSMutableSet> BridgedHosts_;
723 static _H<NSMutableSet> TokenHosts_;
724 static _H<NSMutableSet> InsecureHosts_;
725 static _H<NSMutableSet> PipelinedHosts_;
726 static _H<NSMutableSet> CachedURLs_;
728 static NSString *kCydiaProgressEventTypeError = @"Error";
729 static NSString *kCydiaProgressEventTypeInformation = @"Information";
730 static NSString *kCydiaProgressEventTypeStatus = @"Status";
731 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
734 static void AddSource(NSDictionary *source) {
735 [Sources_ setObject:source forKey:[NSString stringWithFormat:@"%@:%@:%@", [source objectForKey:@"Type"], [source objectForKey:@"URI"], [source objectForKey:@"Distribution"]]];
739 static void AddSource(NSString *href, NSString *distribution, NSArray *sections = nil) {
740 AddSource([NSMutableDictionary dictionaryWithObjectsAndKeys:
743 distribution, @"Distribution",
744 sections ?: [NSMutableArray array], @"Sections",
748 static void WriteSources() {
749 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
750 _assert(file != NULL);
752 fprintf(file, "deb http://%s/ tangelo-3.7 main\n",
753 [CydiaSource_ UTF8String]
756 for (NSString *key in [Sources_ allKeys]) {
757 NSDictionary *source([Sources_ objectForKey:key]);
759 NSArray *sections([source objectForKey:@"Sections"] ?: [NSArray array]);
761 fprintf(file, "%s %s %s%s%s\n",
762 [[source objectForKey:@"Type"] UTF8String],
763 [[source objectForKey:@"URI"] UTF8String],
764 [[source objectForKey:@"Distribution"] UTF8String],
765 [sections count] == 0 ? "" : " ",
766 [[sections componentsJoinedByString:@" "] UTF8String]
773 /* Display Helpers {{{ */
774 inline float Interpolate(float begin, float end, float fraction) {
775 return (end - begin) * fraction + begin;
778 static _finline const char *StripVersion_(const char *version) {
779 const char *colon(strchr(version, ':'));
780 return colon == NULL ? version : colon + 1;
783 NSString *LocalizeSection(NSString *section) {
784 static Pcre title_r("^(.*?) \\((.*)\\)$");
785 if (title_r(section)) {
786 NSString *parent(title_r[1]);
787 NSString *child(title_r[2]);
789 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
790 LocalizeSection(parent),
791 LocalizeSection(child)
795 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
798 NSString *Simplify(NSString *title) {
799 const char *data = [title UTF8String];
800 size_t size = [title length];
802 static Pcre square_r("^\\[(.*)\\]$");
803 if (square_r(data, size))
804 return Simplify(square_r[1]);
806 static Pcre paren_r("^\\((.*)\\)$");
807 if (paren_r(data, size))
808 return Simplify(paren_r[1]);
810 static Pcre title_r("^(.*?) \\((.*)\\)$");
811 if (title_r(data, size))
812 return Simplify(title_r[1]);
818 NSString *GetLastUpdate() {
819 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
822 return UCLocalize("NEVER_OR_UNKNOWN");
824 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
825 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
827 CFRelease(formatter);
829 return [(NSString *) formatted autorelease];
832 bool isSectionVisible(NSString *section) {
833 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
834 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
835 return hidden == nil || ![hidden boolValue];
838 static NSObject *CYIOGetValue(const char *path, NSString *property) {
839 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
840 if (entry == MACH_PORT_NULL)
843 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
844 IOObjectRelease(entry);
848 return [(id) value autorelease];
851 static NSString *CYHex(NSData *data, bool reverse = false) {
855 size_t length([data length]);
856 uint8_t bytes[length];
857 [data getBytes:bytes];
859 char string[length * 2 + 1];
860 for (size_t i(0); i != length; ++i)
861 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
863 return [NSString stringWithUTF8String:string];
868 /* Delegate Prototypes {{{ */
871 @class CydiaProgressEvent;
873 @protocol DatabaseDelegate
874 - (void) repairWithSelector:(SEL)selector;
875 - (void) setConfigurationData:(NSString *)data;
876 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
879 @class CYPackageController;
881 @protocol CydiaDelegate
882 - (void) returnToCydia;
884 - (void) retainNetworkActivityIndicator;
885 - (void) releaseNetworkActivityIndicator;
886 - (void) clearPackage:(Package *)package;
887 - (void) installPackage:(Package *)package;
888 - (void) installPackages:(NSArray *)packages;
889 - (void) removePackage:(Package *)package;
890 - (void) beginUpdate;
892 - (void) distUpgrade;
896 - (void) addSource:(NSDictionary *)source;
897 - (void) addTrivialSource:(NSString *)href;
898 - (void) showSettings;
899 - (UIProgressHUD *) addProgressHUD;
900 - (void) removeProgressHUD:(UIProgressHUD *)hud;
901 - (CyteViewController *) pageForPackage:(NSString *)name;
902 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
903 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
907 /* Status Delegation {{{ */
909 public pkgAcquireStatus
912 _transient NSObject<ProgressDelegate> *delegate_;
922 void setDelegate(NSObject<ProgressDelegate> *delegate) {
923 delegate_ = delegate;
926 NSObject<ProgressDelegate> *getDelegate() const {
930 virtual bool MediaChange(std::string media, std::string drive) {
934 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
938 virtual void Fetch(pkgAcquire::ItemDesc &item) {
939 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
940 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
941 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
944 virtual void Done(pkgAcquire::ItemDesc &item) {
945 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
946 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
947 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
950 virtual void Fail(pkgAcquire::ItemDesc &item) {
952 item.Owner->Status == pkgAcquire::Item::StatIdle ||
953 item.Owner->Status == pkgAcquire::Item::StatDone
957 std::string &error(item.Owner->ErrorText);
961 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
962 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
965 virtual bool Pulse(pkgAcquire *Owner) {
966 bool value = pkgAcquireStatus::Pulse(Owner);
969 double(CurrentBytes + CurrentItems) /
970 double(TotalBytes + TotalItems)
973 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
974 [NSNumber numberWithDouble:percent], @"Percent",
976 [NSNumber numberWithDouble:CurrentBytes], @"Current",
977 [NSNumber numberWithDouble:TotalBytes], @"Total",
978 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
979 nil] waitUntilDone:YES];
981 if (value && ![delegate_ isProgressCancelled])
989 _finline bool WasCancelled() const {
993 virtual void Start() {
994 pkgAcquireStatus::Start();
995 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
998 virtual void Stop() {
999 pkgAcquireStatus::Stop();
1000 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1001 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1005 /* Database Interface {{{ */
1006 typedef std::map< unsigned long, _H<Source> > SourceMap;
1008 @interface Database : NSObject {
1014 pkgCacheFile cache_;
1015 pkgDepCache::Policy *policy_;
1016 pkgRecords *records_;
1017 pkgProblemResolver *resolver_;
1018 pkgAcquire *fetcher_;
1020 SPtr<pkgPackageManager> manager_;
1021 pkgSourceList *list_;
1023 SourceMap sourceMap_;
1024 _H<NSMutableArray> sourceList_;
1026 CFMutableArrayRef packages_;
1028 _transient NSObject<DatabaseDelegate> *delegate_;
1029 _transient NSObject<ProgressDelegate> *progress_;
1037 std::map<const char *, _H<NSString> > sections_;
1040 + (Database *) sharedInstance;
1043 - (void) _readCydia:(NSNumber *)fd;
1044 - (void) _readStatus:(NSNumber *)fd;
1045 - (void) _readOutput:(NSNumber *)fd;
1049 - (Package *) packageWithName:(NSString *)name;
1051 - (pkgCacheFile &) cache;
1052 - (pkgDepCache::Policy *) policy;
1053 - (pkgRecords *) records;
1054 - (pkgProblemResolver *) resolver;
1055 - (pkgAcquire &) fetcher;
1056 - (pkgSourceList &) list;
1057 - (NSArray *) packages;
1058 - (NSArray *) sources;
1059 - (Source *) sourceWithKey:(NSString *)key;
1060 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1068 - (void) updateWithStatus:(Status &)status;
1070 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1072 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1073 - (NSObject<ProgressDelegate> *) progressDelegate;
1075 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1077 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1081 /* ProgressEvent Implementation {{{ */
1082 @implementation CydiaProgressEvent
1084 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1085 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1088 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1089 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1090 [event setPackage:package];
1094 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1095 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1097 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1098 NSArray *fields([description componentsSeparatedByString:@" "]);
1099 [event setItem:fields];
1101 if ([fields count] > 3) {
1102 [event setPackage:[fields objectAtIndex:2]];
1103 [event setVersion:[fields objectAtIndex:3]];
1106 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1111 + (NSArray *) _attributeKeys {
1112 return [NSArray arrayWithObjects:
1122 - (NSArray *) attributeKeys {
1123 return [[self class] _attributeKeys];
1126 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1127 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1130 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1131 if ((self = [super init]) != nil) {
1137 - (NSString *) message {
1141 - (NSString *) type {
1145 - (NSArray *) item {
1146 return (id) item_ ?: [NSNull null];
1149 - (void) setItem:(NSArray *)item {
1153 - (NSString *) package {
1154 return (id) package_ ?: [NSNull null];
1157 - (void) setPackage:(NSString *)package {
1161 - (NSString *) url {
1162 return (id) url_ ?: [NSNull null];
1165 - (void) setURL:(NSString *)url {
1169 - (void) setVersion:(NSString *)version {
1173 - (NSString *) version {
1174 return (id) version_ ?: [NSNull null];
1177 - (NSString *) compound:(NSString *)value {
1179 NSString *mode(nil); {
1180 NSString *type([self type]);
1181 if ([type isEqualToString:kCydiaProgressEventTypeError])
1182 mode = UCLocalize("ERROR");
1183 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1184 mode = UCLocalize("WARNING");
1188 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1194 - (NSString *) compoundMessage {
1195 return [self compound:[self message]];
1198 - (NSString *) compoundTitle {
1201 if (package_ == nil)
1203 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1204 title = [package name];
1208 return [self compound:title];
1214 // Cytore Definitions {{{
1215 struct PackageValue :
1218 Cytore::Offset<PackageValue> next_;
1220 uint32_t index_ : 23;
1221 uint32_t subscribed_ : 1;
1238 Cytore::Offset<PackageValue> packages_[1 << 16];
1241 static Cytore::File<MetaValue> MetaFile_;
1243 // Cytore Helper Functions {{{
1244 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1245 SplitHash nhash = { hashlittle(name, length) };
1247 PackageValue *metadata;
1249 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1250 offset: if (offset->IsNull()) {
1251 *offset = MetaFile_.New<PackageValue>(length + 1);
1252 metadata = &MetaFile_.Get(*offset);
1254 if (metadata == NULL) {
1258 metadata = new PackageValue();
1259 memset(metadata, 0, sizeof(*metadata));
1262 memcpy(metadata->name_, name, length + 1);
1263 metadata->nhash_ = nhash.u16[1];
1265 metadata = &MetaFile_.Get(*offset);
1267 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1268 offset = &metadata->next_;
1276 static void PackageImport(const void *key, const void *value, void *context) {
1277 bool &fail(*reinterpret_cast<bool *>(context));
1280 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1281 NSLog(@"failed to import package %@", key);
1285 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1286 NSDictionary *package((NSDictionary *) value);
1288 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1289 if ([subscribed boolValue] && !metadata->subscribed_)
1290 metadata->subscribed_ = true;
1292 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1293 time_t time([date timeIntervalSince1970]);
1294 if (metadata->first_ > time || metadata->first_ == 0)
1295 metadata->first_ = time;
1298 NSDate *date([package objectForKey:@"LastSeen"]);
1299 NSString *version([package objectForKey:@"LastVersion"]);
1301 if (date != nil && version != nil) {
1302 time_t time([date timeIntervalSince1970]);
1303 if (metadata->last_ < time || metadata->last_ == 0)
1304 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1305 size_t length(strlen(buffer));
1306 uint16_t vhash(hashlittle(buffer, length));
1308 size_t capped(std::min<size_t>(8, length));
1309 char *latest(buffer + length - capped);
1311 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1312 metadata->vhash_ = vhash;
1314 metadata->last_ = time;
1320 /* Source Class {{{ */
1321 @interface Source : NSObject {
1323 Database *database_;
1326 CYString depiction_;
1327 CYString description_;
1333 CYString distribution_;
1339 _H<NSString> authority_;
1341 CYString defaultIcon_;
1343 _H<NSDictionary> record_;
1347 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1349 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1351 - (NSString *) depictionForPackage:(NSString *)package;
1352 - (NSString *) supportForPackage:(NSString *)package;
1354 - (NSDictionary *) record;
1358 - (NSString *) distribution;
1359 - (NSString *) type;
1361 - (NSString *) base;
1364 - (NSString *) host;
1366 - (NSString *) name;
1367 - (NSString *) shortDescription;
1368 - (NSString *) label;
1369 - (NSString *) origin;
1370 - (NSString *) version;
1372 - (NSString *) defaultIcon;
1376 @implementation Source
1380 distribution_.clear();
1385 description_.clear();
1391 defaultIcon_.clear();
1398 + (NSString *) webScriptNameForSelector:(SEL)selector {
1400 else if (selector == @selector(addSection:))
1401 return @"addSection";
1402 else if (selector == @selector(getField:))
1404 else if (selector == @selector(removeSection:))
1405 return @"removeSection";
1406 else if (selector == @selector(remove))
1412 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1413 return [self webScriptNameForSelector:selector] == nil;
1416 + (NSArray *) _attributeKeys {
1417 return [NSArray arrayWithObjects:
1425 @"shortDescription",
1433 - (NSArray *) attributeKeys {
1434 return [[self class] _attributeKeys];
1437 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1438 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1441 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1444 trusted_ = index->IsTrusted();
1446 uri_.set(pool, index->GetURI());
1447 distribution_.set(pool, index->GetDist());
1448 type_.set(pool, index->GetType());
1450 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1451 if (dindex != NULL) {
1452 base_.set(pool, dindex->MetaIndexURI(""));
1455 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1458 pkgTagFile tags(&fd);
1460 pkgTagSection section;
1467 {"default-icon", &defaultIcon_},
1468 {"depiction", &depiction_},
1469 {"description", &description_},
1471 {"origin", &origin_},
1472 {"support", &support_},
1473 {"version", &version_},
1476 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1477 const char *start, *end;
1479 if (section.Find(names[i].name_, start, end)) {
1480 CYString &value(*names[i].value_);
1481 value.set(pool, start, end - start);
1487 record_ = [Sources_ objectForKey:[self key]];
1489 NSURL *url([NSURL URLWithString:uri_]);
1493 host_ = [host_ lowercaseString];
1498 authority_ = [url path];
1501 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1502 if ((self = [super init]) != nil) {
1503 era_ = [database era];
1504 database_ = database;
1507 [self setMetaIndex:index inPool:pool];
1511 - (NSString *) getField:(NSString *)name {
1512 @synchronized (database_) {
1513 if ([database_ era] != era_ || index_ == NULL)
1516 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1521 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1526 pkgTagFile tags(&fd);
1528 pkgTagSection section;
1531 const char *start, *end;
1532 if (!section.Find([name UTF8String], start, end))
1533 return (NSString *) [NSNull null];
1535 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1538 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1539 NSDictionary *lhr = [self record];
1540 NSDictionary *rhr = [source record];
1542 if ((lhr == nil) != (rhr == nil))
1543 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1545 NSString *lhs = [self name];
1546 NSString *rhs = [source name];
1548 if ([lhs length] != 0 && [rhs length] != 0) {
1549 unichar lhc = [lhs characterAtIndex:0];
1550 unichar rhc = [rhs characterAtIndex:0];
1552 if (isalpha(lhc) && !isalpha(rhc))
1553 return NSOrderedAscending;
1554 else if (!isalpha(lhc) && isalpha(rhc))
1555 return NSOrderedDescending;
1558 return [lhs compare:rhs options:LaxCompareOptions_];
1561 - (NSString *) depictionForPackage:(NSString *)package {
1562 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1565 - (NSString *) supportForPackage:(NSString *)package {
1566 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1569 - (NSArray *) sections {
1570 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1573 - (void) _addSection:(NSString *)section {
1576 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1577 if (![sections containsObject:section]) {
1578 [sections addObject:section];
1582 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1587 - (bool) addSection:(NSString *)section {
1591 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1595 - (void) _removeSection:(NSString *)section {
1599 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1600 if ([sections containsObject:section]) {
1601 [sections removeObject:section];
1606 - (bool) removeSection:(NSString *)section {
1610 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1615 [Sources_ removeObjectForKey:[self key]];
1620 bool value(record_ != nil);
1621 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1625 - (NSDictionary *) record {
1633 - (NSString *) uri {
1637 - (NSString *) distribution {
1638 return distribution_;
1641 - (NSString *) type {
1645 - (NSString *) base {
1649 - (NSString *) key {
1650 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1653 - (NSString *) host {
1657 - (NSString *) name {
1658 return origin_.empty() ? (id) authority_ : origin_;
1661 - (NSString *) shortDescription {
1662 return description_;
1665 - (NSString *) label {
1666 return label_.empty() ? (id) authority_ : label_;
1669 - (NSString *) origin {
1673 - (NSString *) version {
1677 - (NSString *) defaultIcon {
1678 return defaultIcon_;
1683 /* CydiaOperation Class {{{ */
1684 @interface CydiaOperation : NSObject {
1685 _H<NSString> operator_;
1686 _H<NSString> value_;
1689 - (NSString *) operator;
1690 - (NSString *) value;
1694 @implementation CydiaOperation
1696 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1697 if ((self = [super init]) != nil) {
1698 operator_ = [NSString stringWithUTF8String:_operator];
1699 value_ = [NSString stringWithUTF8String:value];
1703 + (NSArray *) _attributeKeys {
1704 return [NSArray arrayWithObjects:
1710 - (NSArray *) attributeKeys {
1711 return [[self class] _attributeKeys];
1714 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1715 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1718 - (NSString *) operator {
1722 - (NSString *) value {
1728 /* CydiaClause Class {{{ */
1729 @interface CydiaClause : NSObject {
1730 _H<NSString> package_;
1731 _H<CydiaOperation> version_;
1734 - (NSString *) package;
1735 - (CydiaOperation *) version;
1739 @implementation CydiaClause
1741 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1742 if ((self = [super init]) != nil) {
1743 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1745 if (const char *version = dep.TargetVer())
1746 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1748 version_ = (id) [NSNull null];
1752 + (NSArray *) _attributeKeys {
1753 return [NSArray arrayWithObjects:
1759 - (NSArray *) attributeKeys {
1760 return [[self class] _attributeKeys];
1763 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1764 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1767 - (NSString *) package {
1771 - (CydiaOperation *) version {
1777 /* CydiaRelation Class {{{ */
1778 @interface CydiaRelation : NSObject {
1779 _H<NSString> relationship_;
1780 _H<NSMutableArray> clauses_;
1783 - (NSString *) relationship;
1784 - (NSArray *) clauses;
1788 @implementation CydiaRelation
1790 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1791 if ((self = [super init]) != nil) {
1792 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1793 clauses_ = [NSMutableArray arrayWithCapacity:8];
1795 pkgCache::DepIterator start;
1796 pkgCache::DepIterator end;
1797 dep.GlobOr(start, end); // ++dep
1800 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1802 // yes, seriously. (wtf?)
1810 + (NSArray *) _attributeKeys {
1811 return [NSArray arrayWithObjects:
1817 - (NSArray *) attributeKeys {
1818 return [[self class] _attributeKeys];
1821 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1822 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1825 - (NSString *) relationship {
1826 return relationship_;
1829 - (NSArray *) clauses {
1833 - (void) addClause:(CydiaClause *)clause {
1834 [clauses_ addObject:clause];
1839 /* Package Class {{{ */
1840 struct ParsedPackage {
1843 CYString architecture_;
1846 CYString depiction_;
1856 @interface Package : NSObject {
1859 uint32_t essential_ : 1;
1860 uint32_t obsolete_ : 1;
1861 uint32_t ignored_ : 1;
1867 _transient Database *database_;
1869 pkgCache::VerIterator version_;
1870 pkgCache::PkgIterator iterator_;
1871 pkgCache::VerFileIterator file_;
1877 CYString installed_;
1879 const char *section_;
1880 _transient NSString *section$_;
1884 PackageValue *metadata_;
1885 ParsedPackage *parsed_;
1887 _H<NSMutableArray> tags_;
1890 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1891 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1893 - (pkgCache::PkgIterator) iterator;
1896 - (NSString *) section;
1897 - (NSString *) simpleSection;
1899 - (NSString *) longSection;
1900 - (NSString *) shortSection;
1904 - (MIMEAddress *) maintainer;
1906 - (NSString *) longDescription;
1907 - (NSString *) shortDescription;
1910 - (PackageValue *) metadata;
1913 - (bool) subscribed;
1914 - (bool) setSubscribed:(bool)subscribed;
1918 - (NSString *) latest;
1919 - (NSString *) installed;
1920 - (BOOL) uninstalled;
1923 - (BOOL) upgradableAndEssential:(BOOL)essential;
1926 - (BOOL) unfiltered;
1930 - (BOOL) halfConfigured;
1931 - (BOOL) halfInstalled;
1933 - (NSString *) mode;
1936 - (NSString *) name;
1938 - (NSString *) homepage;
1939 - (NSString *) depiction;
1940 - (MIMEAddress *) author;
1942 - (NSString *) support;
1944 - (NSArray *) files;
1945 - (NSArray *) warnings;
1946 - (NSArray *) applications;
1948 - (Source *) source;
1951 - (BOOL) matches:(NSArray *)query;
1953 - (bool) hasSupportingRole;
1954 - (BOOL) hasTag:(NSString *)tag;
1955 - (NSString *) primaryPurpose;
1956 - (NSArray *) purposes;
1957 - (bool) isCommercial;
1959 - (void) setIndex:(size_t)index;
1961 - (CYString &) cyname;
1963 - (uint32_t) compareBySection:(NSArray *)sections;
1968 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1969 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1970 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1971 - (bool) isVisibleInSection:(NSString *)section;
1972 - (bool) isVisibleInSource:(Source *)source;
1976 uint32_t PackageChangesRadix(Package *self, void *) {
1981 uint32_t timestamp : 30;
1982 uint32_t ignored : 1;
1983 uint32_t upgradable : 1;
1987 bool upgradable([self upgradableAndEssential:YES]);
1988 value.bits.upgradable = upgradable ? 1 : 0;
1991 value.bits.timestamp = 0;
1992 value.bits.ignored = [self ignored] ? 0 : 1;
1993 value.bits.upgradable = 1;
1995 value.bits.timestamp = [self seen] >> 2;
1996 value.bits.ignored = 0;
1997 value.bits.upgradable = 0;
2000 return _not(uint32_t) - value.key;
2003 uint32_t PackagePrefixRadix(Package *self, void *context) {
2004 size_t offset(reinterpret_cast<size_t>(context));
2005 CYString &name([self cyname]);
2007 size_t size(name.size());
2010 char *text(name.data());
2013 if (!isdigit(text[0]))
2017 while (size != digits && isdigit(text[digits]))
2025 if (offset == 0 && zeros != 0) {
2026 memset(data, '0', zeros);
2027 memcpy(data + zeros, text, 4 - zeros);
2029 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2030 if (size <= offset - zeros)
2033 text += offset - zeros;
2034 size -= offset - zeros;
2037 memcpy(data, text, 4);
2039 memcpy(data, text, size);
2040 memset(data + size, 0, 4 - size);
2043 for (size_t i(0); i != 4; ++i)
2044 if (isalpha(data[i]))
2052 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2054 /* XXX: ntohl may be more honest */
2055 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2058 CYString &(*PackageName)(Package *self, SEL sel);
2060 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2061 _profile(PackageNameCompare)
2062 CYString &lhi(PackageName(lhs, @selector(cyname)));
2063 CYString &rhi(PackageName(rhs, @selector(cyname)));
2064 CFStringRef lhn(lhi), rhn(rhi);
2067 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2068 else if (rhn == NULL)
2069 return NSOrderedDescending;
2071 _profile(PackageNameCompare$NumbersLast)
2072 if (!lhi.empty() && !rhi.empty()) {
2073 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2074 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2075 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2076 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2077 return lha ? NSOrderedAscending : NSOrderedDescending;
2081 CFIndex length = CFStringGetLength(lhn);
2083 _profile(PackageNameCompare$Compare)
2084 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2089 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2090 return PackageNameCompare(*lhs, *rhs, context);
2093 struct PackageNameOrdering :
2094 std::binary_function<Package *, Package *, bool>
2096 _finline bool operator ()(Package *lhs, Package *rhs) const {
2097 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2101 @implementation Package
2103 - (NSString *) description {
2104 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2108 if (parsed_ != NULL)
2113 + (NSString *) webScriptNameForSelector:(SEL)selector {
2115 else if (selector == @selector(clear))
2117 else if (selector == @selector(getField:))
2119 else if (selector == @selector(hasTag:))
2121 else if (selector == @selector(install))
2123 else if (selector == @selector(remove))
2129 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2130 return [self webScriptNameForSelector:selector] == nil;
2133 + (NSArray *) _attributeKeys {
2134 return [NSArray arrayWithObjects:
2154 @"shortDescription",
2167 - (NSArray *) attributeKeys {
2168 return [[self class] _attributeKeys];
2171 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2172 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2175 - (NSArray *) relations {
2176 @synchronized (database_) {
2177 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2178 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2179 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2183 - (NSString *) architecture {
2185 @synchronized (database_) {
2186 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2189 - (NSString *) getField:(NSString *)name {
2190 @synchronized (database_) {
2191 if ([database_ era] != era_ || file_.end())
2194 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2196 const char *start, *end;
2197 if (!parser.Find([name UTF8String], start, end))
2198 return (NSString *) [NSNull null];
2200 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2204 if (parsed_ != NULL)
2206 @synchronized (database_) {
2207 if ([database_ era] != era_ || file_.end())
2210 ParsedPackage *parsed(new ParsedPackage);
2213 _profile(Package$parse)
2214 pkgRecords::Parser *parser;
2216 _profile(Package$parse$Lookup)
2217 parser = &[database_ records]->Lookup(file_);
2222 _profile(Package$parse$Find)
2227 {"architecture", &parsed->architecture_},
2228 {"icon", &parsed->icon_},
2229 {"depiction", &parsed->depiction_},
2230 {"homepage", &parsed->homepage_},
2231 {"website", &website},
2232 {"bugs", &parsed->bugs_},
2233 {"support", &parsed->support_},
2234 {"sponsor", &parsed->sponsor_},
2235 {"author", &parsed->author_},
2238 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2239 const char *start, *end;
2241 if (parser->Find(names[i].name_, start, end)) {
2242 CYString &value(*names[i].value_);
2243 _profile(Package$parse$Value)
2244 value.set(pool_, start, end - start);
2250 _profile(Package$parse$Tagline)
2251 const char *start, *end;
2252 if (parser->ShortDesc(start, end)) {
2253 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2256 while (stop != start && stop[-1] == '\r')
2258 parsed->tagline_.set(pool_, start, stop - start);
2262 _profile(Package$parse$Retain)
2263 if (parsed->homepage_.empty())
2264 parsed->homepage_ = website;
2265 if (parsed->homepage_ == parsed->depiction_)
2266 parsed->homepage_.clear();
2271 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2272 if ((self = [super init]) != nil) {
2273 _profile(Package$initWithVersion)
2276 database_ = database;
2277 era_ = [database era];
2281 pkgCache::PkgIterator iterator(version.ParentPkg());
2282 iterator_ = iterator;
2284 _profile(Package$initWithVersion$Version)
2285 if (!version_.end())
2286 file_ = version_.FileList();
2288 pkgCache &cache([database_ cache]);
2289 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2293 _profile(Package$initWithVersion$Cache)
2294 name_.set(NULL, iterator.Display());
2296 latest_.set(NULL, StripVersion_(version_.VerStr()));
2298 pkgCache::VerIterator current(iterator.CurrentVer());
2300 installed_.set(NULL, StripVersion_(current.VerStr()));
2303 _profile(Package$initWithVersion$Tags)
2304 pkgCache::TagIterator tag(iterator.TagList());
2306 tags_ = [NSMutableArray arrayWithCapacity:8];
2308 const char *name(tag.Name());
2309 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2311 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2312 if (strcmp(name + 6, "enduser") == 0)
2314 else if (strcmp(name + 6, "hacker") == 0)
2316 else if (strcmp(name + 6, "developer") == 0)
2318 else if (strcmp(name + 6, "cydia") == 0)
2324 if (strncmp(name, "cydia::", 7) == 0) {
2325 if (strcmp(name + 7, "essential") == 0)
2327 else if (strcmp(name + 7, "obsolete") == 0)
2332 } while (!tag.end());
2336 _profile(Package$initWithVersion$Metadata)
2337 const char *mixed(iterator.Name());
2338 size_t size(strlen(mixed));
2339 char lower[size + 1];
2341 for (size_t i(0); i != size; ++i)
2342 lower[i] = mixed[i] | 0x20;
2345 PackageValue *metadata(PackageFind(lower, size));
2346 metadata_ = metadata;
2348 id_.set(NULL, metadata->name_, size);
2350 const char *latest(version_.VerStr());
2351 size_t length(strlen(latest));
2353 uint16_t vhash(hashlittle(latest, length));
2355 size_t capped(std::min<size_t>(8, length));
2356 latest = latest + length - capped;
2358 if (metadata->first_ == 0)
2359 metadata->first_ = now_;
2361 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2362 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2363 metadata->vhash_ = vhash;
2364 metadata->last_ = now_;
2365 } else if (metadata->last_ == 0)
2366 metadata->last_ = metadata->first_;
2369 _profile(Package$initWithVersion$Section)
2370 section_ = iterator.Section();
2373 _profile(Package$initWithVersion$Flags)
2374 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2375 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2380 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2381 pkgCache::VerIterator version;
2383 _profile(Package$packageWithIterator$GetCandidateVer)
2384 version = [database policy]->GetCandidateVer(iterator);
2392 _profile(Package$packageWithIterator$Allocate)
2393 package = [Package allocWithZone:zone];
2396 _profile(Package$packageWithIterator$Initialize)
2398 initWithVersion:version
2405 _profile(Package$packageWithIterator$Autorelease)
2406 package = [package autorelease];
2412 - (pkgCache::PkgIterator) iterator {
2416 - (NSString *) section {
2417 if (section$_ == nil) {
2418 if (section_ == NULL)
2421 _profile(Package$section$mappedSectionForPointer)
2422 section$_ = [database_ mappedSectionForPointer:section_];
2427 - (NSString *) simpleSection {
2428 if (NSString *section = [self section])
2429 return Simplify(section);
2434 - (NSString *) longSection {
2435 return LocalizeSection([self section]);
2438 - (NSString *) shortSection {
2439 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2442 - (NSString *) uri {
2445 pkgIndexFile *index;
2446 pkgCache::PkgFileIterator file(file_.File());
2447 if (![database_ list].FindIndex(file, index))
2449 return [NSString stringWithUTF8String:iterator_->Path];
2450 //return [NSString stringWithUTF8String:file.Site()];
2451 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2455 - (MIMEAddress *) maintainer {
2456 @synchronized (database_) {
2457 if ([database_ era] != era_ || file_.end())
2460 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2461 const std::string &maintainer(parser->Maintainer());
2462 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2466 @synchronized (database_) {
2467 if ([database_ era] != era_ || version_.end())
2470 return version_->InstalledSize;
2473 - (NSString *) longDescription {
2474 @synchronized (database_) {
2475 if ([database_ era] != era_ || file_.end())
2478 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2479 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2481 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2482 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2483 if ([lines count] < 2)
2486 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2487 for (size_t i(1), e([lines count]); i != e; ++i) {
2488 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2489 [trimmed addObject:trim];
2492 return [trimmed componentsJoinedByString:@"\n"];
2495 - (NSString *) shortDescription {
2496 if (parsed_ != NULL)
2497 return static_cast<NSString *>(parsed_->tagline_);
2499 @synchronized (database_) {
2500 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2502 const char *start, *end;
2503 if (!parser.ShortDesc(start, end))
2506 if (end - start > 200)
2510 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2513 while (end != start && end[-1] == '\r')
2517 return [(id) CYStringCreate(start, end - start) autorelease];
2521 _profile(Package$index)
2522 CFStringRef name((CFStringRef) [self name]);
2523 if (CFStringGetLength(name) == 0)
2525 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2526 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2528 return toupper(character);
2532 - (PackageValue *) metadata {
2537 PackageValue *metadata([self metadata]);
2538 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2541 - (bool) subscribed {
2542 return [self metadata]->subscribed_;
2545 - (bool) setSubscribed:(bool)subscribed {
2546 PackageValue *metadata([self metadata]);
2547 if (metadata->subscribed_ == subscribed)
2549 metadata->subscribed_ = subscribed;
2557 - (NSString *) latest {
2561 - (NSString *) installed {
2565 - (BOOL) uninstalled {
2566 return installed_.empty();
2570 return !version_.end();
2573 - (BOOL) upgradableAndEssential:(BOOL)essential {
2574 _profile(Package$upgradableAndEssential)
2575 pkgCache::VerIterator current(iterator_.CurrentVer());
2577 return essential && essential_;
2579 return !version_.end() && version_ != current;
2583 - (BOOL) essential {
2588 return [database_ cache][iterator_].InstBroken();
2591 - (BOOL) unfiltered {
2592 _profile(Package$unfiltered$obsolete)
2593 if (_unlikely(obsolete_))
2597 _profile(Package$unfiltered$hasSupportingRole)
2598 if (_unlikely(![self hasSupportingRole]))
2606 if (![self unfiltered])
2611 _profile(Package$visible$section)
2612 section = [self section];
2615 _profile(Package$visible$isSectionVisible)
2616 if (!isSectionVisible(section))
2624 unsigned char current(iterator_->CurrentState);
2625 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2628 - (BOOL) halfConfigured {
2629 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2632 - (BOOL) halfInstalled {
2633 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2637 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2638 return state.Mode != pkgDepCache::ModeKeep;
2641 - (NSString *) mode {
2642 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2644 switch (state.Mode) {
2645 case pkgDepCache::ModeDelete:
2646 if ((state.iFlags & pkgDepCache::Purge) != 0)
2650 case pkgDepCache::ModeKeep:
2651 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2652 return @"REINSTALL";
2653 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2657 case pkgDepCache::ModeInstall:
2658 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2659 return @"REINSTALL";
2660 else*/ switch (state.Status) {
2662 return @"DOWNGRADE";
2668 return @"NEW_INSTALL";
2679 - (NSString *) name {
2680 return name_.empty() ? id_ : name_;
2683 - (UIImage *) icon {
2684 NSString *section = [self simpleSection];
2687 if (parsed_ != NULL)
2688 if (NSString *href = parsed_->icon_)
2689 if ([href hasPrefix:@"file:///"])
2690 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2691 if (icon == nil) if (section != nil)
2692 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2693 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2694 if ([dicon hasPrefix:@"file:///"])
2695 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2697 icon = [UIImage applicationImageNamed:@"unknown.png"];
2701 - (NSString *) homepage {
2702 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2705 - (NSString *) depiction {
2706 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2709 - (MIMEAddress *) sponsor {
2710 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2713 - (MIMEAddress *) author {
2714 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2717 - (NSString *) support {
2718 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2721 - (NSArray *) files {
2722 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2723 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2726 fin.open([path UTF8String]);
2731 while (std::getline(fin, line))
2732 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2737 - (NSString *) state {
2738 @synchronized (database_) {
2739 if ([database_ era] != era_ || file_.end())
2742 switch (iterator_->CurrentState) {
2743 case pkgCache::State::NotInstalled:
2744 return @"NotInstalled";
2745 case pkgCache::State::UnPacked:
2747 case pkgCache::State::HalfConfigured:
2748 return @"HalfConfigured";
2749 case pkgCache::State::HalfInstalled:
2750 return @"HalfInstalled";
2751 case pkgCache::State::ConfigFiles:
2752 return @"ConfigFiles";
2753 case pkgCache::State::Installed:
2754 return @"Installed";
2755 case pkgCache::State::TriggersAwaited:
2756 return @"TriggersAwaited";
2757 case pkgCache::State::TriggersPending:
2758 return @"TriggersPending";
2761 return (NSString *) [NSNull null];
2764 - (NSString *) selection {
2765 @synchronized (database_) {
2766 if ([database_ era] != era_ || file_.end())
2769 switch (iterator_->SelectedState) {
2770 case pkgCache::State::Unknown:
2772 case pkgCache::State::Install:
2774 case pkgCache::State::Hold:
2776 case pkgCache::State::DeInstall:
2777 return @"DeInstall";
2778 case pkgCache::State::Purge:
2782 return (NSString *) [NSNull null];
2785 - (NSArray *) warnings {
2786 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2787 const char *name(iterator_.Name());
2789 size_t length(strlen(name));
2790 if (length < 2) invalid:
2791 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2792 else for (size_t i(0); i != length; ++i)
2794 /* XXX: technically this is not allowed */
2795 (name[i] < 'A' || name[i] > 'Z') &&
2796 (name[i] < 'a' || name[i] > 'z') &&
2797 (name[i] < '0' || name[i] > '9') &&
2798 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2801 if (strcmp(name, "cydia") != 0) {
2804 bool _private = false;
2807 bool repository = [[self section] isEqualToString:@"Repositories"];
2809 if (NSArray *files = [self files])
2810 for (NSString *file in files)
2811 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2813 else if (!user && [file isEqualToString:@"/User"])
2815 else if (!_private && [file isEqualToString:@"/private"])
2817 else if (!stash && [file isEqualToString:@"/var/stash"])
2820 /* XXX: this is not sensitive enough. only some folders are valid. */
2821 if (cydia && !repository)
2822 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2824 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2826 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2828 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2831 return [warnings count] == 0 ? nil : warnings;
2834 - (NSArray *) applications {
2835 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2837 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2839 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2840 if (NSArray *files = [self files])
2841 for (NSString *file in files)
2842 if (application_r(file)) {
2843 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2844 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2845 if ([id isEqualToString:me])
2848 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2850 display = application_r[1];
2852 NSString *bundle([file stringByDeletingLastPathComponent]);
2853 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2854 if (icon == nil || [icon length] == 0)
2856 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2858 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2859 [applications addObject:application];
2861 [application addObject:id];
2862 [application addObject:display];
2863 [application addObject:url];
2866 return [applications count] == 0 ? nil : applications;
2869 - (Source *) source {
2870 if (source_ == nil) {
2871 @synchronized (database_) {
2872 if ([database_ era] != era_ || file_.end())
2873 source_ = (Source *) [NSNull null];
2875 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2879 return source_ == (Source *) [NSNull null] ? nil : source_;
2886 - (BOOL) matches:(NSArray *)query {
2887 if (query == nil || [query count] == 0)
2896 string = [self name];
2897 length = [string length];
2899 for (NSString *term in query) {
2900 range = [string rangeOfString:term options:MatchCompareOptions_];
2901 if (range.location != NSNotFound)
2902 rank_ -= 6 * 1000000 / length;
2907 length = [string length];
2909 for (NSString *term in query) {
2910 range = [string rangeOfString:term options:MatchCompareOptions_];
2911 if (range.location != NSNotFound)
2912 rank_ -= 6 * 1000000 / length;
2916 string = [self shortDescription];
2917 length = [string length];
2918 NSUInteger stop(std::min<NSUInteger>(length, 200));
2920 for (NSString *term in query) {
2921 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2922 if (range.location != NSNotFound)
2923 rank_ -= 2 * 100000;
2929 - (bool) hasSupportingRole {
2934 if ([Role_ isEqualToString:@"User"])
2938 if ([Role_ isEqualToString:@"Hacker"])
2942 if ([Role_ isEqualToString:@"Developer"])
2947 - (NSArray *) tags {
2951 - (BOOL) hasTag:(NSString *)tag {
2952 return tags_ == nil ? NO : [tags_ containsObject:tag];
2955 - (NSString *) primaryPurpose {
2956 for (NSString *tag in (NSArray *) tags_)
2957 if ([tag hasPrefix:@"purpose::"])
2958 return [tag substringFromIndex:9];
2962 - (NSArray *) purposes {
2963 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2964 for (NSString *tag in (NSArray *) tags_)
2965 if ([tag hasPrefix:@"purpose::"])
2966 [purposes addObject:[tag substringFromIndex:9]];
2967 return [purposes count] == 0 ? nil : purposes;
2970 - (bool) isCommercial {
2971 return [self hasTag:@"cydia::commercial"];
2974 - (void) setIndex:(size_t)index {
2975 if (metadata_->index_ != index)
2976 metadata_->index_ = index;
2979 - (CYString &) cyname {
2980 return name_.empty() ? id_ : name_;
2983 - (uint32_t) compareBySection:(NSArray *)sections {
2984 NSString *section([self section]);
2985 for (size_t i(0), e([sections count]); i != e; ++i) {
2986 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2990 return _not(uint32_t);
2994 @synchronized (database_) {
2995 pkgProblemResolver *resolver = [database_ resolver];
2996 resolver->Clear(iterator_);
2998 pkgCacheFile &cache([database_ cache]);
2999 cache->SetReInstall(iterator_, false);
3000 cache->MarkKeep(iterator_, false);
3004 @synchronized (database_) {
3005 pkgProblemResolver *resolver = [database_ resolver];
3006 resolver->Clear(iterator_);
3007 resolver->Protect(iterator_);
3009 pkgCacheFile &cache([database_ cache]);
3010 cache->SetReInstall(iterator_, false);
3011 cache->MarkInstall(iterator_, false);
3013 pkgDepCache::StateCache &state((*cache)[iterator_]);
3014 if (!state.Install())
3015 cache->SetReInstall(iterator_, true);
3019 @synchronized (database_) {
3020 pkgProblemResolver *resolver = [database_ resolver];
3021 resolver->Clear(iterator_);
3022 resolver->Remove(iterator_);
3023 resolver->Protect(iterator_);
3025 pkgCacheFile &cache([database_ cache]);
3026 cache->SetReInstall(iterator_, false);
3027 cache->MarkDelete(iterator_, true);
3030 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3031 _profile(Package$isUnfilteredAndSearchedForBy)
3034 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3035 value &= [self unfiltered];
3038 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3039 value &= [self matches:query];
3046 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3047 if ([search length] == 0)
3050 _profile(Package$isUnfilteredAndSelectedForBy)
3053 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3054 value &= [self unfiltered];
3057 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3058 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3065 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3066 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3069 - (bool) isVisibleInSection:(NSString *)name {
3070 NSString *section([self section]);
3074 section == nil && [name length] == 0 ||
3075 [name isEqualToString:section]
3076 ) && [self visible];
3079 - (bool) isVisibleInSource:(Source *)source {
3080 return [self source] == source && [self visible];
3085 /* Section Class {{{ */
3086 @interface Section : NSObject {
3091 _H<NSString> localized_;
3094 - (NSComparisonResult) compareByLocalized:(Section *)section;
3095 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3096 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3097 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3098 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3099 - (NSString *) name;
3106 - (void) addToCount;
3108 - (void) setCount:(size_t)count;
3109 - (NSString *) localized;
3113 @implementation Section
3115 - (NSComparisonResult) compareByLocalized:(Section *)section {
3116 NSString *lhs(localized_);
3117 NSString *rhs([section localized]);
3119 /*if ([lhs length] != 0 && [rhs length] != 0) {
3120 unichar lhc = [lhs characterAtIndex:0];
3121 unichar rhc = [rhs characterAtIndex:0];
3123 if (isalpha(lhc) && !isalpha(rhc))
3124 return NSOrderedAscending;
3125 else if (!isalpha(lhc) && isalpha(rhc))
3126 return NSOrderedDescending;
3129 return [lhs compare:rhs options:LaxCompareOptions_];
3132 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3133 if ((self = [self initWithName:name localize:NO]) != nil) {
3134 if (localized != nil)
3135 localized_ = localized;
3139 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3140 return [self initWithName:name row:0 localize:localize];
3143 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3144 if ((self = [super init]) != nil) {
3149 localized_ = LocalizeSection(name_);
3153 /* XXX: localize the index thingees */
3154 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3155 if ((self = [super init]) != nil) {
3156 name_ = [NSString stringWithCharacters:&index length:1];
3162 - (NSString *) name {
3182 - (void) addToCount {
3186 - (void) setCount:(size_t)count {
3190 - (NSString *) localized {
3197 class CydiaLogCleaner :
3198 public pkgArchiveCleaner
3201 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3206 /* Database Implementation {{{ */
3207 @implementation Database
3209 + (Database *) sharedInstance {
3210 static _H<Database> instance;
3211 if (instance == nil)
3212 instance = [[[Database alloc] init] autorelease];
3220 - (void) releasePackages {
3221 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3222 CFArrayRemoveAllValues(packages_);
3226 // XXX: actually implement this thing
3228 [self releasePackages];
3229 apr_pool_destroy(pool_);
3230 NSRecycleZone(zone_);
3234 - (void) _readCydia:(NSNumber *)fd {
3235 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3236 std::istream is(&ib);
3239 static Pcre finish_r("^finish:([^:]*)$");
3241 while (std::getline(is, line)) {
3242 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3244 const char *data(line.c_str());
3245 size_t size = line.size();
3246 lprintf("C:%s\n", data);
3248 if (finish_r(data, size)) {
3249 NSString *finish = finish_r[1];
3250 int index = [Finishes_ indexOfObject:finish];
3251 if (index != INT_MAX && index > Finish_)
3261 - (void) _readStatus:(NSNumber *)fd {
3262 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3263 std::istream is(&ib);
3266 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3267 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3269 while (std::getline(is, line)) {
3270 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3272 const char *data(line.c_str());
3273 size_t size(line.size());
3274 lprintf("S:%s\n", data);
3276 if (conffile_r(data, size)) {
3277 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3278 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3279 } else if (strncmp(data, "status: ", 8) == 0) {
3280 // status: <package>: {unpacked,half-configured,installed}
3281 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3282 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3283 } else if (strncmp(data, "processing: ", 12) == 0) {
3284 // processing: configure: config-test
3285 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3286 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3287 } else if (pmstatus_r(data, size)) {
3288 std::string type([pmstatus_r[1] UTF8String]);
3290 NSString *package = pmstatus_r[2];
3291 if ([package isEqualToString:@"dpkg-exec"])
3294 float percent([pmstatus_r[3] floatValue]);
3295 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3297 NSString *string = pmstatus_r[4];
3299 if (type == "pmerror") {
3300 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3301 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3302 } else if (type == "pmstatus") {
3303 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3304 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3305 } else if (type == "pmconffile")
3306 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3308 lprintf("E:unknown pmstatus\n");
3310 lprintf("E:unknown status\n");
3318 - (void) _readOutput:(NSNumber *)fd {
3319 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3320 std::istream is(&ib);
3323 while (std::getline(is, line)) {
3324 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3326 lprintf("O:%s\n", line.c_str());
3328 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3329 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3341 - (Package *) packageWithName:(NSString *)name {
3344 @synchronized (self) {
3345 if (static_cast<pkgDepCache *>(cache_) == NULL)
3347 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3348 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3352 if ((self = [super init]) != nil) {
3359 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3360 apr_pool_create(&pool_, NULL);
3362 size_t capacity(MetaFile_->active_);
3368 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3369 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3373 _assert(pipe(fds) != -1);
3376 _config->Set("APT::Keep-Fds::", cydiafd_);
3377 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3380 detachNewThreadSelector:@selector(_readCydia:)
3382 withObject:[NSNumber numberWithInt:fds[0]]
3385 _assert(pipe(fds) != -1);
3389 detachNewThreadSelector:@selector(_readStatus:)
3391 withObject:[NSNumber numberWithInt:fds[0]]
3394 _assert(pipe(fds) != -1);
3395 _assert(dup2(fds[0], 0) != -1);
3396 _assert(close(fds[0]) != -1);
3398 input_ = fdopen(fds[1], "a");
3400 _assert(pipe(fds) != -1);
3401 _assert(dup2(fds[1], 1) != -1);
3402 _assert(close(fds[1]) != -1);
3405 detachNewThreadSelector:@selector(_readOutput:)
3407 withObject:[NSNumber numberWithInt:fds[0]]
3412 - (pkgCacheFile &) cache {
3416 - (pkgDepCache::Policy *) policy {
3420 - (pkgRecords *) records {
3424 - (pkgProblemResolver *) resolver {
3428 - (pkgAcquire &) fetcher {
3432 - (pkgSourceList &) list {
3436 - (NSArray *) packages {
3437 return (NSArray *) packages_;
3440 - (NSArray *) sources {
3444 - (Source *) sourceWithKey:(NSString *)key {
3445 for (Source *source in [self sources]) {
3446 if ([[source key] isEqualToString:key])
3451 - (bool) popErrorWithTitle:(NSString *)title {
3454 while (!_error->empty()) {
3456 bool warning(!_error->PopMessage(error));
3461 size_t size(error.size());
3462 if (size == 0 || error[size - 1] != '\n')
3464 error.resize(size - 1);
3467 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3469 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3475 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3476 return [self popErrorWithTitle:title] || !success;
3479 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3480 @synchronized (self) {
3483 [self releasePackages];
3486 [sourceList_ removeAllObjects];
3506 apr_pool_clear(pool_);
3508 NSRecycleZone(zone_);
3509 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3511 int chk(creat("/tmp/cydia.chk", 0644));
3515 if (invocation != nil)
3516 [invocation invoke];
3518 NSString *title(UCLocalize("DATABASE"));
3521 OpProgress progress;
3522 while (!cache_.Open(progress, true)) { pop:
3524 bool warning(!_error->PopMessage(error));
3525 lprintf("cache_.Open():[%s]\n", error.c_str());
3527 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3528 [delegate_ repairWithSelector:@selector(configure)];
3529 else if (error == "The package lists or status file could not be parsed or opened.")
3530 [delegate_ repairWithSelector:@selector(update)];
3531 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3532 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3533 // else if (error == "Malformed Status line")
3534 // else if (error == "The list of sources could not be read.")
3536 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3546 unlink("/tmp/cydia.chk");
3548 now_ = [[NSDate date] timeIntervalSince1970];
3550 policy_ = new pkgDepCache::Policy();
3551 records_ = new pkgRecords(cache_);
3552 resolver_ = new pkgProblemResolver(cache_);
3553 fetcher_ = new pkgAcquire(&status_);
3556 list_ = new pkgSourceList();
3557 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3560 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3561 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3565 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3568 if (cache_->BrokenCount() != 0) {
3569 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3572 if (cache_->BrokenCount() != 0) {
3573 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3577 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3581 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3582 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3583 [sourceList_ addObject:object];
3585 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3586 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3587 // XXX: this could be more intelligent
3588 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3589 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3591 sourceMap_[cached->ID] = object;
3596 /*std::vector<Package *> packages;
3597 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3602 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3603 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3604 //packages.push_back(package);
3605 CFArrayAppendValue(packages_, CFRetain(package));
3609 /*if (packages.empty())
3610 packages_ = [[NSArray alloc] init];
3612 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3615 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3616 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3617 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3625 /*if (!packages.empty())
3626 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3627 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3629 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3631 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3633 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3637 size_t count(CFArrayGetCount(packages_));
3638 MetaFile_->active_ = count;
3640 for (size_t index(0); index != count; ++index)
3641 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3648 @synchronized (self) {
3650 resolver_ = new pkgProblemResolver(cache_);
3652 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3653 if (!cache_[iterator].Keep())
3654 cache_->MarkKeep(iterator, false);
3655 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3656 cache_->SetReInstall(iterator, false);
3659 - (void) configure {
3660 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3662 system([dpkg UTF8String]);
3667 // XXX: I don't remember this condition
3672 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3674 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3676 if ([self popErrorWithTitle:title])
3680 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3682 CydiaLogCleaner cleaner;
3683 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3690 fetcher_->Shutdown();
3692 pkgRecords records(cache_);
3694 lock_ = new FileFd();
3695 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3697 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3699 if ([self popErrorWithTitle:title])
3703 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3706 manager_ = (_system->CreatePM(cache_));
3707 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3714 bool substrate(RestartSubstrate_);
3715 RestartSubstrate_ = false;
3717 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3719 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3721 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3723 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3724 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3727 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3729 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3731 [self popErrorWithTitle:title];
3735 bool failed = false;
3736 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3737 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3739 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3745 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3753 RestartSubstrate_ = true;
3756 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3758 if (_error->PendingError()) {
3763 if (result == pkgPackageManager::Failed) {
3768 if (result != pkgPackageManager::Completed) {
3773 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3775 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3777 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3778 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3781 if (![before isEqualToArray:after])
3786 NSString *title(UCLocalize("UPGRADE"));
3787 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3793 [self updateWithStatus:status_];
3796 - (void) updateWithStatus:(Status &)status {
3797 NSString *title(UCLocalize("REFRESHING_DATA"));
3800 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3804 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3805 if ([self popErrorWithTitle:title])
3808 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3810 bool success(ListUpdate(status, list, PulseInterval_));
3811 if (status.WasCancelled())
3814 [self popErrorWithTitle:title forOperation:success];
3815 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3819 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3822 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3823 delegate_ = delegate;
3826 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3827 progress_ = delegate;
3828 status_.setDelegate(delegate);
3831 - (NSObject<ProgressDelegate> *) progressDelegate {
3835 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3836 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3837 return i == sourceMap_.end() ? nil : i->second;
3840 - (NSString *) mappedSectionForPointer:(const char *)section {
3841 _H<NSString> *mapped;
3843 _profile(Database$mappedSectionForPointer$Cache)
3844 mapped = §ions_[section];
3847 if (*mapped == NULL) {
3848 size_t length(strlen(section));
3849 char spaced[length + 1];
3851 _profile(Database$mappedSectionForPointer$Replace)
3852 for (size_t index(0); index != length; ++index)
3853 spaced[index] = section[index] == '_' ? ' ' : section[index];
3854 spaced[length] = '\0';
3859 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3860 string = [NSString stringWithUTF8String:spaced];
3863 _profile(Database$mappedSectionForPointer$Map)
3864 string = [SectionMap_ objectForKey:string] ?: string;
3874 static _H<NSMutableSet> Diversions_;
3876 @interface Diversion : NSObject {
3879 _H<NSString> format_;
3884 @implementation Diversion
3886 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3887 if ((self = [super init]) != nil) {
3888 pattern_ = [from UTF8String];
3894 - (NSString *) divert:(NSString *)url {
3895 return !pattern_(url) ? nil : pattern_->*format_;
3898 + (NSURL *) divertURL:(NSURL *)url {
3900 NSString *href([url absoluteString]);
3902 for (Diversion *diversion in (id) Diversions_)
3903 if (NSString *diverted = [diversion divert:href]) {
3905 NSLog(@"div: %@", diverted);
3907 url = [NSURL URLWithString:diverted];
3914 - (NSString *) key {
3918 - (NSUInteger) hash {
3922 - (BOOL) isEqual:(Diversion *)object {
3923 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3928 @interface CydiaObject : NSObject {
3929 _H<IndirectDelegate> indirect_;
3930 _transient id delegate_;
3933 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3937 @interface CydiaWebViewController : CyteWebViewController {
3938 _H<CydiaObject> cydia_;
3941 + (void) addDiversion:(Diversion *)diversion;
3945 /* Web Scripting {{{ */
3946 @implementation CydiaObject
3948 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3949 if ((self = [super init]) != nil) {
3950 indirect_ = indirect;
3954 - (void) setDelegate:(id)delegate {
3955 delegate_ = delegate;
3958 + (NSArray *) _attributeKeys {
3959 return [NSArray arrayWithObjects:
3976 - (NSArray *) attributeKeys {
3977 return [[self class] _attributeKeys];
3980 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3981 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3984 - (NSString *) version {
3988 - (NSString *) device {
3989 return [[UIDevice currentDevice] uniqueIdentifier];
3992 - (NSString *) firmware {
3993 return [[UIDevice currentDevice] systemVersion];
3996 - (NSString *) hostname {
3997 return [[UIDevice currentDevice] name];
4000 - (NSString *) idiom {
4001 return (id) Idiom_ ?: [NSNull null];
4004 - (NSString *) plmn {
4005 return (id) PLMN_ ?: [NSNull null];
4008 - (NSString *) bbsnum {
4009 return (id) BBSNum_ ?: [NSNull null];
4012 - (NSString *) ecid {
4013 return (id) ChipID_ ?: [NSNull null];
4016 - (NSString *) serial {
4017 return SerialNumber_;
4020 - (NSString *) role {
4021 return (id) Role_ ?: [NSNull null];
4024 - (NSString *) model {
4025 return [NSString stringWithUTF8String:Machine_];
4028 - (NSString *) token {
4029 return (id) Token_ ?: [NSNull null];
4032 + (NSString *) webScriptNameForSelector:(SEL)selector {
4034 else if (selector == @selector(addBridgedHost:))
4035 return @"addBridgedHost";
4036 else if (selector == @selector(addInsecureHost:))
4037 return @"addInsecureHost";
4038 else if (selector == @selector(addInternalRedirect::))
4039 return @"addInternalRedirect";
4040 else if (selector == @selector(addPipelinedHost:scheme:))
4041 return @"addPipelinedHost";
4042 else if (selector == @selector(addSource:::))
4043 return @"addSource";
4044 else if (selector == @selector(addTokenHost:))
4045 return @"addTokenHost";
4046 else if (selector == @selector(addTrivialSource:))
4047 return @"addTrivialSource";
4048 else if (selector == @selector(close))
4050 else if (selector == @selector(du:))
4052 else if (selector == @selector(stringWithFormat:arguments:))
4054 else if (selector == @selector(getAllSources))
4055 return @"getAllSourcs";
4056 else if (selector == @selector(getKernelNumber:))
4057 return @"getKernelNumber";
4058 else if (selector == @selector(getKernelString:))
4059 return @"getKernelString";
4060 else if (selector == @selector(getInstalledPackages))
4061 return @"getInstalledPackages";
4062 else if (selector == @selector(getIORegistryEntry::))
4063 return @"getIORegistryEntry";
4064 else if (selector == @selector(getLocaleIdentifier))
4065 return @"getLocaleIdentifier";
4066 else if (selector == @selector(getPreferredLanguages))
4067 return @"getPreferredLanguages";
4068 else if (selector == @selector(getPackageById:))
4069 return @"getPackageById";
4070 else if (selector == @selector(getMetadataKeys))
4071 return @"getMetadataKeys";
4072 else if (selector == @selector(getMetadataValue:))
4073 return @"getMetadataValue";
4074 else if (selector == @selector(getSessionValue:))
4075 return @"getSessionValue";
4076 else if (selector == @selector(installPackages:))
4077 return @"installPackages";
4078 else if (selector == @selector(localizedStringForKey:value:table:))
4080 else if (selector == @selector(popViewController:))
4081 return @"popViewController";
4082 else if (selector == @selector(refreshSources))
4083 return @"refreshSources";
4084 else if (selector == @selector(removeButton))
4085 return @"removeButton";
4086 else if (selector == @selector(saveConfig))
4087 return @"saveConfig";
4088 else if (selector == @selector(setCydiaSource:))
4089 return @"setCydiaSource";
4090 else if (selector == @selector(setMetadataValue::))
4091 return @"setMetadataValue";
4092 else if (selector == @selector(setSessionValue::))
4093 return @"setSessionValue";
4094 else if (selector == @selector(substitutePackageNames:))
4095 return @"substitutePackageNames";
4096 else if (selector == @selector(scrollToBottom:))
4097 return @"scrollToBottom";
4098 else if (selector == @selector(setAllowsNavigationAction:))
4099 return @"setAllowsNavigationAction";
4100 else if (selector == @selector(setBadgeValue:))
4101 return @"setBadgeValue";
4102 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4103 return @"setButtonImage";
4104 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4105 return @"setButtonTitle";
4106 else if (selector == @selector(setHidesBackButton:))
4107 return @"setHidesBackButton";
4108 else if (selector == @selector(setHidesNavigationBar:))
4109 return @"setHidesNavigationBar";
4110 else if (selector == @selector(setNavigationBarStyle:))
4111 return @"setNavigationBarStyle";
4112 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4113 return @"setNavigationBarTintColor";
4114 else if (selector == @selector(setPasteboardString:))
4115 return @"setPasteboardString";
4116 else if (selector == @selector(setPasteboardURL:))
4117 return @"setPasteboardURL";
4118 else if (selector == @selector(setToken:))
4120 else if (selector == @selector(setViewportWidth:))
4121 return @"setViewportWidth";
4122 else if (selector == @selector(statfs:))
4124 else if (selector == @selector(supports:))
4126 else if (selector == @selector(unload))
4132 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4133 return [self webScriptNameForSelector:selector] == nil;
4136 - (BOOL) supports:(NSString *)feature {
4137 return [feature isEqualToString:@"window.open"];
4141 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4144 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4145 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4148 - (NSNumber *) getKernelNumber:(NSString *)name {
4149 const char *string([name UTF8String]);
4152 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4153 return (id) [NSNull null];
4155 if (size != sizeof(int))
4156 return (id) [NSNull null];
4159 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4160 return (id) [NSNull null];
4162 return [NSNumber numberWithInt:value];
4165 - (NSString *) getKernelString:(NSString *)name {
4166 const char *string([name UTF8String]);
4169 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4170 return (id) [NSNull null];
4172 char value[size + 1];
4173 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4174 return (id) [NSNull null];
4176 // XXX: just in case you request something ludicrous
4179 return [NSString stringWithCString:value];
4182 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4183 NSObject *value(CYIOGetValue([path UTF8String], entry));
4186 if ([value isKindOfClass:[NSData class]])
4187 value = CYHex((NSData *) value);
4192 - (void) _setCydiaSource:(NSString *)source {
4193 @synchronized (HostConfig_) {
4194 CydiaSource_ = source;
4195 [Metadata_ setObject:source forKey:@"CydiaSource"];
4201 - (void) setCydiaSource:(NSString *)source {
4202 [self performSelectorOnMainThread:@selector(_setCydiaSource:) withObject:source waitUntilDone:NO];
4205 - (NSString *) cydiaSource {
4206 @synchronized (HostConfig_) {
4207 return (id) CydiaSource_ ?: [NSNull null];
4211 - (NSArray *) getMetadataKeys {
4212 @synchronized (Values_) {
4213 return [Values_ allKeys];
4216 - (id) getMetadataValue:(NSString *)key {
4217 @synchronized (Values_) {
4218 return [Values_ objectForKey:key];
4221 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4222 @synchronized (Values_) {
4223 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4224 [Values_ removeObjectForKey:key];
4226 [Values_ setObject:value forKey:key];
4228 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4231 - (id) getSessionValue:(NSString *)key {
4232 @synchronized (SessionData_) {
4233 return [SessionData_ objectForKey:key];
4236 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4237 @synchronized (SessionData_) {
4238 if (value == (id) [WebUndefined undefined])
4239 [SessionData_ removeObjectForKey:key];
4241 [SessionData_ setObject:value forKey:key];
4244 - (void) addBridgedHost:(NSString *)host {
4245 @synchronized (HostConfig_) {
4246 [BridgedHosts_ addObject:host];
4249 - (void) addInsecureHost:(NSString *)host {
4250 @synchronized (HostConfig_) {
4251 [InsecureHosts_ addObject:host];
4254 - (void) addTokenHost:(NSString *)host {
4255 @synchronized (HostConfig_) {
4256 [TokenHosts_ addObject:host];
4259 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4260 @synchronized (HostConfig_) {
4261 if (scheme != (id) [WebUndefined undefined])
4262 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4264 [PipelinedHosts_ addObject:host];
4267 - (void) popViewController:(NSNumber *)value {
4268 if (value == (id) [WebUndefined undefined])
4269 value = [NSNumber numberWithBool:YES];
4270 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4273 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4274 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4276 for (NSString *section in sections)
4277 [array addObject:section];
4279 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4282 distribution, @"Distribution",
4284 nil] waitUntilDone:NO];
4287 - (void) addTrivialSource:(NSString *)href {
4288 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4291 - (void) refreshSources {
4292 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4295 - (void) saveConfig {
4296 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4299 - (NSArray *) getAllSources {
4300 return [[Database sharedInstance] sources];
4303 - (NSArray *) getInstalledPackages {
4304 Database *database([Database sharedInstance]);
4305 @synchronized (database) {
4306 NSArray *packages([database packages]);
4307 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4308 for (Package *package in packages)
4309 if (![package uninstalled])
4310 [installed addObject:package];
4314 - (Package *) getPackageById:(NSString *)id {
4315 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4319 return (Package *) [NSNull null];
4322 - (NSString *) getLocaleIdentifier {
4323 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4326 - (NSArray *) getPreferredLanguages {
4330 - (NSArray *) statfs:(NSString *)path {
4333 if (path == nil || statfs([path UTF8String], &stat) == -1)
4336 return [NSArray arrayWithObjects:
4337 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4338 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4339 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4343 - (NSNumber *) du:(NSString *)path {
4344 NSNumber *value(nil);
4347 _assert(pipe(fds) != -1);
4349 pid_t pid(ExecFork());
4351 _assert(dup2(fds[1], 1) != -1);
4352 _assert(close(fds[0]) != -1);
4353 _assert(close(fds[1]) != -1);
4354 /* XXX: this should probably not use du */
4355 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4360 _assert(close(fds[1]) != -1);
4362 if (FILE *du = fdopen(fds[0], "r")) {
4364 while (fgets(line, sizeof(line), du) != NULL) {
4365 size_t length(strlen(line));
4366 while (length != 0 && line[length - 1] == '\n')
4367 line[--length] = '\0';
4368 if (char *tab = strchr(line, '\t')) {
4370 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4375 } else _assert(close(fds[0]));
4379 if (waitpid(pid, &status, 0) == -1)
4382 else _assert(false);
4388 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4391 - (void) installPackages:(NSArray *)packages {
4392 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4395 - (NSString *) substitutePackageNames:(NSString *)message {
4396 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4397 for (size_t i(0), e([words count]); i != e; ++i) {
4398 NSString *word([words objectAtIndex:i]);
4399 if (Package *package = [[Database sharedInstance] packageWithName:word])
4400 [words replaceObjectAtIndex:i withObject:[package name]];
4403 return [words componentsJoinedByString:@" "];
4406 - (void) removeButton {
4407 [indirect_ removeButton];
4410 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4411 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4414 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4415 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4418 - (void) setBadgeValue:(id)value {
4419 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4422 - (void) setAllowsNavigationAction:(NSString *)value {
4423 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4426 - (void) setHidesBackButton:(NSString *)value {
4427 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4430 - (void) setHidesNavigationBar:(NSString *)value {
4431 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4434 - (void) setNavigationBarStyle:(NSString *)value {
4435 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4438 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4439 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4440 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4441 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4444 - (void) setPasteboardString:(NSString *)value {
4445 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4448 - (void) setPasteboardURL:(NSString *)value {
4449 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4452 - (void) _setToken:(NSString *)token {
4456 [Metadata_ removeObjectForKey:@"Token"];
4458 [Metadata_ setObject:Token_ forKey:@"Token"];
4463 - (void) setToken:(NSString *)token {
4464 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4467 - (void) scrollToBottom:(NSNumber *)animated {
4468 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4471 - (void) setViewportWidth:(float)width {
4472 [indirect_ setViewportWidthOnMainThread:width];
4475 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4476 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4477 unsigned count([arguments count]);
4479 for (unsigned i(0); i != count; ++i)
4480 values[i] = [arguments objectAtIndex:i];
4481 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4484 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4485 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4487 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4489 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4495 @interface NSURL (CydiaSecure)
4498 @implementation NSURL (CydiaSecure)
4500 - (bool) isCydiaSecure {
4501 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4504 @synchronized (HostConfig_) {
4505 if ([InsecureHosts_ containsObject:[self host]])
4514 /* Cydia Browser Controller {{{ */
4515 @implementation CydiaWebViewController
4517 - (NSURL *) navigationURL {
4518 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4521 + (void) initialize {
4522 Diversions_ = [NSMutableSet setWithCapacity:0];
4525 + (void) addDiversion:(Diversion *)diversion {
4526 [Diversions_ addObject:diversion];
4529 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4530 [super webView:view didClearWindowObject:window forFrame:frame];
4532 WebDataSource *source([frame dataSource]);
4533 NSURLResponse *response([source response]);
4534 NSURL *url([response URL]);
4535 NSString *scheme([[url scheme] lowercaseString]);
4537 bool bridged(false);
4539 @synchronized (HostConfig_) {
4540 if ([scheme isEqualToString:@"file"])
4542 else if ([scheme isEqualToString:@"https"])
4543 if ([BridgedHosts_ containsObject:[url host]])
4548 [window setValue:cydia_ forKey:@"cydia"];
4551 - (void) _setupMail:(MFMailComposeViewController *)controller {
4552 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4554 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4555 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4558 - (NSURL *) URLWithURL:(NSURL *)url {
4559 return [Diversion divertURL:url];
4562 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4563 NSURL *url([request URL]);
4564 NSString *host([url host]);
4566 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4568 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4569 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4570 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4571 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4574 @synchronized (HostConfig_) {
4575 token = [TokenHosts_ containsObject:host] || [BridgedHosts_ containsObject:host];
4578 if ([url isCydiaSecure] && token) {
4579 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4580 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4586 - (void) setDelegate:(id)delegate {
4587 [super setDelegate:delegate];
4588 [cydia_ setDelegate:delegate];
4591 - (NSString *) applicationNameForUserAgent {
4592 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4595 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4597 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4598 if (Product_ != nil)
4599 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4605 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4606 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4612 @interface AppCacheController : CydiaWebViewController {
4617 @implementation AppCacheController
4619 - (void) didReceiveMemoryWarning {
4626 @interface NSObject (CydiaScript)
4627 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4630 @implementation NSObject (CydiaScript)
4632 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4638 @implementation NSArray (CydiaScript)
4640 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4641 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4642 for (size_t i(0), e([self count]); i != e; ++i)
4643 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4649 @implementation NSDictionary (CydiaScript)
4651 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4652 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4654 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4661 /* Confirmation Controller {{{ */
4662 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4663 if (!iterator.end())
4664 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4665 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4667 pkgCache::PkgIterator package(dep.TargetPkg());
4670 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4677 @protocol ConfirmationControllerDelegate
4678 - (void) cancelAndClear:(bool)clear;
4679 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4683 @interface ConfirmationController : CydiaWebViewController {
4684 _transient Database *database_;
4686 _H<UIAlertView> essential_;
4688 _H<NSDictionary> changes_;
4689 _H<NSMutableArray> issues_;
4690 _H<NSDictionary> sizes_;
4695 - (id) initWithDatabase:(Database *)database;
4699 @implementation ConfirmationController
4703 RestartSubstrate_ = true;
4704 [delegate_ confirmWithNavigationController:[self navigationController]];
4707 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4708 NSString *context([alert context]);
4710 if ([context isEqualToString:@"remove"]) {
4711 if (button == [alert cancelButtonIndex])
4712 [self dismissModalViewControllerAnimated:YES];
4713 else if (button == [alert firstOtherButtonIndex]) {
4717 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4718 } else if ([context isEqualToString:@"unable"]) {
4719 [self dismissModalViewControllerAnimated:YES];
4720 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4722 [super alertView:alert clickedButtonAtIndex:button];
4726 - (void) _doContinue {
4727 [delegate_ cancelAndClear:NO];
4728 [self dismissModalViewControllerAnimated:YES];
4731 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4732 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4736 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4737 [super webView:view didClearWindowObject:window forFrame:frame];
4739 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4740 (id) changes_, @"changes",
4741 (id) issues_, @"issues",
4742 (id) sizes_, @"sizes",
4744 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4747 - (id) initWithDatabase:(Database *)database {
4748 if ((self = [super init]) != nil) {
4749 database_ = database;
4751 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4752 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4753 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4754 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4755 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4759 pkgCacheFile &cache([database_ cache]);
4760 NSArray *packages([database_ packages]);
4761 pkgDepCache::Policy *policy([database_ policy]);
4763 issues_ = [NSMutableArray arrayWithCapacity:4];
4765 for (Package *package in packages) {
4766 pkgCache::PkgIterator iterator([package iterator]);
4767 NSString *name([package id]);
4769 if ([package broken]) {
4770 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4772 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4774 reasons, @"reasons",
4777 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4781 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4782 pkgCache::DepIterator start;
4783 pkgCache::DepIterator end;
4784 dep.GlobOr(start, end); // ++dep
4786 if (!cache->IsImportantDep(end))
4788 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4791 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4793 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4794 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4795 clauses, @"clauses",
4799 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4801 pkgCache::PkgIterator target(start.TargetPkg());
4802 if (target->ProvidesList != 0)
4803 reason = @"missing";
4805 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4807 reason = @"installed";
4808 installed = [NSString stringWithUTF8String:ver.VerStr()];
4809 } else if (!cache[target].CandidateVerIter(cache).end())
4810 reason = @"uninstalled";
4811 else if (target->ProvidesList == 0)
4812 reason = @"uninstallable";
4814 reason = @"virtual";
4817 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4818 [NSString stringWithUTF8String:start.CompType()], @"operator",
4819 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4822 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4823 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4824 version, @"version",
4826 installed, @"installed",
4829 // yes, seriously. (wtf?)
4837 pkgDepCache::StateCache &state(cache[iterator]);
4839 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4841 if (state.NewInstall())
4842 [installs addObject:name];
4843 // XXX: else if (state.Install())
4844 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4845 [reinstalls addObject:name];
4846 // XXX: move before previous if
4847 else if (state.Upgrade())
4848 [upgrades addObject:name];
4849 else if (state.Downgrade())
4850 [downgrades addObject:name];
4851 else if (!state.Delete())
4852 // XXX: _assert(state.Keep());
4854 else if (special_r(name))
4855 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4856 [NSNull null], @"package",
4857 [NSArray arrayWithObjects:
4858 [NSDictionary dictionaryWithObjectsAndKeys:
4859 @"Conflicts", @"relationship",
4860 [NSArray arrayWithObjects:
4861 [NSDictionary dictionaryWithObjectsAndKeys:
4863 [NSNull null], @"version",
4864 @"installed", @"reason",
4871 if ([package essential])
4873 [removes addObject:name];
4876 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4877 substrate_ |= DepSubstrate(iterator.CurrentVer());
4882 else if (Advanced_) {
4883 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4885 essential_ = [[[UIAlertView alloc]
4886 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4887 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4889 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4891 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4895 [essential_ setContext:@"remove"];
4897 essential_ = [[[UIAlertView alloc]
4898 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4899 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4901 cancelButtonTitle:UCLocalize("OKAY")
4902 otherButtonTitles:nil
4905 [essential_ setContext:@"unable"];
4908 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4909 installs, @"installs",
4910 reinstalls, @"reinstalls",
4911 upgrades, @"upgrades",
4912 downgrades, @"downgrades",
4913 removes, @"removes",
4916 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4917 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4918 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4921 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4925 - (UIBarButtonItem *) leftButton {
4926 return [[[UIBarButtonItem alloc]
4927 initWithTitle:UCLocalize("CANCEL")
4928 style:UIBarButtonItemStylePlain
4930 action:@selector(cancelButtonClicked)
4935 - (void) applyRightButton {
4936 if ([issues_ count] == 0 && ![self isLoading])
4937 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4938 initWithTitle:UCLocalize("CONFIRM")
4939 style:UIBarButtonItemStyleDone
4941 action:@selector(confirmButtonClicked)
4944 [[self navigationItem] setRightBarButtonItem:nil];
4948 - (void) cancelButtonClicked {
4949 [self dismissModalViewControllerAnimated:YES];
4950 [delegate_ cancelAndClear:YES];
4954 - (void) confirmButtonClicked {
4955 if (essential_ != nil)
4965 /* Progress Data {{{ */
4966 @interface CydiaProgressData : NSObject {
4967 _transient id delegate_;
4976 _H<NSMutableArray> events_;
4977 _H<NSString> title_;
4979 _H<NSString> status_;
4980 _H<NSString> finish_;
4985 @implementation CydiaProgressData
4987 + (NSArray *) _attributeKeys {
4988 return [NSArray arrayWithObjects:
5000 - (NSArray *) attributeKeys {
5001 return [[self class] _attributeKeys];
5004 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5005 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5009 if ((self = [super init]) != nil) {
5010 events_ = [NSMutableArray arrayWithCapacity:32];
5014 - (void) setDelegate:(id)delegate {
5015 delegate_ = delegate;
5018 - (void) setPercent:(float)value {
5022 - (NSNumber *) percent {
5023 return [NSNumber numberWithFloat:percent_];
5026 - (void) setCurrent:(float)value {
5030 - (NSNumber *) current {
5031 return [NSNumber numberWithFloat:current_];
5034 - (void) setTotal:(float)value {
5038 - (NSNumber *) total {
5039 return [NSNumber numberWithFloat:total_];
5042 - (void) setSpeed:(float)value {
5046 - (NSNumber *) speed {
5047 return [NSNumber numberWithFloat:speed_];
5050 - (NSArray *) events {
5054 - (void) removeAllEvents {
5055 [events_ removeAllObjects];
5058 - (void) addEvent:(CydiaProgressEvent *)event {
5059 [events_ addObject:event];
5062 - (void) setTitle:(NSString *)text {
5066 - (NSString *) title {
5070 - (void) setFinish:(NSString *)text {
5074 - (NSString *) finish {
5075 return (id) finish_ ?: [NSNull null];
5078 - (void) setRunning:(bool)running {
5082 - (NSNumber *) running {
5083 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5088 /* Progress Controller {{{ */
5089 @interface ProgressController : CydiaWebViewController <
5092 _transient Database *database_;
5093 _H<CydiaProgressData, 1> progress_;
5097 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5099 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5101 - (void) setTitle:(NSString *)title;
5102 - (void) setCancellable:(bool)cancellable;
5106 @implementation ProgressController
5109 [database_ setProgressDelegate:nil];
5113 - (UIBarButtonItem *) leftButton {
5114 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5115 initWithTitle:UCLocalize("CANCEL")
5116 style:UIBarButtonItemStylePlain
5118 action:@selector(cancel)
5119 ] autorelease] : nil;
5122 - (void) updateCancel {
5123 [super applyLeftButton];
5126 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5127 if ((self = [super init]) != nil) {
5128 database_ = database;
5129 delegate_ = delegate;
5131 [database_ setProgressDelegate:self];
5133 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5134 [progress_ setDelegate:self];
5136 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5138 [scroller_ setBackgroundColor:[UIColor blackColor]];
5140 [[self navigationItem] setHidesBackButton:YES];
5142 [self updateCancel];
5146 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5147 [super webView:view didClearWindowObject:window forFrame:frame];
5148 [window setValue:progress_ forKey:@"cydiaProgress"];
5151 - (void) updateProgress {
5152 [self dispatchEvent:@"CydiaProgressUpdate"];
5155 - (void) viewWillAppear:(BOOL)animated {
5156 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5157 [super viewWillAppear:animated];
5161 UpdateExternalStatus(0);
5164 [delegate_ saveState];
5168 [delegate_ returnToCydia];
5172 [delegate_ terminateWithSuccess];
5173 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5174 [delegate_ suspendWithAnimation:YES];
5176 [delegate_ suspend];*/
5188 system("/usr/bin/sbreload");
5194 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5195 SBReboot(SBSSpringBoardServerPort());
5197 reboot2(RB_AUTOBOOT);
5204 - (void) setTitle:(NSString *)title {
5205 [progress_ setTitle:title];
5206 [self updateProgress];
5209 - (UIBarButtonItem *) rightButton {
5210 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5211 initWithTitle:UCLocalize("CLOSE")
5212 style:UIBarButtonItemStylePlain
5214 action:@selector(close)
5218 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5219 UpdateExternalStatus(1);
5221 [progress_ setRunning:true];
5222 [self setTitle:title];
5223 // implicit updateProgress
5225 SHA1SumValue notifyconf; {
5227 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5230 MMap mmap(file, MMap::ReadOnly);
5232 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5233 notifyconf = sha1.Result();
5237 SHA1SumValue springlist; {
5239 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5242 MMap mmap(file, MMap::ReadOnly);
5244 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5245 springlist = sha1.Result();
5249 if (invocation != nil) {
5250 [invocation yieldToSelector:@selector(invoke)];
5251 [self setTitle:@"COMPLETE"];
5256 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5259 MMap mmap(file, MMap::ReadOnly);
5261 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5262 if (!(notifyconf == sha1.Result()))
5269 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5272 MMap mmap(file, MMap::ReadOnly);
5274 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5275 if (!(springlist == sha1.Result()))
5281 if (RestartSubstrate_)
5285 RestartSubstrate_ = false;
5288 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5289 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5290 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5291 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5292 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5296 system("su -c /usr/bin/uicache mobile");
5299 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5301 [progress_ setRunning:false];
5302 [self updateProgress];
5304 [self applyRightButton];
5307 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5308 [progress_ addEvent:event];
5309 [self updateProgress];
5312 - (bool) isProgressCancelled {
5313 return cancel_ == 2;
5318 [self updateCancel];
5321 - (void) setCancellable:(bool)cancellable {
5322 unsigned cancel(cancel_);
5326 else if (cancel_ == 0)
5329 if (cancel != cancel_)
5330 [self updateCancel];
5333 - (void) setProgressCancellable:(NSNumber *)cancellable {
5334 [self setCancellable:[cancellable boolValue]];
5337 - (void) setProgressPercent:(NSNumber *)percent {
5338 [progress_ setPercent:[percent floatValue]];
5339 [self updateProgress];
5342 - (void) setProgressStatus:(NSDictionary *)status {
5343 if (status == nil) {
5344 [progress_ setCurrent:0];
5345 [progress_ setTotal:0];
5346 [progress_ setSpeed:0];
5348 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5350 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5351 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5352 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5355 [self updateProgress];
5361 /* Package Cell {{{ */
5362 @interface PackageCell : CyteTableViewCell <
5363 CyteTableViewCellDelegate
5367 _H<NSString> description_;
5369 _H<NSString> source_;
5371 _H<UIImage> placard_;
5375 - (PackageCell *) init;
5376 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5378 - (void) drawContentRect:(CGRect)rect;
5382 @implementation PackageCell
5384 - (PackageCell *) init {
5385 CGRect frame(CGRectMake(0, 0, 320, 74));
5386 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5387 UIView *content([self contentView]);
5388 CGRect bounds([content bounds]);
5390 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5391 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5392 [content addSubview:content_];
5394 [content_ setDelegate:self];
5395 [content_ setOpaque:YES];
5399 - (NSString *) accessibilityLabel {
5400 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5403 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5404 summarized_ = summary;
5414 [content_ setBackgroundColor:[UIColor whiteColor]];
5418 Source *source = [package source];
5420 icon_ = [package icon];
5422 if (NSString *name = [package name])
5423 name_ = [NSString stringWithString:name];
5425 NSString *description(nil);
5427 if (description == nil && IsWildcat_)
5428 description = [package longDescription];
5429 if (description == nil)
5430 description = [package shortDescription];
5432 if (description != nil)
5433 description_ = [NSString stringWithString:description];
5435 commercial_ = [package isCommercial];
5437 NSString *label = nil;
5438 bool trusted = false;
5440 if (source != nil) {
5441 label = [source label];
5442 trusted = [source trusted];
5443 } else if ([[package id] isEqualToString:@"firmware"])
5444 label = UCLocalize("APPLE");
5446 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5448 NSString *from(label);
5450 NSString *section = [package simpleSection];
5451 if (section != nil && ![section isEqualToString:label]) {
5452 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5453 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5456 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5458 if (NSString *purpose = [package primaryPurpose])
5459 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5464 if (NSString *mode = [package mode]) {
5465 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5466 color = RemovingColor_;
5467 //placard = @"removing";
5469 color = InstallingColor_;
5470 //placard = @"installing";
5473 // XXX: the removing/installing placards are not @2x
5476 color = [UIColor whiteColor];
5478 if ([package installed] != nil)
5479 placard = @"installed";
5484 [content_ setBackgroundColor:color];
5487 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5490 [self setNeedsDisplay];
5491 [content_ setNeedsDisplay];
5494 - (void) drawSummaryContentRect:(CGRect)rect {
5495 bool highlighted(highlighted_);
5496 float width([self bounds].size.width);
5500 rect.size = [(UIImage *) icon_ size];
5502 rect.size.width /= 4;
5503 rect.size.height /= 4;
5505 rect.origin.x = 14 - rect.size.width / 4;
5506 rect.origin.y = 14 - rect.size.height / 4;
5508 [icon_ drawInRect:rect];
5511 if (badge_ != nil) {
5513 rect.size = [(UIImage *) badge_ size];
5515 rect.size.width /= 4;
5516 rect.size.height /= 4;
5518 rect.origin.x = 20 - rect.size.width / 4;
5519 rect.origin.y = 20 - rect.size.height / 4;
5521 [badge_ drawInRect:rect];
5528 UISetColor(commercial_ ? Purple_ : Black_);
5529 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5531 if (placard_ != nil)
5532 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5535 - (void) drawNormalContentRect:(CGRect)rect {
5536 bool highlighted(highlighted_);
5537 float width([self bounds].size.width);
5541 rect.size = [(UIImage *) icon_ size];
5543 rect.size.width /= 2;
5544 rect.size.height /= 2;
5546 rect.origin.x = 25 - rect.size.width / 2;
5547 rect.origin.y = 25 - rect.size.height / 2;
5549 [icon_ drawInRect:rect];
5552 if (badge_ != nil) {
5554 rect.size = [(UIImage *) badge_ size];
5556 rect.size.width /= 2;
5557 rect.size.height /= 2;
5559 rect.origin.x = 36 - rect.size.width / 2;
5560 rect.origin.y = 36 - rect.size.height / 2;
5562 [badge_ drawInRect:rect];
5569 UISetColor(commercial_ ? Purple_ : Black_);
5570 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5571 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5574 UISetColor(commercial_ ? Purplish_ : Gray_);
5575 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5577 if (placard_ != nil)
5578 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5581 - (void) drawContentRect:(CGRect)rect {
5583 [self drawSummaryContentRect:rect];
5585 [self drawNormalContentRect:rect];
5590 /* Section Cell {{{ */
5591 @interface SectionCell : CyteTableViewCell <
5592 CyteTableViewCellDelegate
5594 _H<NSString> basic_;
5595 _H<NSString> section_;
5597 _H<NSString> count_;
5599 _H<UISwitch> switch_;
5603 - (void) setSection:(Section *)section editing:(BOOL)editing;
5607 @implementation SectionCell
5609 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5610 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5611 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5612 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5613 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5615 UIView *content([self contentView]);
5616 CGRect bounds([content bounds]);
5618 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5619 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5620 [content addSubview:content_];
5621 [content_ setBackgroundColor:[UIColor whiteColor]];
5623 [content_ setDelegate:self];
5627 - (void) onSwitch:(id)sender {
5628 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5629 if (metadata == nil) {
5630 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5631 [Sections_ setObject:metadata forKey:basic_];
5634 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5638 - (void) setSection:(Section *)section editing:(BOOL)editing {
5639 if (editing != editing_) {
5641 [switch_ removeFromSuperview];
5643 [self addSubview:switch_];
5652 if (section == nil) {
5653 name_ = UCLocalize("ALL_PACKAGES");
5656 basic_ = [section name];
5657 section_ = [section localized];
5659 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5660 count_ = [NSString stringWithFormat:@"%d", [section count]];
5663 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5666 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5667 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5669 [content_ setNeedsDisplay];
5672 - (void) setFrame:(CGRect)frame {
5673 [super setFrame:frame];
5675 CGRect rect([switch_ frame]);
5676 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5679 - (NSString *) accessibilityLabel {
5683 - (void) drawContentRect:(CGRect)rect {
5684 bool highlighted(highlighted_ && !editing_);
5686 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5691 float width(rect.size.width);
5697 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5699 CGSize size = [count_ sizeWithFont:Font14_];
5703 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5709 /* File Table {{{ */
5710 @interface FileTable : CyteViewController <
5711 UITableViewDataSource,
5714 _transient Database *database_;
5715 _H<Package> package_;
5717 _H<NSMutableArray> files_;
5718 _H<UITableView, 2> list_;
5721 - (id) initWithDatabase:(Database *)database;
5722 - (void) setPackage:(Package *)package;
5726 @implementation FileTable
5728 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5729 return files_ == nil ? 0 : [files_ count];
5732 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5736 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5737 static NSString *reuseIdentifier = @"Cell";
5739 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5741 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5742 [cell setFont:[UIFont systemFontOfSize:16]];
5744 [cell setText:[files_ objectAtIndex:indexPath.row]];
5745 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5750 - (NSURL *) navigationURL {
5751 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5755 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5757 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5758 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5759 [list_ setRowHeight:24.0f];
5760 [(UITableView *) list_ setDataSource:self];
5761 [list_ setDelegate:self];
5762 [[self view] addSubview:list_];
5765 - (void) viewDidLoad {
5766 [super viewDidLoad];
5768 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5771 - (void) releaseSubviews {
5777 [super releaseSubviews];
5780 - (id) initWithDatabase:(Database *)database {
5781 if ((self = [super init]) != nil) {
5782 database_ = database;
5786 - (void) setPackage:(Package *)package {
5790 files_ = [NSMutableArray arrayWithCapacity:32];
5792 if (package != nil) {
5794 name_ = [package id];
5796 if (NSArray *files = [package files])
5797 [files_ addObjectsFromArray:files];
5799 if ([files_ count] != 0) {
5800 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5801 [files_ removeObjectAtIndex:0];
5802 [files_ sortUsingSelector:@selector(compareByPath:)];
5804 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5805 [stack addObject:@"/"];
5807 for (int i(0), e([files_ count]); i != e; ++i) {
5808 NSString *file = [files_ objectAtIndex:i];
5809 while (![file hasPrefix:[stack lastObject]])
5810 [stack removeLastObject];
5811 NSString *directory = [stack lastObject];
5812 [stack addObject:[file stringByAppendingString:@"/"]];
5813 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5814 ([stack count] - 2) * 3, "",
5815 [file substringFromIndex:[directory length]]
5824 - (void) reloadData {
5827 [self setPackage:[database_ packageWithName:name_]];
5832 /* Package Controller {{{ */
5833 @interface CYPackageController : CydiaWebViewController <
5834 UIActionSheetDelegate
5836 _transient Database *database_;
5837 _H<Package> package_;
5840 _H<NSMutableArray> buttons_;
5841 _H<UIBarButtonItem> button_;
5844 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5848 @implementation CYPackageController
5850 - (NSURL *) navigationURL {
5851 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5854 /* XXX: this is not safe at all... localization of /fail/ */
5855 - (void) _clickButtonWithName:(NSString *)name {
5856 if ([name isEqualToString:UCLocalize("CLEAR")])
5857 [delegate_ clearPackage:package_];
5858 else if ([name isEqualToString:UCLocalize("INSTALL")])
5859 [delegate_ installPackage:package_];
5860 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5861 [delegate_ installPackage:package_];
5862 else if ([name isEqualToString:UCLocalize("REMOVE")])
5863 [delegate_ removePackage:package_];
5864 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5865 [delegate_ installPackage:package_];
5866 else _assert(false);
5869 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5870 NSString *context([sheet context]);
5872 if ([context isEqualToString:@"modify"]) {
5873 if (button != [sheet cancelButtonIndex]) {
5874 NSString *buttonName = [buttons_ objectAtIndex:button];
5875 [self _clickButtonWithName:buttonName];
5878 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5882 - (bool) _allowJavaScriptPanel {
5887 - (void) _customButtonClicked {
5888 int count([buttons_ count]);
5893 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5895 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5896 [buttons addObjectsFromArray:buttons_];
5898 UIActionSheet *sheet = [[[UIActionSheet alloc]
5901 cancelButtonTitle:nil
5902 destructiveButtonTitle:nil
5903 otherButtonTitles:nil
5906 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5908 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5909 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5911 [sheet setContext:@"modify"];
5913 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5917 // We don't want to allow non-commercial packages to do custom things to the install button,
5918 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5919 - (void) customButtonClicked {
5921 [super customButtonClicked];
5923 [self _customButtonClicked];
5926 - (void) reloadButtonClicked {
5927 // Don't reload a commerical package by tapping the loading button,
5928 // but if it's not an Install button, we should forward it on.
5929 if (![package_ uninstalled])
5930 [self _customButtonClicked];
5933 - (void) applyLoadingTitle {
5934 // Don't show "Loading" as the title. Ever.
5937 - (UIBarButtonItem *) rightButton {
5942 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5943 if ((self = [super init]) != nil) {
5944 database_ = database;
5945 buttons_ = [NSMutableArray arrayWithCapacity:4];
5946 name_ = name == nil ? @"" : [NSString stringWithString:name];
5947 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5951 - (void) reloadData {
5954 package_ = [database_ packageWithName:name_];
5956 [buttons_ removeAllObjects];
5958 if (package_ != nil) {
5959 [(Package *) package_ parse];
5961 commercial_ = [package_ isCommercial];
5963 if ([package_ mode] != nil)
5964 [buttons_ addObject:UCLocalize("CLEAR")];
5965 if ([package_ source] == nil);
5966 else if ([package_ upgradableAndEssential:NO])
5967 [buttons_ addObject:UCLocalize("UPGRADE")];
5968 else if ([package_ uninstalled])
5969 [buttons_ addObject:UCLocalize("INSTALL")];
5971 [buttons_ addObject:UCLocalize("REINSTALL")];
5972 if (![package_ uninstalled])
5973 [buttons_ addObject:UCLocalize("REMOVE")];
5977 switch ([buttons_ count]) {
5978 case 0: title = nil; break;
5979 case 1: title = [buttons_ objectAtIndex:0]; break;
5980 default: title = UCLocalize("MODIFY"); break;
5983 button_ = [[[UIBarButtonItem alloc]
5985 style:UIBarButtonItemStylePlain
5987 action:@selector(customButtonClicked)
5991 - (bool) isLoading {
5992 return commercial_ ? [super isLoading] : false;
5998 /* Package List Controller {{{ */
5999 @interface PackageListController : CyteViewController <
6000 UITableViewDataSource,
6003 _transient Database *database_;
6005 _H<NSArray> packages_;
6006 _H<NSMutableArray> sections_;
6007 _H<UITableView, 2> list_;
6008 _H<NSMutableArray> index_;
6009 _H<NSMutableDictionary> indices_;
6010 _H<NSString> title_;
6011 unsigned reloading_;
6014 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6015 - (void) setDelegate:(id)delegate;
6016 - (void) resetCursor;
6021 @implementation PackageListController
6023 - (bool) isSummarized {
6027 - (bool) showsSections {
6031 - (void) deselectWithAnimation:(BOOL)animated {
6032 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6035 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6036 CGRect base = [[self view] bounds];
6037 base.size.height -= bounds.size.height;
6038 base.origin = [list_ frame].origin;
6040 [UIView beginAnimations:nil context:NULL];
6041 [UIView setAnimationBeginsFromCurrentState:YES];
6042 [UIView setAnimationCurve:curve];
6043 [UIView setAnimationDuration:duration];
6044 [list_ setFrame:base];
6045 [UIView commitAnimations];
6048 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6049 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6052 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6053 [self resizeForKeyboardBounds:bounds duration:0];
6056 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6057 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6058 *curve = UIViewAnimationCurveEaseInOut;
6060 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6062 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6065 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6068 - (void) keyboardWillShow:(NSNotification *)notification {
6071 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6072 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6074 NSTimeInterval duration;
6075 UIViewAnimationCurve curve;
6076 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6078 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);
6079 UIViewController *base = self;
6080 while ([base parentViewController] != nil)
6081 base = [base parentViewController];
6082 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6083 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6085 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6086 intersection.size.height += CYStatusBarHeight([self interfaceOrientation]);
6088 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6091 - (void) keyboardWillHide:(NSNotification *)notification {
6092 NSTimeInterval duration;
6093 UIViewAnimationCurve curve;
6094 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6096 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6099 - (void) viewWillAppear:(BOOL)animated {
6100 [super viewWillAppear:animated];
6102 [self resizeForKeyboardBounds:CGRectZero];
6103 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6104 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6107 - (void) viewWillDisappear:(BOOL)animated {
6108 [super viewWillDisappear:animated];
6110 [self resizeForKeyboardBounds:CGRectZero];
6111 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6112 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6115 - (void) viewDidAppear:(BOOL)animated {
6116 [super viewDidAppear:animated];
6117 [self deselectWithAnimation:animated];
6120 - (void) didSelectPackage:(Package *)package {
6121 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6122 [view setDelegate:delegate_];
6123 [[self navigationController] pushViewController:view animated:YES];
6126 #if TryIndexedCollation
6127 + (BOOL) hasIndexedCollation {
6128 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6132 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6133 NSInteger count([sections_ count]);
6134 return count == 0 ? 1 : count;
6137 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6138 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6140 return [[sections_ objectAtIndex:section] name];
6143 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6144 if ([sections_ count] == 0)
6146 return [[sections_ objectAtIndex:section] count];
6149 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6150 @synchronized (database_) {
6151 if ([database_ era] != era_)
6154 Section *section([sections_ objectAtIndex:[path section]]);
6155 NSInteger row([path row]);
6156 Package *package([packages_ objectAtIndex:([section row] + row)]);
6157 return [[package retain] autorelease];
6160 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6161 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6163 cell = [[[PackageCell alloc] init] autorelease];
6165 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6166 [cell setPackage:package asSummary:[self isSummarized]];
6170 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6171 Package *package([self packageAtIndexPath:path]);
6172 package = [database_ packageWithName:[package id]];
6173 [self didSelectPackage:package];
6176 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6177 if (![self showsSections])
6183 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6184 #if TryIndexedCollation
6185 if ([[self class] hasIndexedCollation]) {
6186 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6193 - (void) updateHeight {
6194 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6197 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6198 if ((self = [super init]) != nil) {
6199 database_ = database;
6200 title_ = [title copy];
6201 [[self navigationItem] setTitle:title_];
6206 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6208 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6209 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6210 [[self view] addSubview:list_];
6212 // XXX: is 20 the most optimal number here?
6213 [list_ setSectionIndexMinimumDisplayRowCount:20];
6215 [(UITableView *) list_ setDataSource:self];
6216 [list_ setDelegate:self];
6218 [self updateHeight];
6221 - (void) releaseSubviews {
6229 [super releaseSubviews];
6232 - (void) setDelegate:(id)delegate {
6233 delegate_ = delegate;
6236 - (bool) shouldYield {
6240 - (bool) shouldBlock {
6244 - (NSMutableArray *) _reloadPackages {
6245 @synchronized (database_) {
6246 era_ = [database_ era];
6247 NSArray *packages([database_ packages]);
6249 return [NSMutableArray arrayWithArray:packages];
6252 - (void) _reloadData {
6253 if (reloading_ != 0) {
6260 if ([self shouldYield]) {
6264 if (![self shouldBlock])
6267 hud = [delegate_ addProgressHUD];
6268 [hud setText:UCLocalize("LOADING")];
6272 packages = [self yieldToSelector:@selector(_reloadPackages)];
6275 [delegate_ removeProgressHUD:hud];
6276 } while (reloading_ == 2);
6280 packages = [self _reloadPackages];
6283 packages_ = packages;
6285 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6286 sections_ = [NSMutableArray arrayWithCapacity:16];
6288 Section *section = nil;
6290 #if TryIndexedCollation
6291 if ([[self class] hasIndexedCollation]) {
6292 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6294 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6295 NSArray *titles = [collation sectionIndexTitles];
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 = [collation sectionForObject:package collationStringSelector:@selector(name)];
6308 while (secidx < index) {
6311 _profile(PackageTable$reloadData$Section$Allocate)
6312 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6315 _profile(PackageTable$reloadData$Section$Add)
6316 [sections_ addObject:section];
6320 [section addToCount];
6326 index_ = [NSMutableArray arrayWithCapacity:32];
6328 bool sectioned([self showsSections]);
6330 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6331 [sections_ addObject:section];
6334 _profile(PackageTable$reloadData$Section)
6335 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6339 _profile(PackageTable$reloadData$Section$Package)
6340 package = [packages_ objectAtIndex:offset];
6341 index = [package index];
6344 if (sectioned && (section == nil || [section index] != index)) {
6345 _profile(PackageTable$reloadData$Section$Allocate)
6346 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6349 [index_ addObject:[section name]];
6350 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6352 _profile(PackageTable$reloadData$Section$Add)
6353 [sections_ addObject:section];
6357 [section addToCount];
6362 [self updateHeight];
6364 _profile(PackageTable$reloadData$List)
6365 [(UITableView *) list_ setDataSource:self];
6370 - (void) reloadData {
6373 if ([self shouldYield])
6374 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6379 - (void) resetCursor {
6380 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6383 - (void) clearData {
6384 [self updateHeight];
6386 [list_ setDataSource:nil];
6394 /* Filtered Package List Controller {{{ */
6395 @interface FilteredPackageListController : PackageListController {
6398 _H<NSObject> object_;
6401 - (void) setObject:(id)object;
6402 - (void) setObject:(id)object forFilter:(SEL)filter;
6405 - (void) setFilter:(SEL)filter;
6407 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6411 @implementation FilteredPackageListController
6417 - (void) setFilter:(SEL)filter {
6418 @synchronized (self) {
6421 /* XXX: this is an unsafe optimization of doomy hell */
6422 Method method(class_getInstanceMethod([Package class], filter));
6423 _assert(method != NULL);
6424 imp_ = method_getImplementation(method);
6425 _assert(imp_ != NULL);
6428 - (void) setObject:(id)object {
6429 @synchronized (self) {
6433 - (void) setObject:(id)object forFilter:(SEL)filter {
6434 @synchronized (self) {
6435 [self setFilter:filter];
6436 [self setObject:object];
6439 - (NSMutableArray *) _reloadPackages {
6440 @synchronized (database_) {
6441 era_ = [database_ era];
6442 NSArray *packages([database_ packages]);
6444 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6448 _H<NSObject> object;
6450 @synchronized (self) {
6456 _profile(PackageTable$reloadData$Filter)
6457 for (Package *package in packages)
6458 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6459 [filtered addObject:package];
6465 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6466 if ((self = [super initWithDatabase:database title:title]) != nil) {
6467 [self setFilter:filter];
6468 [self setObject:object];
6475 /* Home Controller {{{ */
6476 @interface HomeController : CydiaWebViewController {
6481 @implementation HomeController
6484 if ((self = [super init]) != nil) {
6485 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6490 - (NSURL *) navigationURL {
6491 return [NSURL URLWithString:@"cydia://home"];
6494 - (void) didReceiveMemoryWarning {
6497 - (void) aboutButtonClicked {
6498 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6500 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6501 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6502 [alert setCancelButtonIndex:0];
6505 @"Copyright \u00a9 2008-2011\n"
6508 "Jay Freeman (saurik)\n"
6509 "saurik@saurik.com\n"
6510 "http://www.saurik.com/"
6516 - (UIBarButtonItem *) leftButton {
6517 return [[[UIBarButtonItem alloc]
6518 initWithTitle:UCLocalize("ABOUT")
6519 style:UIBarButtonItemStylePlain
6521 action:@selector(aboutButtonClicked)
6527 /* Manage Controller {{{ */
6528 @interface ManageController : CydiaWebViewController {
6531 - (void) queueStatusDidChange;
6535 @implementation ManageController
6538 if ((self = [super init]) != nil) {
6539 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6543 - (NSURL *) navigationURL {
6544 return [NSURL URLWithString:@"cydia://manage"];
6547 - (UIBarButtonItem *) leftButton {
6548 return [[[UIBarButtonItem alloc]
6549 initWithTitle:UCLocalize("SETTINGS")
6550 style:UIBarButtonItemStylePlain
6552 action:@selector(settingsButtonClicked)
6556 - (void) settingsButtonClicked {
6557 [delegate_ showSettings];
6560 - (void) queueButtonClicked {
6564 - (UIBarButtonItem *) customButton {
6565 return Queuing_ ? [[[UIBarButtonItem alloc]
6566 initWithTitle:UCLocalize("QUEUE")
6567 style:UIBarButtonItemStyleDone
6569 action:@selector(queueButtonClicked)
6570 ] autorelease] : [super customButton];
6573 - (void) queueStatusDidChange {
6574 [self applyRightButton];
6577 - (bool) isLoading {
6578 return !Queuing_ && [super isLoading];
6584 /* Refresh Bar {{{ */
6585 @interface RefreshBar : UINavigationBar {
6586 _H<UIProgressIndicator> indicator_;
6587 _H<UITextLabel> prompt_;
6588 _H<UIProgressBar> progress_;
6589 _H<UINavigationButton> cancel_;
6594 @implementation RefreshBar
6596 - (void) positionViews {
6597 CGRect frame = [cancel_ frame];
6598 frame.size = [cancel_ sizeThatFits:frame.size];
6599 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6600 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6601 [cancel_ setFrame:frame];
6603 CGSize prgsize = {75, 100};
6605 [self frame].size.width - prgsize.width - 10,
6606 ([self frame].size.height - prgsize.height) / 2
6608 [progress_ setFrame:prgrect];
6610 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6611 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6612 CGRect indrect = {{indoffset, indoffset}, indsize};
6613 [indicator_ setFrame:indrect];
6615 CGSize prmsize = {215, indsize.height + 4};
6617 indoffset * 2 + indsize.width,
6618 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6620 [prompt_ setFrame:prmrect];
6623 - (void) setFrame:(CGRect)frame {
6624 [super setFrame:frame];
6625 [self positionViews];
6628 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6629 if ((self = [super initWithFrame:frame]) != nil) {
6630 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6632 [self setBarStyle:UIBarStyleBlack];
6634 UIBarStyle barstyle([self _barStyle:NO]);
6635 bool ugly(barstyle == UIBarStyleDefault);
6637 UIProgressIndicatorStyle style = ugly ?
6638 UIProgressIndicatorStyleMediumBrown :
6639 UIProgressIndicatorStyleMediumWhite;
6641 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6642 [(UIProgressIndicator *) indicator_ setStyle:style];
6643 [indicator_ startAnimation];
6644 [self addSubview:indicator_];
6646 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6647 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6648 [prompt_ setBackgroundColor:[UIColor clearColor]];
6649 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6650 [self addSubview:prompt_];
6652 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6653 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6654 [(UIProgressBar *) progress_ setStyle:0];
6655 [self addSubview:progress_];
6657 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6658 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6659 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6660 [cancel_ setBarStyle:barstyle];
6662 [self positionViews];
6666 - (void) setCancellable:(bool)cancellable {
6668 [self addSubview:cancel_];
6670 [cancel_ removeFromSuperview];
6674 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6675 [progress_ setProgress:0];
6679 [self setCancellable:NO];
6682 - (void) setPrompt:(NSString *)prompt {
6683 [prompt_ setText:prompt];
6686 - (void) setProgress:(float)progress {
6687 [progress_ setProgress:progress];
6693 /* Cydia Navigation Controller Interface {{{ */
6694 @interface UINavigationController (Cydia)
6696 - (NSArray *) navigationURLCollection;
6697 - (void) unloadData;
6702 /* Cydia Tab Bar Controller {{{ */
6703 @interface CYTabBarController : UITabBarController <
6704 UITabBarControllerDelegate,
6707 _transient Database *database_;
6708 _H<RefreshBar, 1> refreshbar_;
6712 // XXX: ok, "updatedelegate_"?...
6713 _transient NSObject<CydiaDelegate> *updatedelegate_;
6715 _H<UIViewController> remembered_;
6716 _transient UIViewController *transient_;
6719 - (NSArray *) navigationURLCollection;
6720 - (void) dropBar:(BOOL)animated;
6721 - (void) beginUpdate;
6722 - (void) raiseBar:(BOOL)animated;
6724 - (void) unloadData;
6728 @implementation CYTabBarController
6730 - (void) setUnselectedViewController:(UIViewController *)transient {
6731 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6732 if (transient != nil) {
6733 if (transient_ == nil)
6734 remembered_ = [controllers objectAtIndex:0];
6735 transient_ = transient;
6736 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6737 [controllers replaceObjectAtIndex:0 withObject:transient_];
6738 [self setSelectedIndex:0];
6739 [self setViewControllers:controllers];
6740 [self concealTabBarSelection];
6741 } else if (remembered_ != nil) {
6742 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6743 transient_ = transient;
6744 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6746 [self setViewControllers:controllers];
6747 [self revealTabBarSelection];
6751 - (UIViewController *) unselectedViewController {
6755 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6756 if ([self unselectedViewController])
6757 [self setUnselectedViewController:nil];
6760 - (NSArray *) navigationURLCollection {
6761 NSMutableArray *items([NSMutableArray array]);
6763 // XXX: Should this deal with transient view controllers?
6764 for (id navigation in [self viewControllers]) {
6765 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6767 [items addObject:stack];
6773 - (void) unloadData {
6776 for (UINavigationController *controller in [self viewControllers])
6777 [controller unloadData];
6779 if (UIViewController *selected = [self selectedViewController])
6780 [selected reloadData];
6782 if (UIViewController *unselected = [self unselectedViewController]) {
6783 [unselected unloadData];
6784 [unselected reloadData];
6789 [[NSNotificationCenter defaultCenter] removeObserver:self];
6794 - (id) initWithDatabase:(Database *)database {
6795 if ((self = [super init]) != nil) {
6796 database_ = database;
6797 [self setDelegate:self];
6799 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6800 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6802 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6806 - (void) setUpdate:(NSDate *)date {
6810 - (void) beginUpdate {
6811 [(RefreshBar *) refreshbar_ start];
6814 [updatedelegate_ retainNetworkActivityIndicator];
6818 detachNewThreadSelector:@selector(performUpdate)
6824 - (void) performUpdate {
6825 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6828 status.setDelegate(self);
6829 [database_ updateWithStatus:status];
6832 performSelectorOnMainThread:@selector(completeUpdate)
6840 - (void) stopUpdateWithSelector:(SEL)selector {
6842 [updatedelegate_ releaseNetworkActivityIndicator];
6844 [self raiseBar:YES];
6847 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6850 - (void) completeUpdate {
6853 [self stopUpdateWithSelector:@selector(reloadData)];
6856 - (void) cancelUpdate {
6857 [self stopUpdateWithSelector:@selector(updateData)];
6860 - (void) cancelPressed {
6861 [self cancelUpdate];
6868 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6869 [refreshbar_ setPrompt:[event compoundMessage]];
6872 - (bool) isProgressCancelled {
6876 - (void) setProgressCancellable:(NSNumber *)cancellable {
6877 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6880 - (void) setProgressPercent:(NSNumber *)percent {
6881 [refreshbar_ setProgress:[percent floatValue]];
6884 - (void) setProgressStatus:(NSDictionary *)status {
6886 [self setProgressPercent:[status objectForKey:@"Percent"]];
6889 - (void) setUpdateDelegate:(id)delegate {
6890 updatedelegate_ = delegate;
6893 - (UIView *) transitionView {
6894 if ([self respondsToSelector:@selector(_transitionView)])
6895 return [self _transitionView];
6897 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6900 - (void) dropBar:(BOOL)animated {
6905 UIView *transition([self transitionView]);
6906 [[self view] addSubview:refreshbar_];
6908 CGRect barframe([refreshbar_ frame]);
6910 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6911 barframe.origin.y = CYStatusBarHeight([self interfaceOrientation]);
6913 barframe.origin.y = 0;
6915 [refreshbar_ setFrame:barframe];
6918 [UIView beginAnimations:nil context:NULL];
6920 CGRect viewframe = [transition frame];
6921 viewframe.origin.y += barframe.size.height;
6922 viewframe.size.height -= barframe.size.height;
6923 [transition setFrame:viewframe];
6926 [UIView commitAnimations];
6928 // Ensure bar has the proper width for our view, it might have changed
6929 barframe.size.width = viewframe.size.width;
6930 [refreshbar_ setFrame:barframe];
6933 - (void) raiseBar:(BOOL)animated {
6938 UIView *transition([self transitionView]);
6939 [refreshbar_ removeFromSuperview];
6941 CGRect barframe([refreshbar_ frame]);
6944 [UIView beginAnimations:nil context:NULL];
6946 CGRect viewframe = [transition frame];
6947 viewframe.origin.y -= barframe.size.height;
6948 viewframe.size.height += barframe.size.height;
6949 [transition setFrame:viewframe];
6952 [UIView commitAnimations];
6955 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6956 bool dropped(dropped_);
6961 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6967 - (void) statusBarFrameChanged:(NSNotification *)notification {
6977 /* Cydia Navigation Controller Implementation {{{ */
6978 @implementation UINavigationController (Cydia)
6980 - (NSArray *) navigationURLCollection {
6981 NSMutableArray *stack([NSMutableArray array]);
6983 for (CyteViewController *controller in [self viewControllers]) {
6984 NSString *url = [[controller navigationURL] absoluteString];
6986 [stack addObject:url];
6992 - (void) reloadData {
6995 UIViewController *visible([self visibleViewController]);
6997 [visible reloadData];
6999 // on the iPad, this view controller is ALSO visible. :(
7001 if (UIViewController *top = [self topViewController])
7006 - (void) unloadData {
7007 for (CyteViewController *page in [self viewControllers])
7016 /* Cydia:// Protocol {{{ */
7017 @interface CydiaURLProtocol : NSURLProtocol {
7022 @implementation CydiaURLProtocol
7024 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7025 NSURL *url([request URL]);
7029 NSString *scheme([[url scheme] lowercaseString]);
7030 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7032 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7038 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7042 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7043 id<NSURLProtocolClient> client([self client]);
7045 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7047 NSData *data(UIImagePNGRepresentation(icon));
7049 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7050 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7051 [client URLProtocol:self didLoadData:data];
7052 [client URLProtocolDidFinishLoading:self];
7056 - (void) startLoading {
7057 id<NSURLProtocolClient> client([self client]);
7058 NSURLRequest *request([self request]);
7060 NSURL *url([request URL]);
7061 NSString *href([url absoluteString]);
7062 NSString *scheme([[url scheme] lowercaseString]);
7066 if ([scheme isEqualToString:@"cydia"])
7067 path = [href substringFromIndex:8];
7068 else if ([scheme isEqualToString:@"about"])
7069 path = [href substringFromIndex:12];
7070 else _assert(false);
7072 NSRange slash([path rangeOfString:@"/"]);
7075 if (slash.location == NSNotFound) {
7079 command = [path substringToIndex:slash.location];
7080 path = [path substringFromIndex:(slash.location + 1)];
7083 Database *database([Database sharedInstance]);
7085 if ([command isEqualToString:@"package-icon"]) {
7088 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7089 Package *package([database packageWithName:path]);
7093 UIImage *icon([package icon]);
7094 [self _returnPNGWithImage:icon forRequest:request];
7095 } else if ([command isEqualToString:@"source-icon"]) {
7098 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7099 NSString *source(Simplify(path));
7100 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7102 icon = [UIImage applicationImageNamed:@"unknown.png"];
7103 [self _returnPNGWithImage:icon forRequest:request];
7104 } else if ([command isEqualToString:@"uikit-image"]) {
7107 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7108 UIImage *icon(_UIImageWithName(path));
7109 [self _returnPNGWithImage:icon forRequest:request];
7110 } else if ([command isEqualToString:@"section-icon"]) {
7113 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7114 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7116 icon = [UIImage applicationImageNamed:@"unknown.png"];
7117 [self _returnPNGWithImage:icon forRequest:request];
7119 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7123 - (void) stopLoading {
7129 /* Section Controller {{{ */
7130 @interface SectionController : FilteredPackageListController {
7131 _H<NSString> section_;
7134 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7138 @implementation SectionController
7140 - (NSURL *) navigationURL {
7141 NSString *name = section_;
7145 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7148 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7151 title = UCLocalize("ALL_PACKAGES");
7152 else if (![name isEqual:@""])
7153 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7155 title = UCLocalize("NO_SECTION");
7157 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7164 /* Sections Controller {{{ */
7165 @interface SectionsController : CyteViewController <
7166 UITableViewDataSource,
7169 _transient Database *database_;
7170 _H<NSMutableArray> sections_;
7171 _H<NSMutableArray> filtered_;
7172 _H<UITableView, 2> list_;
7175 - (id) initWithDatabase:(Database *)database;
7176 - (void) editButtonClicked;
7180 @implementation SectionsController
7182 - (NSURL *) navigationURL {
7183 return [NSURL URLWithString:@"cydia://sections"];
7186 - (void) updateNavigationItem {
7187 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7188 if ([sections_ count] == 0) {
7189 [[self navigationItem] setRightBarButtonItem:nil];
7191 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7192 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7194 action:@selector(editButtonClicked)
7195 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7199 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7200 [super setEditing:editing animated:animated];
7205 [delegate_ updateData];
7207 [self updateNavigationItem];
7210 - (void) viewDidAppear:(BOOL)animated {
7211 [super viewDidAppear:animated];
7212 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7215 - (void) viewWillDisappear:(BOOL)animated {
7216 [super viewWillDisappear:animated];
7217 if ([self isEditing]) [self setEditing:NO];
7220 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7221 Section *section = nil;
7222 int index = [indexPath row];
7223 if (![self isEditing]) {
7226 section = [filtered_ objectAtIndex:index];
7228 section = [sections_ objectAtIndex:index];
7233 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7234 if ([self isEditing])
7235 return [sections_ count];
7237 return [filtered_ count] + 1;
7240 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7244 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7245 static NSString *reuseIdentifier = @"SectionCell";
7247 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7249 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7251 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7256 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7257 if ([self isEditing])
7260 Section *section = [self sectionAtIndexPath:indexPath];
7262 SectionController *controller = [[[SectionController alloc]
7263 initWithDatabase:database_
7264 section:[section name]
7266 [controller setDelegate:delegate_];
7268 [[self navigationController] pushViewController:controller animated:YES];
7272 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7274 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7275 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7276 [list_ setRowHeight:45.0f];
7277 [(UITableView *) list_ setDataSource:self];
7278 [list_ setDelegate:self];
7279 [[self view] addSubview:list_];
7282 - (void) viewDidLoad {
7283 [super viewDidLoad];
7285 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7288 - (void) releaseSubviews {
7294 [super releaseSubviews];
7297 - (id) initWithDatabase:(Database *)database {
7298 if ((self = [super init]) != nil) {
7299 database_ = database;
7303 - (void) reloadData {
7306 NSArray *packages = [database_ packages];
7308 sections_ = [NSMutableArray arrayWithCapacity:16];
7309 filtered_ = [NSMutableArray arrayWithCapacity:16];
7311 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7314 for (Package *package in packages) {
7315 NSString *name([package section]);
7316 NSString *key(name == nil ? @"" : name);
7320 _profile(SectionsView$reloadData$Section)
7321 section = [sections objectForKey:key];
7322 if (section == nil) {
7323 _profile(SectionsView$reloadData$Section$Allocate)
7324 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7325 [sections setObject:section forKey:key];
7330 [section addToCount];
7332 _profile(SectionsView$reloadData$Filter)
7333 if (![package valid] || ![package visible])
7341 [sections_ addObjectsFromArray:[sections allValues]];
7343 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7345 for (Section *section in (id) sections_) {
7346 size_t count([section row]);
7350 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7351 [section setCount:count];
7352 [filtered_ addObject:section];
7355 [self updateNavigationItem];
7360 - (void) editButtonClicked {
7361 [self setEditing:![self isEditing] animated:YES];
7367 /* Changes Controller {{{ */
7368 @interface ChangesController : CyteViewController <
7369 UITableViewDataSource,
7372 _transient Database *database_;
7374 _H<NSArray> packages_;
7375 _H<NSMutableArray> sections_;
7376 _H<UITableView, 2> list_;
7380 - (id) initWithDatabase:(Database *)database;
7384 @implementation ChangesController
7386 - (NSURL *) navigationURL {
7387 return [NSURL URLWithString:@"cydia://changes"];
7390 - (void) viewDidAppear:(BOOL)animated {
7391 [super viewDidAppear:animated];
7392 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7395 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7396 NSInteger count([sections_ count]);
7397 return count == 0 ? 1 : count;
7400 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7401 if ([sections_ count] == 0)
7403 return [[sections_ objectAtIndex:section] name];
7406 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7407 if ([sections_ count] == 0)
7409 return [[sections_ objectAtIndex:section] count];
7412 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7413 @synchronized (database_) {
7414 if ([database_ era] != era_)
7417 NSUInteger sectionIndex([path section]);
7418 if (sectionIndex >= [sections_ count])
7420 Section *section([sections_ objectAtIndex:sectionIndex]);
7421 NSInteger row([path row]);
7422 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7425 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7426 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7428 cell = [[[PackageCell alloc] init] autorelease];
7430 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7431 [cell setPackage:package asSummary:false];
7435 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7436 Package *package([self packageAtIndexPath:path]);
7437 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7438 [view setDelegate:delegate_];
7439 [[self navigationController] pushViewController:view animated:YES];
7443 - (void) refreshButtonClicked {
7444 [delegate_ beginUpdate];
7445 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7448 - (void) upgradeButtonClicked {
7449 [delegate_ distUpgrade];
7450 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7454 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7456 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7457 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7458 [list_ setRowHeight:73];
7459 [(UITableView *) list_ setDataSource:self];
7460 [list_ setDelegate:self];
7461 [[self view] addSubview:list_];
7464 - (void) viewDidLoad {
7465 [super viewDidLoad];
7467 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7470 - (void) releaseSubviews {
7476 [super releaseSubviews];
7479 - (id) initWithDatabase:(Database *)database {
7480 if ((self = [super init]) != nil) {
7481 database_ = database;
7485 - (NSMutableArray *) _reloadPackages {
7486 @synchronized (database_) {
7487 era_ = [database_ era];
7488 NSArray *packages([database_ packages]);
7490 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7493 _profile(ChangesController$_reloadPackages$Filter)
7494 for (Package *package in packages)
7495 if ([package upgradableAndEssential:YES] || [package visible])
7496 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7499 _profile(ChangesController$_reloadPackages$radixSort)
7500 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7507 - (void) _reloadData {
7512 UIProgressHUD *hud([delegate_ addProgressHUD]);
7513 [hud setText:UCLocalize("LOADING")];
7514 //NSLog(@"HUD:%@::%@", delegate_, hud);
7515 packages = [self yieldToSelector:@selector(_reloadPackages)];
7516 [delegate_ removeProgressHUD:hud];
7518 packages = [self _reloadPackages];
7521 @synchronized (database_) {
7522 if (era_ != [database_ era])
7525 packages_ = packages;
7526 sections_ = [NSMutableArray arrayWithCapacity:16];
7528 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7529 Section *ignored = nil;
7530 Section *section = nil;
7534 bool unseens = false;
7536 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7538 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7539 Package *package = [packages_ objectAtIndex:offset];
7541 BOOL uae = [package upgradableAndEssential:YES];
7545 time_t seen([package seen]);
7547 if (section == nil || last != seen) {
7551 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7554 _profile(ChangesController$reloadData$Allocate)
7555 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7556 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7557 [sections_ addObject:section];
7561 [section addToCount];
7562 } else if ([package ignored]) {
7563 if (ignored == nil) {
7564 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7566 [ignored addToCount];
7569 [upgradable addToCount];
7574 CFRelease(formatter);
7577 Section *last = [sections_ lastObject];
7578 size_t count = [last count];
7579 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7580 [sections_ removeLastObject];
7583 if ([ignored count] != 0)
7584 [sections_ insertObject:ignored atIndex:0];
7586 [sections_ insertObject:upgradable atIndex:0];
7590 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7591 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7592 style:UIBarButtonItemStylePlain
7594 action:@selector(upgradeButtonClicked)
7595 ] autorelease]) animated:YES];
7597 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7598 initWithTitle:UCLocalize("REFRESH")
7599 style:UIBarButtonItemStylePlain
7601 action:@selector(refreshButtonClicked)
7602 ] autorelease]) animated:YES];
7607 - (void) reloadData {
7609 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7614 /* Search Controller {{{ */
7615 @interface SearchController : FilteredPackageListController <
7618 _H<UISearchBar, 1> search_;
7622 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7623 - (void) reloadData;
7627 @implementation SearchController
7629 - (NSURL *) navigationURL {
7630 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7631 return [NSURL URLWithString:@"cydia://search"];
7633 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7636 - (void) useSearch {
7637 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7642 - (void) viewWillAppear:(BOOL)animated {
7643 [super viewWillAppear:animated];
7645 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7649 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7650 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7655 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7656 [search_ resignFirstResponder];
7660 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7661 [search_ setText:@""];
7662 [self searchBarButtonClicked:searchBar];
7665 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7666 [self searchBarButtonClicked:searchBar];
7669 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7670 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7674 - (bool) shouldYield {
7678 - (bool) shouldBlock {
7679 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7682 - (bool) isSummarized {
7683 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7686 - (bool) showsSections {
7690 - (NSMutableArray *) _reloadPackages {
7691 NSMutableArray *packages([super _reloadPackages]);
7692 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7693 [packages radixSortUsingSelector:@selector(rank)];
7697 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7698 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7699 search_ = [[[UISearchBar alloc] init] autorelease];
7700 [search_ setDelegate:self];
7703 [search_ setText:query];
7707 - (void) viewDidAppear:(BOOL)animated {
7708 [super viewDidAppear:animated];
7710 if (!searchloaded_) {
7711 searchloaded_ = YES;
7712 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7713 [search_ layoutSubviews];
7714 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7716 UITextField *textField;
7717 if ([search_ respondsToSelector:@selector(searchField)])
7718 textField = [search_ searchField];
7720 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7722 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7723 [textField setEnablesReturnKeyAutomatically:NO];
7724 [[self navigationItem] setTitleView:textField];
7728 - (void) reloadData {
7729 id object([search_ text]);
7730 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7731 object = [object componentsSeparatedByString:@" "];
7733 [self setObject:object];
7739 - (void) didSelectPackage:(Package *)package {
7740 [search_ resignFirstResponder];
7741 [super didSelectPackage:package];
7746 /* Package Settings Controller {{{ */
7747 @interface PackageSettingsController : CyteViewController <
7748 UITableViewDataSource,
7751 _transient Database *database_;
7753 _H<Package> package_;
7754 _H<UITableView, 2> table_;
7755 _H<UISwitch> subscribedSwitch_;
7756 _H<UISwitch> ignoredSwitch_;
7757 _H<UITableViewCell> subscribedCell_;
7758 _H<UITableViewCell> ignoredCell_;
7761 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7765 @implementation PackageSettingsController
7767 - (NSURL *) navigationURL {
7768 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7771 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7772 if (package_ == nil)
7775 if ([package_ installed] == nil)
7781 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7782 if (package_ == nil)
7785 // both sections contain just one item right now.
7789 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7793 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7795 return UCLocalize("SHOW_ALL_CHANGES_EX");
7797 return UCLocalize("IGNORE_UPGRADES_EX");
7800 - (void) onSubscribed:(id)control {
7801 bool value([control isOn]);
7802 if (package_ == nil)
7804 if ([package_ setSubscribed:value])
7805 [delegate_ updateData];
7808 - (void) _updateIgnored {
7809 const char *package([name_ UTF8String]);
7810 bool on([ignoredSwitch_ isOn]);
7812 pid_t pid(ExecFork());
7814 FILE *dpkg(popen("dpkg --set-selections", "w"));
7815 fwrite(package, strlen(package), 1, dpkg);
7818 fwrite(" hold\n", 6, 1, dpkg);
7820 fwrite(" install\n", 9, 1, dpkg);
7830 int result(waitpid(pid, &status, 0));
7833 _assert(result == pid);
7839 - (void) onIgnored:(id)control {
7840 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7841 [invocation setTarget:self];
7842 [invocation setSelector:@selector(_updateIgnored)];
7844 [delegate_ reloadDataWithInvocation:invocation];
7847 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7848 if (package_ == nil)
7851 switch ([indexPath section]) {
7852 case 0: return subscribedCell_;
7853 case 1: return ignoredCell_;
7862 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7864 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7865 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7866 [(UITableView *) table_ setDataSource:self];
7867 [table_ setDelegate:self];
7868 [[self view] addSubview:table_];
7870 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7871 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7872 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7874 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7875 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7876 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7878 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7879 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7880 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7881 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7883 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7884 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7885 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7886 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7889 - (void) viewDidLoad {
7890 [super viewDidLoad];
7892 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7895 - (void) releaseSubviews {
7897 subscribedCell_ = nil;
7899 ignoredSwitch_ = nil;
7900 subscribedSwitch_ = nil;
7902 [super releaseSubviews];
7905 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7906 if ((self = [super init]) != nil) {
7907 database_ = database;
7912 - (void) reloadData {
7915 package_ = [database_ packageWithName:name_];
7917 if (package_ != nil) {
7918 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7919 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7920 } // XXX: what now, G?
7922 [table_ reloadData];
7928 /* Installed Controller {{{ */
7929 @interface InstalledController : FilteredPackageListController {
7933 - (id) initWithDatabase:(Database *)database;
7935 - (void) updateRoleButton;
7936 - (void) queueStatusDidChange;
7940 @implementation InstalledController
7942 - (NSURL *) navigationURL {
7943 return [NSURL URLWithString:@"cydia://installed"];
7946 - (id) initWithDatabase:(Database *)database {
7947 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7948 [self updateRoleButton];
7949 [self queueStatusDidChange];
7954 - (void) queueButtonClicked {
7959 - (void) queueStatusDidChange {
7963 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7964 initWithTitle:UCLocalize("QUEUE")
7965 style:UIBarButtonItemStyleDone
7967 action:@selector(queueButtonClicked)
7970 [[self navigationItem] setLeftBarButtonItem:nil];
7976 - (void) updateRoleButton {
7977 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7978 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7979 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7980 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7982 action:@selector(roleButtonClicked)
7986 - (void) roleButtonClicked {
7987 [self setObject:[NSNumber numberWithBool:expert_]];
7991 [self updateRoleButton];
7997 /* Source Cell {{{ */
7998 @interface SourceCell : CyteTableViewCell <
7999 CyteTableViewCellDelegate
8002 _H<NSString> origin_;
8003 _H<NSString> label_;
8006 - (void) setSource:(Source *)source;
8010 @implementation SourceCell
8012 - (void) _setImage:(UIImage *)image {
8014 [content_ setNeedsDisplay];
8017 - (void) _setSource:(Source *)source {
8018 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8020 if (NSString *base = [source base])
8021 if ([base length] != 0) {
8022 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
8024 if (NSData *data = [NSURLConnection
8025 sendSynchronousRequest:[NSURLRequest
8027 //cachePolicy:NSURLRequestUseProtocolCachePolicy
8031 returningResponse:NULL
8034 if (UIImage *image = [UIImage imageWithData:data])
8035 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
8041 - (void) setSource:(Source *)source {
8042 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8044 origin_ = [source name];
8045 label_ = [source uri];
8047 [content_ setNeedsDisplay];
8049 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
8052 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8053 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8054 UIView *content([self contentView]);
8055 CGRect bounds([content bounds]);
8057 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8058 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8059 [content_ setBackgroundColor:[UIColor whiteColor]];
8060 [content addSubview:content_];
8062 [content_ setDelegate:self];
8063 [content_ setOpaque:YES];
8065 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8069 - (NSString *) accessibilityLabel {
8073 - (void) drawContentRect:(CGRect)rect {
8074 bool highlighted(highlighted_);
8075 float width(rect.size.width);
8078 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8085 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 60) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8089 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 75) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8094 /* Source Controller {{{ */
8095 @interface SourceController : FilteredPackageListController {
8096 _transient Source *source_;
8100 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8104 @implementation SourceController
8106 - (NSURL *) navigationURL {
8107 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8110 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8111 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8113 key_ = [source key];
8117 - (void) reloadData {
8118 source_ = [database_ sourceWithKey:key_];
8119 key_ = [source_ key];
8120 [self setObject:source_];
8122 [[self navigationItem] setTitle:[source_ label]];
8129 /* Sources Controller {{{ */
8130 @interface SourcesController : CyteViewController <
8131 UITableViewDataSource,
8134 _transient Database *database_;
8135 _H<UITableView, 2> list_;
8136 _H<NSMutableArray> sources_;
8140 _H<UIProgressHUD> hud_;
8143 //NSURLConnection *installer_;
8144 NSURLConnection *trivial_;
8145 NSURLConnection *trivial_bz2_;
8146 NSURLConnection *trivial_gz_;
8147 //NSURLConnection *automatic_;
8152 - (id) initWithDatabase:(Database *)database;
8153 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8157 @implementation SourcesController
8159 - (void) _releaseConnection:(NSURLConnection *)connection {
8160 if (connection != nil) {
8161 [connection cancel];
8162 //[connection setDelegate:nil];
8163 [connection release];
8168 //[self _releaseConnection:installer_];
8169 [self _releaseConnection:trivial_];
8170 [self _releaseConnection:trivial_gz_];
8171 [self _releaseConnection:trivial_bz2_];
8172 //[self _releaseConnection:automatic_];
8177 - (NSURL *) navigationURL {
8178 return [NSURL URLWithString:@"cydia://sources"];
8181 - (void) viewDidAppear:(BOOL)animated {
8182 [super viewDidAppear:animated];
8183 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8186 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8187 return offset_ == 0 ? 1 : 2;
8190 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8191 switch (section + (offset_ == 0 ? 1 : 0)) {
8192 case 0: return UCLocalize("ENTERED_BY_USER");
8193 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8199 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8200 int count = [sources_ count];
8202 case 0: return (offset_ == 0 ? count : offset_);
8203 case 1: return count - offset_;
8209 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8211 switch (indexPath.section) {
8212 case 0: idx = indexPath.row; break;
8213 case 1: idx = indexPath.row + offset_; break;
8217 return [sources_ objectAtIndex:idx];
8220 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8221 static NSString *cellIdentifier = @"SourceCell";
8223 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8224 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8225 [cell setSource:[self sourceAtIndexPath:indexPath]];
8226 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8231 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8232 Source *source = [self sourceAtIndexPath:indexPath];
8234 SourceController *controller = [[[SourceController alloc]
8235 initWithDatabase:database_
8239 [controller setDelegate:delegate_];
8241 [[self navigationController] pushViewController:controller animated:YES];
8244 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8245 Source *source = [self sourceAtIndexPath:indexPath];
8246 return [source record] != nil;
8249 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8250 if (editingStyle == UITableViewCellEditingStyleDelete) {
8251 Source *source = [self sourceAtIndexPath:indexPath];
8252 [Sources_ removeObjectForKey:[source key]];
8253 [delegate_ syncData];
8258 [delegate_ addTrivialSource:href_];
8259 [delegate_ syncData];
8262 - (NSString *) getWarning {
8263 NSString *href(href_);
8264 NSRange colon([href rangeOfString:@"://"]);
8265 if (colon.location != NSNotFound)
8266 href = [href substringFromIndex:(colon.location + 3)];
8267 href = [href stringByAddingPercentEscapes];
8268 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8269 href = [href stringByCachingURLWithCurrentCDN];
8271 NSURL *url([NSURL URLWithString:href]);
8273 NSStringEncoding encoding;
8274 NSError *error(nil);
8276 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8277 return [warning length] == 0 ? nil : warning;
8281 - (void) _endConnection:(NSURLConnection *)connection {
8282 // XXX: the memory management in this method is horribly awkward
8284 NSURLConnection **field = NULL;
8285 if (connection == trivial_)
8287 else if (connection == trivial_bz2_)
8288 field = &trivial_bz2_;
8289 else if (connection == trivial_gz_)
8290 field = &trivial_gz_;
8291 _assert(field != NULL);
8292 [connection release];
8297 trivial_bz2_ == nil &&
8300 [delegate_ releaseNetworkActivityIndicator];
8302 [delegate_ removeProgressHUD:hud_];
8308 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8311 UIAlertView *alert = [[[UIAlertView alloc]
8312 initWithTitle:UCLocalize("SOURCE_WARNING")
8315 cancelButtonTitle:UCLocalize("CANCEL")
8317 UCLocalize("ADD_ANYWAY"),
8321 [alert setContext:@"warning"];
8322 [alert setNumberOfRows:1];
8326 } else if (error_ != nil) {
8327 UIAlertView *alert = [[[UIAlertView alloc]
8328 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8329 message:[error_ localizedDescription]
8331 cancelButtonTitle:UCLocalize("OK")
8332 otherButtonTitles:nil
8335 [alert setContext:@"urlerror"];
8338 UIAlertView *alert = [[[UIAlertView alloc]
8339 initWithTitle:UCLocalize("NOT_REPOSITORY")
8340 message:UCLocalize("NOT_REPOSITORY_EX")
8342 cancelButtonTitle:UCLocalize("OK")
8343 otherButtonTitles:nil
8346 [alert setContext:@"trivial"];
8355 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8356 switch ([response statusCode]) {
8362 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8363 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8365 [self _endConnection:connection];
8368 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8369 [self _endConnection:connection];
8372 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8373 NSURL *url([NSURL URLWithString:href]);
8375 NSMutableURLRequest *request = [NSMutableURLRequest
8377 cachePolicy:NSURLRequestUseProtocolCachePolicy
8378 timeoutInterval:120.0
8381 [request setHTTPMethod:method];
8383 if (Machine_ != NULL)
8384 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8386 if ([url isCydiaSecure]) {
8387 if (UniqueID_ != nil)
8388 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8391 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8394 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8395 NSString *context([alert context]);
8397 if ([context isEqualToString:@"source"]) {
8400 NSString *href = [[alert textField] text];
8402 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8404 if (![href hasSuffix:@"/"])
8405 href_ = [href stringByAppendingString:@"/"];
8409 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8410 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8411 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8412 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8416 // XXX: this is stupid
8417 hud_ = [delegate_ addProgressHUD];
8418 [hud_ setText:UCLocalize("VERIFYING_URL")];
8419 [delegate_ retainNetworkActivityIndicator];
8428 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8429 } else if ([context isEqualToString:@"trivial"])
8430 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8431 else if ([context isEqualToString:@"urlerror"])
8432 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8433 else if ([context isEqualToString:@"warning"]) {
8447 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8452 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8454 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8455 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8456 [list_ setRowHeight:53];
8457 [(UITableView *) list_ setDataSource:self];
8458 [list_ setDelegate:self];
8459 [[self view] addSubview:list_];
8462 - (void) viewDidLoad {
8463 [super viewDidLoad];
8465 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8466 [self updateButtonsForEditingStatus:NO animated:NO];
8469 - (void) releaseSubviews {
8474 [super releaseSubviews];
8477 - (id) initWithDatabase:(Database *)database {
8478 if ((self = [super init]) != nil) {
8479 database_ = database;
8483 - (void) reloadData {
8487 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8490 sources_ = [NSMutableArray arrayWithCapacity:16];
8491 [sources_ addObjectsFromArray:[database_ sources]];
8493 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8496 int count([sources_ count]);
8498 for (int i = 0; i != count; i++) {
8499 if ([[sources_ objectAtIndex:i] record] == nil)
8504 [list_ setEditing:NO];
8505 [self updateButtonsForEditingStatus:NO animated:NO];
8509 - (void) showAddSourcePrompt {
8510 UIAlertView *alert = [[[UIAlertView alloc]
8511 initWithTitle:UCLocalize("ENTER_APT_URL")
8514 cancelButtonTitle:UCLocalize("CANCEL")
8516 UCLocalize("ADD_SOURCE"),
8520 [alert setContext:@"source"];
8522 [alert setNumberOfRows:1];
8523 [alert addTextFieldWithValue:@"http://" label:@""];
8525 UITextInputTraits *traits = [[alert textField] textInputTraits];
8526 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8527 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8528 [traits setKeyboardType:UIKeyboardTypeURL];
8529 // XXX: UIReturnKeyDone
8530 [traits setReturnKeyType:UIReturnKeyNext];
8535 - (void) addButtonClicked {
8536 [self showAddSourcePrompt];
8539 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8540 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8541 initWithTitle:UCLocalize("ADD")
8542 style:UIBarButtonItemStylePlain
8544 action:@selector(addButtonClicked)
8545 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8547 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8548 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8549 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8551 action:@selector(editButtonClicked)
8552 ] autorelease] animated:animated];
8554 if (IsWildcat_ && !editing)
8555 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8556 initWithTitle:UCLocalize("SETTINGS")
8557 style:UIBarButtonItemStylePlain
8559 action:@selector(settingsButtonClicked)
8563 - (void) settingsButtonClicked {
8564 [delegate_ showSettings];
8567 - (void) editButtonClicked {
8568 [list_ setEditing:![list_ isEditing] animated:YES];
8570 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8576 /* Settings Controller {{{ */
8577 @interface SettingsController : CyteViewController <
8578 UITableViewDataSource,
8581 _transient Database *database_;
8582 // XXX: ok, "roledelegate_"?...
8583 _transient id roledelegate_;
8584 _H<UITableView, 2> table_;
8585 _H<UISegmentedControl> segment_;
8586 _H<UIView> container_;
8589 - (void) showDoneButton;
8590 - (void) resizeSegmentedControl;
8594 @implementation SettingsController
8597 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8599 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8600 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8601 [table_ setDelegate:self];
8602 [(UITableView *) table_ setDataSource:self];
8603 [[self view] addSubview:table_];
8605 NSArray *items = [NSArray arrayWithObjects:
8607 UCLocalize("HACKER"),
8608 UCLocalize("DEVELOPER"),
8610 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8611 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8612 [container_ addSubview:segment_];
8615 - (void) viewDidLoad {
8616 [super viewDidLoad];
8618 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8621 if ([Role_ isEqualToString:@"User"]) index = 0;
8622 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8623 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8625 [segment_ setSelectedSegmentIndex:index];
8626 [self showDoneButton];
8629 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8630 [self resizeSegmentedControl];
8633 - (void) releaseSubviews {
8638 [super releaseSubviews];
8641 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8642 if ((self = [super init]) != nil) {
8643 database_ = database;
8644 roledelegate_ = delegate;
8648 - (void) resizeSegmentedControl {
8649 CGFloat width = [[self view] frame].size.width;
8650 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8653 - (void) viewWillAppear:(BOOL)animated {
8654 [super viewWillAppear:animated];
8656 [self resizeSegmentedControl];
8659 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8660 [self resizeSegmentedControl];
8663 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8664 [self resizeSegmentedControl];
8668 NSString *role(nil);
8670 switch ([segment_ selectedSegmentIndex]) {
8671 case 0: role = @"User"; break;
8672 case 1: role = @"Hacker"; break;
8673 case 2: role = @"Developer"; break;
8678 if (![role isEqualToString:Role_]) {
8679 bool rolling(Role_ == nil);
8682 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8686 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8690 [roledelegate_ loadData];
8692 [roledelegate_ updateData];
8696 - (void) segmentChanged:(UISegmentedControl *)control {
8697 [self showDoneButton];
8700 - (void) saveAndClose {
8703 [[self navigationItem] setRightBarButtonItem:nil];
8704 [[self navigationController] dismissModalViewControllerAnimated:YES];
8707 - (void) doneButtonClicked {
8708 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8709 [spinner startAnimating];
8710 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8711 [[self navigationItem] setRightBarButtonItem:spinItem];
8713 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8716 - (void) showDoneButton {
8717 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8718 initWithTitle:UCLocalize("DONE")
8719 style:UIBarButtonItemStyleDone
8721 action:@selector(doneButtonClicked)
8722 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8725 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8726 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8730 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8734 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8735 return nil; // This method is required by the protocol.
8738 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8740 return UCLocalize("ROLE_EX");
8742 return [NSString stringWithFormat:
8743 @"%@: %@\n%@: %@\n%@: %@",
8744 UCLocalize("USER"), UCLocalize("USER_EX"),
8745 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8746 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8751 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8752 return section == 3 ? 44.0f : 0;
8755 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8756 return section == 3 ? container_ : nil;
8759 - (void) reloadData {
8762 [table_ reloadData];
8767 /* Stash Controller {{{ */
8768 @interface StashController : CyteViewController {
8769 _H<UIActivityIndicatorView> spinner_;
8770 _H<UILabel> status_;
8771 _H<UILabel> caption_;
8776 @implementation StashController
8779 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8780 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8782 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8783 CGRect spinrect = [spinner_ frame];
8784 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8785 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8786 [spinner_ setFrame:spinrect];
8787 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8788 [[self view] addSubview:spinner_];
8789 [spinner_ startAnimating];
8792 captrect.size.width = [[self view] frame].size.width;
8793 captrect.size.height = 40.0f;
8794 captrect.origin.x = 0;
8795 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8796 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8797 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8798 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8799 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8800 [caption_ setTextColor:[UIColor whiteColor]];
8801 [caption_ setBackgroundColor:[UIColor clearColor]];
8802 [caption_ setShadowColor:[UIColor blackColor]];
8803 [caption_ setTextAlignment:UITextAlignmentCenter];
8804 [[self view] addSubview:caption_];
8807 statusrect.size.width = [[self view] frame].size.width;
8808 statusrect.size.height = 30.0f;
8809 statusrect.origin.x = 0;
8810 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8811 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8812 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8813 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8814 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8815 [status_ setTextColor:[UIColor whiteColor]];
8816 [status_ setBackgroundColor:[UIColor clearColor]];
8817 [status_ setShadowColor:[UIColor blackColor]];
8818 [status_ setTextAlignment:UITextAlignmentCenter];
8819 [[self view] addSubview:status_];
8822 - (void) releaseSubviews {
8827 [super releaseSubviews];
8833 @interface CYURLCache : SDURLCache {
8838 @implementation CYURLCache
8840 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8843 else if ([event isEqualToString:@"no-cache"])
8845 else if ([event isEqualToString:@"store"])
8847 else if ([event isEqualToString:@"invalid"])
8849 else if ([event isEqualToString:@"memory"])
8851 else if ([event isEqualToString:@"disk"])
8853 else if ([event isEqualToString:@"miss"])
8856 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8860 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8861 if (NSURLResponse *response = [cached response])
8862 if (NSString *mime = [response MIMEType])
8863 if ([mime isEqualToString:@"text/cache-manifest"]) {
8864 NSURL *url([response URL]);
8867 NSLog(@"###: %@", [url absoluteString]);
8870 @synchronized (HostConfig_) {
8871 [CachedURLs_ addObject:url];
8875 [super storeCachedResponse:cached forRequest:request];
8880 @interface Cydia : UIApplication <
8881 ConfirmationControllerDelegate,
8884 UINavigationControllerDelegate,
8885 UITabBarControllerDelegate
8887 _H<UIWindow> window_;
8888 _H<CYTabBarController> tabbar_;
8889 _H<CydiaLoadingViewController> emulated_;
8891 _H<NSMutableArray> essential_;
8892 _H<NSMutableArray> broken_;
8894 Database *database_;
8896 _H<NSURL> starturl_;
8901 _H<StashController> stash_;
8910 @implementation Cydia
8912 - (void) beginUpdate {
8913 [tabbar_ beginUpdate];
8917 return [tabbar_ updating];
8921 if ([broken_ count] != 0) {
8922 int count = [broken_ count];
8924 UIAlertView *alert = [[[UIAlertView alloc]
8925 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8926 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8928 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8930 UCLocalize("TEMPORARY_IGNORE"),
8934 [alert setContext:@"fixhalf"];
8935 [alert setNumberOfRows:2];
8937 } else if (!Ignored_ && [essential_ count] != 0) {
8938 int count = [essential_ count];
8940 UIAlertView *alert = [[[UIAlertView alloc]
8941 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8942 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8944 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8946 UCLocalize("UPGRADE_ESSENTIAL"),
8947 UCLocalize("COMPLETE_UPGRADE"),
8951 [alert setContext:@"upgrade"];
8956 - (void) returnToCydia {
8960 - (void) _saveConfig {
8966 NSString *error(nil);
8968 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8970 NSError *error(nil);
8971 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8972 NSLog(@"failure to save metadata data: %@", error);
8977 NSLog(@"failure to serialize metadata: %@", error);
8984 // Navigation controller for the queuing badge.
8985 - (UINavigationController *) queueNavigationController {
8986 NSArray *controllers = [tabbar_ viewControllers];
8987 return [controllers objectAtIndex:3];
8990 - (void) unloadData {
8991 [tabbar_ unloadData];
8994 - (void) _updateData {
8998 UINavigationController *navigation = [self queueNavigationController];
9000 id queuedelegate = nil;
9001 if ([[navigation viewControllers] count] > 0)
9002 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9004 [queuedelegate queueStatusDidChange];
9005 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9008 - (void) _refreshIfPossible:(NSDate *)update {
9009 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9011 bool recently = false;
9012 if (update != nil) {
9013 NSTimeInterval interval([update timeIntervalSinceNow]);
9014 if (interval <= 0 && interval > -(15*60))
9018 // Don't automatic refresh if:
9019 // - We already refreshed recently.
9020 // - We already auto-refreshed this launch.
9021 // - Auto-refresh is disabled.
9022 if (recently || loaded_ || ManualRefresh) {
9023 // If we are cancelling, we need to make sure it knows it's already loaded.
9026 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9028 // We are going to load, so remember that.
9031 SCNetworkReachabilityFlags flags; {
9032 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9033 SCNetworkReachabilityGetFlags(reachability, &flags);
9034 CFRelease(reachability);
9037 // XXX: this elaborate mess is what Apple is using to determine this? :(
9038 // XXX: do we care if the user has to intervene? maybe that's ok?
9040 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9041 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9042 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9043 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9044 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9045 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9049 // If we can reach the server, auto-refresh!
9051 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9057 - (void) refreshIfPossible {
9058 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9061 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9062 @synchronized (self) {
9063 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9064 [hud setText:UCLocalize("RELOADING_DATA")];
9066 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9069 [self removeProgressHUD:hud];
9073 [essential_ removeAllObjects];
9074 [broken_ removeAllObjects];
9076 NSArray *packages([database_ packages]);
9077 for (Package *package in packages) {
9079 [broken_ addObject:package];
9080 if ([package upgradableAndEssential:NO]) {
9081 if ([package essential])
9082 [essential_ addObject:package];
9087 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9090 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9091 [changesItem setBadgeValue:badge];
9092 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9093 [self setApplicationIconBadgeNumber:changes];
9096 [changesItem setBadgeValue:nil];
9097 [changesItem setAnimatedBadge:NO];
9098 [self setApplicationIconBadgeNumber:0];
9104 - (void) updateData {
9110 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9113 - (void) disemulate {
9114 if (emulated_ == nil)
9117 [window_ addSubview:[tabbar_ view]];
9118 [[emulated_ view] removeFromSuperview];
9120 [window_ setUserInteractionEnabled:YES];
9123 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9124 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9126 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9128 UIViewController *parent;
9129 if (emulated_ == nil)
9138 [parent presentModalViewController:navigation animated:YES];
9141 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9142 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9144 if (navigation != nil)
9145 [navigation pushViewController:progress animated:YES];
9147 [self presentModalViewController:progress force:YES];
9149 [progress invoke:invocation withTitle:title];
9153 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9154 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9157 - (void) repairWithInvocation:(NSInvocation *)invocation {
9159 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9163 - (void) repairWithSelector:(SEL)selector {
9164 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9167 - (void) reloadData {
9168 [self reloadDataWithInvocation:nil];
9169 if ([database_ progressDelegate] == nil)
9175 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9178 - (void) addSource:(NSDictionary *) source {
9182 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9183 AddSource(href, distribution, sections);
9186 - (void) addTrivialSource:(NSString *)href {
9187 AddSource(href, @"./");
9190 - (void) updateValues {
9195 pkgProblemResolver *resolver = [database_ resolver];
9197 resolver->InstallProtect();
9198 if (!resolver->Resolve(true))
9203 // XXX: this is a really crappy way of doing this.
9204 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9205 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9206 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9207 if ([tabbar_ updating])
9208 [tabbar_ cancelUpdate];
9210 if (![database_ prepare])
9213 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9214 [page setDelegate:self];
9215 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9218 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9219 [tabbar_ presentModalViewController:confirm_ animated:YES];
9225 @synchronized (self) {
9230 - (void) clearPackage:(Package *)package {
9231 @synchronized (self) {
9238 - (void) installPackages:(NSArray *)packages {
9239 @synchronized (self) {
9240 for (Package *package in packages)
9247 - (void) installPackage:(Package *)package {
9248 @synchronized (self) {
9255 - (void) removePackage:(Package *)package {
9256 @synchronized (self) {
9263 - (void) distUpgrade {
9264 @synchronized (self) {
9265 if (![database_ upgrade])
9272 [database_ perform];
9273 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9276 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9279 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9281 [self refreshIfPossible];
9284 - (void) showSettings {
9285 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9288 - (void) retainNetworkActivityIndicator {
9289 if (activity_++ == 0)
9290 [self setNetworkActivityIndicatorVisible:YES];
9293 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9297 - (void) releaseNetworkActivityIndicator {
9298 if (--activity_ == 0)
9299 [self setNetworkActivityIndicatorVisible:NO];
9302 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9307 - (void) cancelAndClear:(bool)clear {
9308 @synchronized (self) {
9320 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9321 NSString *context([alert context]);
9323 if ([context isEqualToString:@"conffile"]) {
9324 FILE *input = [database_ input];
9325 if (button == [alert cancelButtonIndex])
9326 fprintf(input, "N\n");
9327 else if (button == [alert firstOtherButtonIndex])
9328 fprintf(input, "Y\n");
9331 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9332 } else if ([context isEqualToString:@"fixhalf"]) {
9333 if (button == [alert cancelButtonIndex]) {
9334 @synchronized (self) {
9335 for (Package *broken in (id) broken_) {
9338 NSString *id = [broken id];
9339 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9340 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9341 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9342 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9348 } else if (button == [alert firstOtherButtonIndex]) {
9349 [broken_ removeAllObjects];
9353 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9354 } else if ([context isEqualToString:@"upgrade"]) {
9355 if (button == [alert firstOtherButtonIndex]) {
9356 @synchronized (self) {
9357 for (Package *essential in (id) essential_)
9358 [essential install];
9363 } else if (button == [alert firstOtherButtonIndex] + 1) {
9365 } else if (button == [alert cancelButtonIndex]) {
9369 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9373 - (void) system:(NSString *)command {
9374 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9377 system([command UTF8String]);
9383 - (void) applicationWillSuspend {
9385 [super applicationWillSuspend];
9388 - (BOOL) isSafeToSuspend {
9391 NSLog(@"isSafeToSuspend: locked_ != 0");
9396 // Use external process status API internally.
9397 // This is probably a really bad idea.
9398 // XXX: what is the point of this? does this solve anything at all?
9399 uint64_t status = 0;
9401 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9402 notify_get_state(notify_token, &status);
9403 notify_cancel(notify_token);
9408 NSLog(@"isSafeToSuspend: status != 0");
9414 NSLog(@"isSafeToSuspend: -> true");
9419 - (void) applicationSuspend:(__GSEvent *)event {
9420 if ([self isSafeToSuspend])
9421 [super applicationSuspend:event];
9424 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9425 if ([self isSafeToSuspend])
9426 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9429 - (void) _setSuspended:(BOOL)value {
9430 if ([self isSafeToSuspend])
9431 [super _setSuspended:value];
9434 - (UIProgressHUD *) addProgressHUD {
9435 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9436 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9438 [window_ setUserInteractionEnabled:NO];
9440 UIViewController *target(tabbar_);
9441 if (UIViewController *modal = [target modalViewController])
9444 UIView *view([target view]);
9445 [view addSubview:hud];
9447 [hud showInView:[tabbar_ view]];
9453 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9456 [hud removeFromSuperview];
9457 [window_ setUserInteractionEnabled:YES];
9460 - (CyteViewController *) pageForPackage:(NSString *)name {
9461 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9464 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9465 NSString *scheme([[url scheme] lowercaseString]);
9466 if ([[url absoluteString] length] <= [scheme length] + 3)
9468 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9469 NSArray *components([path pathComponents]);
9471 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9472 return [self pageForPackage:[components objectAtIndex:1]];
9474 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9477 NSString *base([components objectAtIndex:0]);
9479 CyteViewController *controller = nil;
9481 if ([base isEqualToString:@"url"]) {
9482 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9483 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9484 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9485 } else if (!external && [components count] == 1) {
9486 if ([base isEqualToString:@"manage"]) {
9487 controller = [[[ManageController alloc] init] autorelease];
9490 if ([base isEqualToString:@"sources"]) {
9491 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9494 if ([base isEqualToString:@"home"]) {
9495 controller = [[[HomeController alloc] init] autorelease];
9498 if ([base isEqualToString:@"sections"]) {
9499 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9502 if ([base isEqualToString:@"search"]) {
9503 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9506 if ([base isEqualToString:@"changes"]) {
9507 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9510 if ([base isEqualToString:@"installed"]) {
9511 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9513 } else if ([components count] == 2) {
9514 NSString *argument = [components objectAtIndex:1];
9516 if ([base isEqualToString:@"package"]) {
9517 controller = [self pageForPackage:argument];
9520 if (!external && [base isEqualToString:@"search"]) {
9521 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9524 if (!external && [base isEqualToString:@"sections"]) {
9525 if ([argument isEqualToString:@"all"])
9527 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9530 if (!external && [base isEqualToString:@"sources"]) {
9531 if ([argument isEqualToString:@"add"]) {
9532 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9533 [(SourcesController *)controller showAddSourcePrompt];
9535 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9536 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9540 if (!external && [base isEqualToString:@"launch"]) {
9541 [self launchApplicationWithIdentifier:argument suspended:NO];
9544 } else if (!external && [components count] == 3) {
9545 NSString *arg1 = [components objectAtIndex:1];
9546 NSString *arg2 = [components objectAtIndex:2];
9548 if ([base isEqualToString:@"package"]) {
9549 if ([arg2 isEqualToString:@"settings"]) {
9550 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9551 } else if ([arg2 isEqualToString:@"files"]) {
9552 if (Package *package = [database_ packageWithName:arg1]) {
9553 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9554 [(FileTable *)controller setPackage:package];
9560 [controller setDelegate:self];
9564 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9565 CyteViewController *page([self pageForURL:url forExternal:external]);
9568 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9569 [nav setViewControllers:[NSArray arrayWithObject:page]];
9570 [tabbar_ setUnselectedViewController:nav];
9576 - (void) applicationOpenURL:(NSURL *)url {
9577 [super applicationOpenURL:url];
9582 [self openCydiaURL:url forExternal:YES];
9585 - (void) applicationWillResignActive:(UIApplication *)application {
9586 // Stop refreshing if you get a phone call or lock the device.
9587 if ([tabbar_ updating])
9588 [tabbar_ cancelUpdate];
9590 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9591 [super applicationWillResignActive:application];
9594 - (void) saveState {
9595 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9596 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9597 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9603 - (void) applicationWillTerminate:(UIApplication *)application {
9607 - (void) setConfigurationData:(NSString *)data {
9608 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9610 if (!conffile_r(data)) {
9611 lprintf("E:invalid conffile\n");
9615 NSString *ofile = conffile_r[1];
9616 //NSString *nfile = conffile_r[2];
9618 UIAlertView *alert = [[[UIAlertView alloc]
9619 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9620 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9622 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9624 UCLocalize("ACCEPT_NEW_COPY"),
9625 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9629 [alert setContext:@"conffile"];
9630 [alert setNumberOfRows:2];
9634 - (void) addStashController {
9636 stash_ = [[[StashController alloc] init] autorelease];
9637 [window_ addSubview:[stash_ view]];
9640 - (void) removeStashController {
9641 [[stash_ view] removeFromSuperview];
9647 [self setIdleTimerDisabled:YES];
9649 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9650 UpdateExternalStatus(1);
9651 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9652 UpdateExternalStatus(0);
9654 [self removeStashController];
9656 if (ExecFork() == 0) {
9657 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9658 perror("launchctl stop");
9662 - (void) setupViewControllers {
9663 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9665 NSMutableArray *items([NSMutableArray arrayWithObjects:
9666 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9667 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9668 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9669 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9673 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9674 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9676 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9679 NSMutableArray *controllers([NSMutableArray array]);
9680 for (UITabBarItem *item in items) {
9681 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9682 [controller setTabBarItem:item];
9683 [controllers addObject:controller];
9685 [tabbar_ setViewControllers:controllers];
9687 [tabbar_ setUpdateDelegate:self];
9690 - (void) _sendMemoryWarningNotification {
9691 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9694 - (void) _sendMemoryWarningNotifications {
9696 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9701 - (void) applicationDidFinishLaunching:(id)unused {
9702 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9705 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9706 [self setApplicationSupportsShakeToEdit:NO];
9708 @synchronized (HostConfig_) {
9709 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9712 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9713 initWithMemoryCapacity:524288
9714 diskCapacity:10485760
9715 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9718 [CydiaWebViewController _initialize];
9720 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9722 // this would disallow http{,s} URLs from accessing this data
9723 //[WebView registerURLSchemeAsLocal:@"cydia"];
9725 Font12_ = [UIFont systemFontOfSize:12];
9726 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9727 Font14_ = [UIFont systemFontOfSize:14];
9728 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9729 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9731 essential_ = [NSMutableArray arrayWithCapacity:4];
9732 broken_ = [NSMutableArray arrayWithCapacity:4];
9734 // XXX: I really need this thing... like, seriously... I'm sorry
9735 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9737 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9738 [window_ orderFront:self];
9739 [window_ makeKey:self];
9740 [window_ setHidden:NO];
9743 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9744 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9745 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9746 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9747 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9748 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9749 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9750 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9751 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9754 [self addStashController];
9755 // XXX: this would be much cleaner as a yieldToSelector:
9756 // that way the removeStashController could happen right here inline
9757 // we also could no longer require the useless stash_ field anymore
9758 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9762 database_ = [Database sharedInstance];
9763 [database_ setDelegate:self];
9765 [window_ setUserInteractionEnabled:NO];
9766 [self setupViewControllers];
9768 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9769 [window_ addSubview:[emulated_ view]];
9771 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9775 - (NSArray *) defaultStartPages {
9776 NSMutableArray *standard = [NSMutableArray array];
9777 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9778 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9779 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9781 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9783 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9784 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9786 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9793 [window_ setUserInteractionEnabled:YES];
9794 [self showSettings];
9797 if ([emulated_ modalViewController] != nil)
9798 [emulated_ dismissModalViewControllerAnimated:YES];
9799 [window_ setUserInteractionEnabled:NO];
9802 [self reloadDataWithInvocation:nil];
9803 [self refreshIfPossible];
9808 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9809 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9810 int standardIndex = 0;
9811 NSArray *standard = [self defaultStartPages];
9818 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9819 if (valid && closed != nil) {
9820 NSTimeInterval interval([closed timeIntervalSinceNow]);
9821 // XXX: Is 15 minutes the optimal time here?
9822 if (interval > 0 && interval <= -(15*60))
9826 if (valid && [saved count] != [standard count])
9830 for (unsigned int i = 0; i < [standard count]; i++) {
9831 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9832 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9833 // but it's good enough for now.
9834 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9841 NSArray *items = nil;
9843 [tabbar_ setSelectedIndex:savedIndex];
9846 [tabbar_ setSelectedIndex:standardIndex];
9850 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9851 NSArray *stack = [items objectAtIndex:tab];
9852 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9853 NSMutableArray *current = [NSMutableArray array];
9855 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9856 NSString *addr = [stack objectAtIndex:nav];
9857 NSURL *url = [NSURL URLWithString:addr];
9858 CyteViewController *page = [self pageForURL:url forExternal:NO];
9860 [current addObject:page];
9863 [navigation setViewControllers:current];
9866 // (Try to) show the startup URL.
9867 if (starturl_ != nil) {
9868 [self openCydiaURL:starturl_ forExternal:NO];
9873 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9874 if (item != nil && IsWildcat_) {
9875 [sheet showFromBarButtonItem:item animated:YES];
9877 [sheet showInView:window_];
9881 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9882 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9883 [progress setTitle:task];
9884 [progress addProgressEvent:event];
9887 - (void) addProgressEventForTask:(NSArray *)data {
9888 CydiaProgressEvent *event([data objectAtIndex:0]);
9889 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9890 [self addProgressEvent:event forTask:task];
9893 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9894 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9900 id Alloc_(id self, SEL selector) {
9901 id object = alloc_(self, selector);
9902 lprintf("[%s]A-%p\n", self->isa->name, object);
9907 id Dealloc_(id self, SEL selector) {
9908 id object = dealloc_(self, selector);
9909 lprintf("[%s]D-%p\n", self->isa->name, object);
9913 Class $WebDefaultUIKitDelegate;
9915 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9916 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9917 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9918 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9921 static NSSet *MobilizedFiles_;
9923 static NSURL *MobilizeURL(NSURL *url) {
9924 NSString *path([url path]);
9925 if ([path hasPrefix:@"/var/root/"]) {
9926 NSString *file([path substringFromIndex:10]);
9927 if ([MobilizedFiles_ containsObject:file])
9928 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9934 Class $CFXPreferencesPropertyListSource;
9935 @class CFXPreferencesPropertyListSource;
9937 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9938 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9939 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9940 url = MobilizeURL(url);
9941 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9942 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9948 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9949 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9950 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9951 url = MobilizeURL(url);
9952 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9953 //NSLog(@"%@ %@", [url absoluteString], value);
9959 Class $NSURLConnection;
9961 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9962 NSMutableURLRequest *copy([request mutableCopy]);
9964 NSURL *url([copy URL]);
9966 NSString *href([url absoluteString]);
9967 NSString *host([url host]);
9968 NSString *scheme([[url scheme] lowercaseString]);
9970 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9972 @synchronized (HostConfig_) {
9973 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9974 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9975 [copy setHTTPShouldUsePipelining:YES];
9977 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9978 if ([control isEqualToString:@"max-age=0"])
9979 if ([CachedURLs_ containsObject:href]) {
9981 NSLog(@"~~~: %@", href);
9984 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9986 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9987 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9988 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9992 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9996 int main(int argc, char *argv[]) {
9997 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10001 UpdateExternalStatus(0);
10003 if (Class $UIDevice = objc_getClass("UIDevice")) {
10004 UIDevice *device([$UIDevice currentDevice]);
10005 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10007 IsWildcat_ = false;
10009 UIScreen *screen([UIScreen mainScreen]);
10010 if ([screen respondsToSelector:@selector(scale)])
10011 ScreenScale_ = [screen scale];
10015 UIDevice *device([UIDevice currentDevice]);
10016 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10017 Idiom_ = @"iphone";
10019 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10020 if (idiom == UIUserInterfaceIdiomPhone)
10021 Idiom_ = @"iphone";
10022 else if (idiom == UIUserInterfaceIdiomPad)
10025 NSLog(@"unknown UIUserInterfaceIdiom!");
10028 Pcre pattern("^([0-9]+\\.[0-9]+)");
10029 if (pattern([device systemVersion]))
10030 Firmware_ = pattern[1];
10032 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10034 HostConfig_ = [[[NSObject alloc] init] autorelease];
10035 @synchronized (HostConfig_) {
10036 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10037 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10038 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10039 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10040 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10043 NSString *ui(@"ui/ios");
10045 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10046 UI_ = CydiaURL(ui);
10048 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10050 MobilizedFiles_ = [NSMutableSet setWithObjects:
10051 @"Library/Preferences/com.apple.Accessibility.plist",
10052 @"Library/Preferences/com.apple.preferences.sounds.plist",
10055 /* Library Hacks {{{ */
10056 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10058 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10060 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10061 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10062 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10063 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10066 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10067 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10068 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10069 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10072 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10073 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10074 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10075 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10076 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10079 $NSURLConnection = objc_getClass("NSURLConnection");
10080 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10081 if (NSURLConnection$init$ != NULL) {
10082 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10083 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10086 /* Set Locale {{{ */
10087 Locale_ = CFLocaleCopyCurrent();
10088 Languages_ = [NSLocale preferredLanguages];
10090 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10091 //NSLog(@"%@", [Languages_ description]);
10094 if (Locale_ != NULL)
10095 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10096 else if (Languages_ != nil && [Languages_ count] != 0)
10097 lang = [[Languages_ objectAtIndex:0] UTF8String];
10099 // XXX: consider just setting to C and then falling through?
10102 if (lang != NULL) {
10103 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10104 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10107 NSLog(@"Setting Language: %s", lang);
10109 if (lang != NULL) {
10110 setenv("LANG", lang, true);
10111 std::setlocale(LC_ALL, lang);
10115 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10117 /* Parse Arguments {{{ */
10118 bool substrate(false);
10124 for (int argi(1); argi != argc; ++argi)
10125 if (strcmp(argv[argi], "--") == 0) {
10127 argv[argi] = argv[0];
10133 for (int argi(1); argi != arge; ++argi)
10134 if (strcmp(args[argi], "--substrate") == 0)
10137 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10141 App_ = [[NSBundle mainBundle] bundlePath];
10147 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10148 alloc_ = alloc->method_imp;
10149 alloc->method_imp = (IMP) &Alloc_;*/
10151 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10152 dealloc_ = dealloc->method_imp;
10153 dealloc->method_imp = (IMP) &Dealloc_;*/
10155 /* System Information {{{ */
10159 size = sizeof(maxproc);
10160 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10161 perror("sysctlbyname(\"kern.maxproc\", ?)");
10162 else if (maxproc < 64) {
10164 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10165 perror("sysctlbyname(\"kern.maxproc\", #)");
10168 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10169 char *osversion = new char[size];
10170 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10171 perror("sysctlbyname(\"kern.osversion\", ?)");
10173 System_ = [NSString stringWithUTF8String:osversion];
10175 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10176 char *machine = new char[size];
10177 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10178 perror("sysctlbyname(\"hw.machine\", ?)");
10180 Machine_ = machine;
10182 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10183 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10184 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10186 UniqueID_ = [device uniqueIdentifier];
10188 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10189 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10190 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10192 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10193 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10194 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10196 if (mcc != NULL && mnc != NULL)
10197 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10204 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10205 Build_ = [system objectForKey:@"ProductBuildVersion"];
10206 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10207 Product_ = [info objectForKey:@"SafariProductVersion"];
10208 Safari_ = [info objectForKey:@"CFBundleVersion"];
10211 /* Load Database {{{ */
10213 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10215 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10217 if (Metadata_ == NULL)
10218 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10220 Settings_ = [Metadata_ objectForKey:@"Settings"];
10222 Packages_ = [Metadata_ objectForKey:@"Packages"];
10224 Values_ = [Metadata_ objectForKey:@"Values"];
10225 Sections_ = [Metadata_ objectForKey:@"Sections"];
10226 Sources_ = [Metadata_ objectForKey:@"Sources"];
10228 Token_ = [Metadata_ objectForKey:@"Token"];
10230 Version_ = [Metadata_ objectForKey:@"Version"];
10232 @synchronized (HostConfig_) {
10233 CydiaSource_ = [Metadata_ objectForKey:@"CydiaSource"];
10237 if (Settings_ != nil)
10238 Role_ = [Settings_ objectForKey:@"Role"];
10240 if (Values_ == nil) {
10241 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10242 [Metadata_ setObject:Values_ forKey:@"Values"];
10245 if (Sections_ == nil) {
10246 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10247 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10250 if (Sources_ == nil) {
10251 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10252 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10255 if (Version_ == nil) {
10256 Version_ = [NSNumber numberWithUnsignedInt:0];
10257 [Metadata_ setObject:Version_ forKey:@"Version"];
10260 @synchronized (HostConfig_) {
10261 if (CydiaSource_ == nil) {
10262 CydiaSource_ = @"apt.saurik.com";
10263 [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
10267 if ([Version_ unsignedIntValue] == 0) {
10268 AddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10269 AddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10270 AddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10271 AddSource(@"http://repo666.ultrasn0w.com/", @"./");
10273 Version_ = [NSNumber numberWithUnsignedInt:1];
10274 [Metadata_ setObject:Version_ forKey:@"Version"];
10276 [Metadata_ removeObjectForKey:@"LastUpdate"];
10285 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10288 if (Packages_ != nil) {
10290 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10294 [Metadata_ removeObjectForKey:@"Packages"];
10300 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10302 #define MobileSubstrate_(name) \
10303 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10304 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10305 if (handle == NULL) \
10306 NSLog(@"%s", dlerror()); \
10309 MobileSubstrate_(Activator)
10310 MobileSubstrate_(libstatusbar)
10311 MobileSubstrate_(SimulatedKeyEvents)
10312 MobileSubstrate_(WinterBoard)
10314 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10315 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10317 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10319 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10320 unlink("/tmp/.cydia.fw");
10322 } else if (access("/User", F_OK) != 0 || version < 4) {
10325 system("/usr/libexec/cydia/firmware.sh");
10329 _assert([[NSFileManager defaultManager]
10330 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10331 withIntermediateDirectories:YES
10336 if (access("/tmp/cydia.chk", F_OK) == 0) {
10337 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10338 _assert(errno == ENOENT);
10339 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10340 _assert(errno == ENOENT);
10343 /* APT Initialization {{{ */
10344 _assert(pkgInitConfig(*_config));
10345 _assert(pkgInitSystem(*_config, _system));
10348 _config->Set("APT::Acquire::Translation", lang);
10350 // XXX: this timeout might be important :(
10351 //_config->Set("Acquire::http::Timeout", 15);
10353 _config->Set("Acquire::http::MaxParallel", 3);
10355 /* Color Choices {{{ */
10356 space_ = CGColorSpaceCreateDeviceRGB();
10358 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10359 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10360 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10361 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10362 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10363 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10364 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10365 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10366 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10368 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10369 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10371 /* UIKit Configuration {{{ */
10372 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10373 if ($GSFontSetUseLegacyFontMetrics != NULL)
10374 $GSFontSetUseLegacyFontMetrics(YES);
10376 // XXX: I have a feeling this was important
10377 //UIKeyboardDisableAutomaticAppearance();
10380 Colon_ = UCLocalize("COLON_DELIMITED");
10381 Elision_ = UCLocalize("ELISION");
10382 Error_ = UCLocalize("ERROR");
10383 Warning_ = UCLocalize("WARNING");
10386 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10388 CGColorSpaceRelease(space_);
10389 CFRelease(Locale_);