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 NSString *distribution(@"ios");
753 if (Firmware_ != nil)
754 distribution = [distribution stringByAppendingString:[NSString stringWithFormat:@"-%@", Firmware_]];
756 fprintf(file, "deb http://%s/ %s main\n",
757 [CydiaSource_ UTF8String],
758 [distribution UTF8String]
761 for (NSString *key in [Sources_ allKeys]) {
762 NSDictionary *source([Sources_ objectForKey:key]);
764 NSArray *sections([source objectForKey:@"Sections"] ?: [NSArray array]);
766 fprintf(file, "%s %s %s%s%s\n",
767 [[source objectForKey:@"Type"] UTF8String],
768 [[source objectForKey:@"URI"] UTF8String],
769 [[source objectForKey:@"Distribution"] UTF8String],
770 [sections count] == 0 ? "" : " ",
771 [[sections componentsJoinedByString:@" "] UTF8String]
778 /* Display Helpers {{{ */
779 inline float Interpolate(float begin, float end, float fraction) {
780 return (end - begin) * fraction + begin;
783 static _finline const char *StripVersion_(const char *version) {
784 const char *colon(strchr(version, ':'));
785 return colon == NULL ? version : colon + 1;
788 NSString *LocalizeSection(NSString *section) {
789 static Pcre title_r("^(.*?) \\((.*)\\)$");
790 if (title_r(section)) {
791 NSString *parent(title_r[1]);
792 NSString *child(title_r[2]);
794 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
795 LocalizeSection(parent),
796 LocalizeSection(child)
800 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
803 NSString *Simplify(NSString *title) {
804 const char *data = [title UTF8String];
805 size_t size = [title length];
807 static Pcre square_r("^\\[(.*)\\]$");
808 if (square_r(data, size))
809 return Simplify(square_r[1]);
811 static Pcre paren_r("^\\((.*)\\)$");
812 if (paren_r(data, size))
813 return Simplify(paren_r[1]);
815 static Pcre title_r("^(.*?) \\((.*)\\)$");
816 if (title_r(data, size))
817 return Simplify(title_r[1]);
823 NSString *GetLastUpdate() {
824 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
827 return UCLocalize("NEVER_OR_UNKNOWN");
829 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
830 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
832 CFRelease(formatter);
834 return [(NSString *) formatted autorelease];
837 bool isSectionVisible(NSString *section) {
838 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
839 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
840 return hidden == nil || ![hidden boolValue];
843 static NSObject *CYIOGetValue(const char *path, NSString *property) {
844 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
845 if (entry == MACH_PORT_NULL)
848 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
849 IOObjectRelease(entry);
853 return [(id) value autorelease];
856 static NSString *CYHex(NSData *data, bool reverse = false) {
860 size_t length([data length]);
861 uint8_t bytes[length];
862 [data getBytes:bytes];
864 char string[length * 2 + 1];
865 for (size_t i(0); i != length; ++i)
866 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
868 return [NSString stringWithUTF8String:string];
873 /* Delegate Prototypes {{{ */
876 @class CydiaProgressEvent;
878 @protocol DatabaseDelegate
879 - (void) repairWithSelector:(SEL)selector;
880 - (void) setConfigurationData:(NSString *)data;
881 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
884 @class CYPackageController;
886 @protocol CydiaDelegate
887 - (void) returnToCydia;
889 - (void) retainNetworkActivityIndicator;
890 - (void) releaseNetworkActivityIndicator;
891 - (void) clearPackage:(Package *)package;
892 - (void) installPackage:(Package *)package;
893 - (void) installPackages:(NSArray *)packages;
894 - (void) removePackage:(Package *)package;
895 - (void) beginUpdate;
897 - (void) distUpgrade;
901 - (void) addSource:(NSDictionary *)source;
902 - (void) addTrivialSource:(NSString *)href;
903 - (void) showSettings;
904 - (UIProgressHUD *) addProgressHUD;
905 - (void) removeProgressHUD:(UIProgressHUD *)hud;
906 - (CyteViewController *) pageForPackage:(NSString *)name;
907 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
908 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
912 /* Status Delegation {{{ */
914 public pkgAcquireStatus
917 _transient NSObject<ProgressDelegate> *delegate_;
927 void setDelegate(NSObject<ProgressDelegate> *delegate) {
928 delegate_ = delegate;
931 NSObject<ProgressDelegate> *getDelegate() const {
935 virtual bool MediaChange(std::string media, std::string drive) {
939 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
943 virtual void Fetch(pkgAcquire::ItemDesc &item) {
944 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
945 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
946 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
949 virtual void Done(pkgAcquire::ItemDesc &item) {
950 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
951 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
952 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
955 virtual void Fail(pkgAcquire::ItemDesc &item) {
957 item.Owner->Status == pkgAcquire::Item::StatIdle ||
958 item.Owner->Status == pkgAcquire::Item::StatDone
962 std::string &error(item.Owner->ErrorText);
966 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
967 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
970 virtual bool Pulse(pkgAcquire *Owner) {
971 bool value = pkgAcquireStatus::Pulse(Owner);
974 double(CurrentBytes + CurrentItems) /
975 double(TotalBytes + TotalItems)
978 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
979 [NSNumber numberWithDouble:percent], @"Percent",
981 [NSNumber numberWithDouble:CurrentBytes], @"Current",
982 [NSNumber numberWithDouble:TotalBytes], @"Total",
983 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
984 nil] waitUntilDone:YES];
986 if (value && ![delegate_ isProgressCancelled])
994 _finline bool WasCancelled() const {
998 virtual void Start() {
999 pkgAcquireStatus::Start();
1000 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1003 virtual void Stop() {
1004 pkgAcquireStatus::Stop();
1005 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1006 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1010 /* Database Interface {{{ */
1011 typedef std::map< unsigned long, _H<Source> > SourceMap;
1013 @interface Database : NSObject {
1019 pkgCacheFile cache_;
1020 pkgDepCache::Policy *policy_;
1021 pkgRecords *records_;
1022 pkgProblemResolver *resolver_;
1023 pkgAcquire *fetcher_;
1025 SPtr<pkgPackageManager> manager_;
1026 pkgSourceList *list_;
1028 SourceMap sourceMap_;
1029 _H<NSMutableArray> sourceList_;
1031 CFMutableArrayRef packages_;
1033 _transient NSObject<DatabaseDelegate> *delegate_;
1034 _transient NSObject<ProgressDelegate> *progress_;
1042 std::map<const char *, _H<NSString> > sections_;
1045 + (Database *) sharedInstance;
1048 - (void) _readCydia:(NSNumber *)fd;
1049 - (void) _readStatus:(NSNumber *)fd;
1050 - (void) _readOutput:(NSNumber *)fd;
1054 - (Package *) packageWithName:(NSString *)name;
1056 - (pkgCacheFile &) cache;
1057 - (pkgDepCache::Policy *) policy;
1058 - (pkgRecords *) records;
1059 - (pkgProblemResolver *) resolver;
1060 - (pkgAcquire &) fetcher;
1061 - (pkgSourceList &) list;
1062 - (NSArray *) packages;
1063 - (NSArray *) sources;
1064 - (Source *) sourceWithKey:(NSString *)key;
1065 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1073 - (void) updateWithStatus:(Status &)status;
1075 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1077 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1078 - (NSObject<ProgressDelegate> *) progressDelegate;
1080 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1082 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1086 /* ProgressEvent Implementation {{{ */
1087 @implementation CydiaProgressEvent
1089 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1090 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1093 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1094 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1095 [event setPackage:package];
1099 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1100 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1102 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1103 NSArray *fields([description componentsSeparatedByString:@" "]);
1104 [event setItem:fields];
1106 if ([fields count] > 3) {
1107 [event setPackage:[fields objectAtIndex:2]];
1108 [event setVersion:[fields objectAtIndex:3]];
1111 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1116 + (NSArray *) _attributeKeys {
1117 return [NSArray arrayWithObjects:
1127 - (NSArray *) attributeKeys {
1128 return [[self class] _attributeKeys];
1131 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1132 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1135 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1136 if ((self = [super init]) != nil) {
1142 - (NSString *) message {
1146 - (NSString *) type {
1150 - (NSArray *) item {
1151 return (id) item_ ?: [NSNull null];
1154 - (void) setItem:(NSArray *)item {
1158 - (NSString *) package {
1159 return (id) package_ ?: [NSNull null];
1162 - (void) setPackage:(NSString *)package {
1166 - (NSString *) url {
1167 return (id) url_ ?: [NSNull null];
1170 - (void) setURL:(NSString *)url {
1174 - (void) setVersion:(NSString *)version {
1178 - (NSString *) version {
1179 return (id) version_ ?: [NSNull null];
1182 - (NSString *) compound:(NSString *)value {
1184 NSString *mode(nil); {
1185 NSString *type([self type]);
1186 if ([type isEqualToString:kCydiaProgressEventTypeError])
1187 mode = UCLocalize("ERROR");
1188 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1189 mode = UCLocalize("WARNING");
1193 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1199 - (NSString *) compoundMessage {
1200 return [self compound:[self message]];
1203 - (NSString *) compoundTitle {
1206 if (package_ == nil)
1208 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1209 title = [package name];
1213 return [self compound:title];
1219 // Cytore Definitions {{{
1220 struct PackageValue :
1223 Cytore::Offset<PackageValue> next_;
1225 uint32_t index_ : 23;
1226 uint32_t subscribed_ : 1;
1243 Cytore::Offset<PackageValue> packages_[1 << 16];
1246 static Cytore::File<MetaValue> MetaFile_;
1248 // Cytore Helper Functions {{{
1249 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1250 SplitHash nhash = { hashlittle(name, length) };
1252 PackageValue *metadata;
1254 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1255 offset: if (offset->IsNull()) {
1256 *offset = MetaFile_.New<PackageValue>(length + 1);
1257 metadata = &MetaFile_.Get(*offset);
1259 if (metadata == NULL) {
1263 metadata = new PackageValue();
1264 memset(metadata, 0, sizeof(*metadata));
1267 memcpy(metadata->name_, name, length + 1);
1268 metadata->nhash_ = nhash.u16[1];
1270 metadata = &MetaFile_.Get(*offset);
1272 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1273 offset = &metadata->next_;
1281 static void PackageImport(const void *key, const void *value, void *context) {
1282 bool &fail(*reinterpret_cast<bool *>(context));
1285 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1286 NSLog(@"failed to import package %@", key);
1290 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1291 NSDictionary *package((NSDictionary *) value);
1293 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1294 if ([subscribed boolValue] && !metadata->subscribed_)
1295 metadata->subscribed_ = true;
1297 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1298 time_t time([date timeIntervalSince1970]);
1299 if (metadata->first_ > time || metadata->first_ == 0)
1300 metadata->first_ = time;
1303 NSDate *date([package objectForKey:@"LastSeen"]);
1304 NSString *version([package objectForKey:@"LastVersion"]);
1306 if (date != nil && version != nil) {
1307 time_t time([date timeIntervalSince1970]);
1308 if (metadata->last_ < time || metadata->last_ == 0)
1309 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1310 size_t length(strlen(buffer));
1311 uint16_t vhash(hashlittle(buffer, length));
1313 size_t capped(std::min<size_t>(8, length));
1314 char *latest(buffer + length - capped);
1316 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1317 metadata->vhash_ = vhash;
1319 metadata->last_ = time;
1325 /* Source Class {{{ */
1326 @interface Source : NSObject {
1328 Database *database_;
1331 CYString depiction_;
1332 CYString description_;
1338 CYString distribution_;
1344 _H<NSString> authority_;
1346 CYString defaultIcon_;
1348 _H<NSDictionary> record_;
1352 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1354 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1356 - (NSString *) depictionForPackage:(NSString *)package;
1357 - (NSString *) supportForPackage:(NSString *)package;
1359 - (NSDictionary *) record;
1363 - (NSString *) distribution;
1364 - (NSString *) type;
1366 - (NSString *) base;
1369 - (NSString *) host;
1371 - (NSString *) name;
1372 - (NSString *) shortDescription;
1373 - (NSString *) label;
1374 - (NSString *) origin;
1375 - (NSString *) version;
1377 - (NSString *) defaultIcon;
1381 @implementation Source
1385 distribution_.clear();
1390 description_.clear();
1396 defaultIcon_.clear();
1403 + (NSString *) webScriptNameForSelector:(SEL)selector {
1405 else if (selector == @selector(addSection:))
1406 return @"addSection";
1407 else if (selector == @selector(getField:))
1409 else if (selector == @selector(removeSection:))
1410 return @"removeSection";
1411 else if (selector == @selector(remove))
1417 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1418 return [self webScriptNameForSelector:selector] == nil;
1421 + (NSArray *) _attributeKeys {
1422 return [NSArray arrayWithObjects:
1430 @"shortDescription",
1438 - (NSArray *) attributeKeys {
1439 return [[self class] _attributeKeys];
1442 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1443 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1446 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1449 trusted_ = index->IsTrusted();
1451 uri_.set(pool, index->GetURI());
1452 distribution_.set(pool, index->GetDist());
1453 type_.set(pool, index->GetType());
1455 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1456 if (dindex != NULL) {
1457 base_.set(pool, dindex->MetaIndexURI(""));
1460 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1463 pkgTagFile tags(&fd);
1465 pkgTagSection section;
1472 {"default-icon", &defaultIcon_},
1473 {"depiction", &depiction_},
1474 {"description", &description_},
1476 {"origin", &origin_},
1477 {"support", &support_},
1478 {"version", &version_},
1481 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1482 const char *start, *end;
1484 if (section.Find(names[i].name_, start, end)) {
1485 CYString &value(*names[i].value_);
1486 value.set(pool, start, end - start);
1492 record_ = [Sources_ objectForKey:[self key]];
1494 NSURL *url([NSURL URLWithString:uri_]);
1498 host_ = [host_ lowercaseString];
1503 authority_ = [url path];
1506 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1507 if ((self = [super init]) != nil) {
1508 era_ = [database era];
1509 database_ = database;
1512 [self setMetaIndex:index inPool:pool];
1516 - (NSString *) getField:(NSString *)name {
1517 @synchronized (database_) {
1518 if ([database_ era] != era_ || index_ == NULL)
1521 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1526 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1531 pkgTagFile tags(&fd);
1533 pkgTagSection section;
1536 const char *start, *end;
1537 if (!section.Find([name UTF8String], start, end))
1538 return (NSString *) [NSNull null];
1540 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1543 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1544 NSDictionary *lhr = [self record];
1545 NSDictionary *rhr = [source record];
1547 if ((lhr == nil) != (rhr == nil))
1548 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1550 NSString *lhs = [self name];
1551 NSString *rhs = [source name];
1553 if ([lhs length] != 0 && [rhs length] != 0) {
1554 unichar lhc = [lhs characterAtIndex:0];
1555 unichar rhc = [rhs characterAtIndex:0];
1557 if (isalpha(lhc) && !isalpha(rhc))
1558 return NSOrderedAscending;
1559 else if (!isalpha(lhc) && isalpha(rhc))
1560 return NSOrderedDescending;
1563 return [lhs compare:rhs options:LaxCompareOptions_];
1566 - (NSString *) depictionForPackage:(NSString *)package {
1567 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1570 - (NSString *) supportForPackage:(NSString *)package {
1571 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1574 - (NSArray *) sections {
1575 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1578 - (void) _addSection:(NSString *)section {
1581 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1582 if (![sections containsObject:section]) {
1583 [sections addObject:section];
1587 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1592 - (bool) addSection:(NSString *)section {
1596 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1600 - (void) _removeSection:(NSString *)section {
1604 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1605 if ([sections containsObject:section]) {
1606 [sections removeObject:section];
1611 - (bool) removeSection:(NSString *)section {
1615 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1620 [Sources_ removeObjectForKey:[self key]];
1625 bool value(record_ != nil);
1626 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1630 - (NSDictionary *) record {
1638 - (NSString *) uri {
1642 - (NSString *) distribution {
1643 return distribution_;
1646 - (NSString *) type {
1650 - (NSString *) base {
1654 - (NSString *) key {
1655 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1658 - (NSString *) host {
1662 - (NSString *) name {
1663 return origin_.empty() ? (id) authority_ : origin_;
1666 - (NSString *) shortDescription {
1667 return description_;
1670 - (NSString *) label {
1671 return label_.empty() ? (id) authority_ : label_;
1674 - (NSString *) origin {
1678 - (NSString *) version {
1682 - (NSString *) defaultIcon {
1683 return defaultIcon_;
1688 /* CydiaOperation Class {{{ */
1689 @interface CydiaOperation : NSObject {
1690 _H<NSString> operator_;
1691 _H<NSString> value_;
1694 - (NSString *) operator;
1695 - (NSString *) value;
1699 @implementation CydiaOperation
1701 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1702 if ((self = [super init]) != nil) {
1703 operator_ = [NSString stringWithUTF8String:_operator];
1704 value_ = [NSString stringWithUTF8String:value];
1708 + (NSArray *) _attributeKeys {
1709 return [NSArray arrayWithObjects:
1715 - (NSArray *) attributeKeys {
1716 return [[self class] _attributeKeys];
1719 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1720 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1723 - (NSString *) operator {
1727 - (NSString *) value {
1733 /* CydiaClause Class {{{ */
1734 @interface CydiaClause : NSObject {
1735 _H<NSString> package_;
1736 _H<CydiaOperation> version_;
1739 - (NSString *) package;
1740 - (CydiaOperation *) version;
1744 @implementation CydiaClause
1746 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1747 if ((self = [super init]) != nil) {
1748 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1750 if (const char *version = dep.TargetVer())
1751 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1753 version_ = (id) [NSNull null];
1757 + (NSArray *) _attributeKeys {
1758 return [NSArray arrayWithObjects:
1764 - (NSArray *) attributeKeys {
1765 return [[self class] _attributeKeys];
1768 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1769 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1772 - (NSString *) package {
1776 - (CydiaOperation *) version {
1782 /* CydiaRelation Class {{{ */
1783 @interface CydiaRelation : NSObject {
1784 _H<NSString> relationship_;
1785 _H<NSMutableArray> clauses_;
1788 - (NSString *) relationship;
1789 - (NSArray *) clauses;
1793 @implementation CydiaRelation
1795 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1796 if ((self = [super init]) != nil) {
1797 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1798 clauses_ = [NSMutableArray arrayWithCapacity:8];
1800 pkgCache::DepIterator start;
1801 pkgCache::DepIterator end;
1802 dep.GlobOr(start, end); // ++dep
1805 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1807 // yes, seriously. (wtf?)
1815 + (NSArray *) _attributeKeys {
1816 return [NSArray arrayWithObjects:
1822 - (NSArray *) attributeKeys {
1823 return [[self class] _attributeKeys];
1826 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1827 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1830 - (NSString *) relationship {
1831 return relationship_;
1834 - (NSArray *) clauses {
1838 - (void) addClause:(CydiaClause *)clause {
1839 [clauses_ addObject:clause];
1844 /* Package Class {{{ */
1845 struct ParsedPackage {
1848 CYString architecture_;
1851 CYString depiction_;
1861 @interface Package : NSObject {
1864 uint32_t essential_ : 1;
1865 uint32_t obsolete_ : 1;
1866 uint32_t ignored_ : 1;
1872 _transient Database *database_;
1874 pkgCache::VerIterator version_;
1875 pkgCache::PkgIterator iterator_;
1876 pkgCache::VerFileIterator file_;
1882 CYString installed_;
1884 const char *section_;
1885 _transient NSString *section$_;
1889 PackageValue *metadata_;
1890 ParsedPackage *parsed_;
1892 _H<NSMutableArray> tags_;
1895 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1896 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1898 - (pkgCache::PkgIterator) iterator;
1901 - (NSString *) section;
1902 - (NSString *) simpleSection;
1904 - (NSString *) longSection;
1905 - (NSString *) shortSection;
1909 - (MIMEAddress *) maintainer;
1911 - (NSString *) longDescription;
1912 - (NSString *) shortDescription;
1915 - (PackageValue *) metadata;
1918 - (bool) subscribed;
1919 - (bool) setSubscribed:(bool)subscribed;
1923 - (NSString *) latest;
1924 - (NSString *) installed;
1925 - (BOOL) uninstalled;
1928 - (BOOL) upgradableAndEssential:(BOOL)essential;
1931 - (BOOL) unfiltered;
1935 - (BOOL) halfConfigured;
1936 - (BOOL) halfInstalled;
1938 - (NSString *) mode;
1941 - (NSString *) name;
1943 - (NSString *) homepage;
1944 - (NSString *) depiction;
1945 - (MIMEAddress *) author;
1947 - (NSString *) support;
1949 - (NSArray *) files;
1950 - (NSArray *) warnings;
1951 - (NSArray *) applications;
1953 - (Source *) source;
1956 - (BOOL) matches:(NSArray *)query;
1958 - (bool) hasSupportingRole;
1959 - (BOOL) hasTag:(NSString *)tag;
1960 - (NSString *) primaryPurpose;
1961 - (NSArray *) purposes;
1962 - (bool) isCommercial;
1964 - (void) setIndex:(size_t)index;
1966 - (CYString &) cyname;
1968 - (uint32_t) compareBySection:(NSArray *)sections;
1973 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1974 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1975 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1976 - (bool) isVisibleInSection:(NSString *)section;
1977 - (bool) isVisibleInSource:(Source *)source;
1981 uint32_t PackageChangesRadix(Package *self, void *) {
1986 uint32_t timestamp : 30;
1987 uint32_t ignored : 1;
1988 uint32_t upgradable : 1;
1992 bool upgradable([self upgradableAndEssential:YES]);
1993 value.bits.upgradable = upgradable ? 1 : 0;
1996 value.bits.timestamp = 0;
1997 value.bits.ignored = [self ignored] ? 0 : 1;
1998 value.bits.upgradable = 1;
2000 value.bits.timestamp = [self seen] >> 2;
2001 value.bits.ignored = 0;
2002 value.bits.upgradable = 0;
2005 return _not(uint32_t) - value.key;
2008 uint32_t PackagePrefixRadix(Package *self, void *context) {
2009 size_t offset(reinterpret_cast<size_t>(context));
2010 CYString &name([self cyname]);
2012 size_t size(name.size());
2015 char *text(name.data());
2018 if (!isdigit(text[0]))
2022 while (size != digits && isdigit(text[digits]))
2030 if (offset == 0 && zeros != 0) {
2031 memset(data, '0', zeros);
2032 memcpy(data + zeros, text, 4 - zeros);
2034 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2035 if (size <= offset - zeros)
2038 text += offset - zeros;
2039 size -= offset - zeros;
2042 memcpy(data, text, 4);
2044 memcpy(data, text, size);
2045 memset(data + size, 0, 4 - size);
2048 for (size_t i(0); i != 4; ++i)
2049 if (isalpha(data[i]))
2057 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2059 /* XXX: ntohl may be more honest */
2060 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2063 CYString &(*PackageName)(Package *self, SEL sel);
2065 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2066 _profile(PackageNameCompare)
2067 CYString &lhi(PackageName(lhs, @selector(cyname)));
2068 CYString &rhi(PackageName(rhs, @selector(cyname)));
2069 CFStringRef lhn(lhi), rhn(rhi);
2072 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2073 else if (rhn == NULL)
2074 return NSOrderedDescending;
2076 _profile(PackageNameCompare$NumbersLast)
2077 if (!lhi.empty() && !rhi.empty()) {
2078 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2079 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2080 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2081 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2082 return lha ? NSOrderedAscending : NSOrderedDescending;
2086 CFIndex length = CFStringGetLength(lhn);
2088 _profile(PackageNameCompare$Compare)
2089 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2094 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2095 return PackageNameCompare(*lhs, *rhs, context);
2098 struct PackageNameOrdering :
2099 std::binary_function<Package *, Package *, bool>
2101 _finline bool operator ()(Package *lhs, Package *rhs) const {
2102 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2106 @implementation Package
2108 - (NSString *) description {
2109 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2113 if (parsed_ != NULL)
2118 + (NSString *) webScriptNameForSelector:(SEL)selector {
2120 else if (selector == @selector(clear))
2122 else if (selector == @selector(getField:))
2124 else if (selector == @selector(hasTag:))
2126 else if (selector == @selector(install))
2128 else if (selector == @selector(remove))
2134 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2135 return [self webScriptNameForSelector:selector] == nil;
2138 + (NSArray *) _attributeKeys {
2139 return [NSArray arrayWithObjects:
2159 @"shortDescription",
2172 - (NSArray *) attributeKeys {
2173 return [[self class] _attributeKeys];
2176 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2177 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2180 - (NSArray *) relations {
2181 @synchronized (database_) {
2182 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2183 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2184 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2188 - (NSString *) architecture {
2190 @synchronized (database_) {
2191 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2194 - (NSString *) getField:(NSString *)name {
2195 @synchronized (database_) {
2196 if ([database_ era] != era_ || file_.end())
2199 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2201 const char *start, *end;
2202 if (!parser.Find([name UTF8String], start, end))
2203 return (NSString *) [NSNull null];
2205 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2209 if (parsed_ != NULL)
2211 @synchronized (database_) {
2212 if ([database_ era] != era_ || file_.end())
2215 ParsedPackage *parsed(new ParsedPackage);
2218 _profile(Package$parse)
2219 pkgRecords::Parser *parser;
2221 _profile(Package$parse$Lookup)
2222 parser = &[database_ records]->Lookup(file_);
2227 _profile(Package$parse$Find)
2232 {"architecture", &parsed->architecture_},
2233 {"icon", &parsed->icon_},
2234 {"depiction", &parsed->depiction_},
2235 {"homepage", &parsed->homepage_},
2236 {"website", &website},
2237 {"bugs", &parsed->bugs_},
2238 {"support", &parsed->support_},
2239 {"sponsor", &parsed->sponsor_},
2240 {"author", &parsed->author_},
2243 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2244 const char *start, *end;
2246 if (parser->Find(names[i].name_, start, end)) {
2247 CYString &value(*names[i].value_);
2248 _profile(Package$parse$Value)
2249 value.set(pool_, start, end - start);
2255 _profile(Package$parse$Tagline)
2256 const char *start, *end;
2257 if (parser->ShortDesc(start, end)) {
2258 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2261 while (stop != start && stop[-1] == '\r')
2263 parsed->tagline_.set(pool_, start, stop - start);
2267 _profile(Package$parse$Retain)
2268 if (parsed->homepage_.empty())
2269 parsed->homepage_ = website;
2270 if (parsed->homepage_ == parsed->depiction_)
2271 parsed->homepage_.clear();
2276 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2277 if ((self = [super init]) != nil) {
2278 _profile(Package$initWithVersion)
2281 database_ = database;
2282 era_ = [database era];
2286 pkgCache::PkgIterator iterator(version.ParentPkg());
2287 iterator_ = iterator;
2289 _profile(Package$initWithVersion$Version)
2290 if (!version_.end())
2291 file_ = version_.FileList();
2293 pkgCache &cache([database_ cache]);
2294 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2298 _profile(Package$initWithVersion$Cache)
2299 name_.set(NULL, iterator.Display());
2301 latest_.set(NULL, StripVersion_(version_.VerStr()));
2303 pkgCache::VerIterator current(iterator.CurrentVer());
2305 installed_.set(NULL, StripVersion_(current.VerStr()));
2308 _profile(Package$initWithVersion$Tags)
2309 pkgCache::TagIterator tag(iterator.TagList());
2311 tags_ = [NSMutableArray arrayWithCapacity:8];
2313 const char *name(tag.Name());
2314 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2316 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2317 if (strcmp(name + 6, "enduser") == 0)
2319 else if (strcmp(name + 6, "hacker") == 0)
2321 else if (strcmp(name + 6, "developer") == 0)
2323 else if (strcmp(name + 6, "cydia") == 0)
2329 if (strncmp(name, "cydia::", 7) == 0) {
2330 if (strcmp(name + 7, "essential") == 0)
2332 else if (strcmp(name + 7, "obsolete") == 0)
2337 } while (!tag.end());
2341 _profile(Package$initWithVersion$Metadata)
2342 const char *mixed(iterator.Name());
2343 size_t size(strlen(mixed));
2344 char lower[size + 1];
2346 for (size_t i(0); i != size; ++i)
2347 lower[i] = mixed[i] | 0x20;
2350 PackageValue *metadata(PackageFind(lower, size));
2351 metadata_ = metadata;
2353 id_.set(NULL, metadata->name_, size);
2355 const char *latest(version_.VerStr());
2356 size_t length(strlen(latest));
2358 uint16_t vhash(hashlittle(latest, length));
2360 size_t capped(std::min<size_t>(8, length));
2361 latest = latest + length - capped;
2363 if (metadata->first_ == 0)
2364 metadata->first_ = now_;
2366 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2367 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2368 metadata->vhash_ = vhash;
2369 metadata->last_ = now_;
2370 } else if (metadata->last_ == 0)
2371 metadata->last_ = metadata->first_;
2374 _profile(Package$initWithVersion$Section)
2375 section_ = iterator.Section();
2378 _profile(Package$initWithVersion$Flags)
2379 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2380 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2385 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2386 pkgCache::VerIterator version;
2388 _profile(Package$packageWithIterator$GetCandidateVer)
2389 version = [database policy]->GetCandidateVer(iterator);
2397 _profile(Package$packageWithIterator$Allocate)
2398 package = [Package allocWithZone:zone];
2401 _profile(Package$packageWithIterator$Initialize)
2403 initWithVersion:version
2410 _profile(Package$packageWithIterator$Autorelease)
2411 package = [package autorelease];
2417 - (pkgCache::PkgIterator) iterator {
2421 - (NSString *) section {
2422 if (section$_ == nil) {
2423 if (section_ == NULL)
2426 _profile(Package$section$mappedSectionForPointer)
2427 section$_ = [database_ mappedSectionForPointer:section_];
2432 - (NSString *) simpleSection {
2433 if (NSString *section = [self section])
2434 return Simplify(section);
2439 - (NSString *) longSection {
2440 return LocalizeSection([self section]);
2443 - (NSString *) shortSection {
2444 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2447 - (NSString *) uri {
2450 pkgIndexFile *index;
2451 pkgCache::PkgFileIterator file(file_.File());
2452 if (![database_ list].FindIndex(file, index))
2454 return [NSString stringWithUTF8String:iterator_->Path];
2455 //return [NSString stringWithUTF8String:file.Site()];
2456 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2460 - (MIMEAddress *) maintainer {
2461 @synchronized (database_) {
2462 if ([database_ era] != era_ || file_.end())
2465 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2466 const std::string &maintainer(parser->Maintainer());
2467 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2471 @synchronized (database_) {
2472 if ([database_ era] != era_ || version_.end())
2475 return version_->InstalledSize;
2478 - (NSString *) longDescription {
2479 @synchronized (database_) {
2480 if ([database_ era] != era_ || file_.end())
2483 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2484 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2486 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2487 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2488 if ([lines count] < 2)
2491 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2492 for (size_t i(1), e([lines count]); i != e; ++i) {
2493 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2494 [trimmed addObject:trim];
2497 return [trimmed componentsJoinedByString:@"\n"];
2500 - (NSString *) shortDescription {
2501 if (parsed_ != NULL)
2502 return static_cast<NSString *>(parsed_->tagline_);
2504 @synchronized (database_) {
2505 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2507 const char *start, *end;
2508 if (!parser.ShortDesc(start, end))
2511 if (end - start > 200)
2515 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2518 while (end != start && end[-1] == '\r')
2522 return [(id) CYStringCreate(start, end - start) autorelease];
2526 _profile(Package$index)
2527 CFStringRef name((CFStringRef) [self name]);
2528 if (CFStringGetLength(name) == 0)
2530 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2531 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2533 return toupper(character);
2537 - (PackageValue *) metadata {
2542 PackageValue *metadata([self metadata]);
2543 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2546 - (bool) subscribed {
2547 return [self metadata]->subscribed_;
2550 - (bool) setSubscribed:(bool)subscribed {
2551 PackageValue *metadata([self metadata]);
2552 if (metadata->subscribed_ == subscribed)
2554 metadata->subscribed_ = subscribed;
2562 - (NSString *) latest {
2566 - (NSString *) installed {
2570 - (BOOL) uninstalled {
2571 return installed_.empty();
2575 return !version_.end();
2578 - (BOOL) upgradableAndEssential:(BOOL)essential {
2579 _profile(Package$upgradableAndEssential)
2580 pkgCache::VerIterator current(iterator_.CurrentVer());
2582 return essential && essential_;
2584 return !version_.end() && version_ != current;
2588 - (BOOL) essential {
2593 return [database_ cache][iterator_].InstBroken();
2596 - (BOOL) unfiltered {
2597 _profile(Package$unfiltered$obsolete)
2598 if (_unlikely(obsolete_))
2602 _profile(Package$unfiltered$hasSupportingRole)
2603 if (_unlikely(![self hasSupportingRole]))
2611 if (![self unfiltered])
2616 _profile(Package$visible$section)
2617 section = [self section];
2620 _profile(Package$visible$isSectionVisible)
2621 if (!isSectionVisible(section))
2629 unsigned char current(iterator_->CurrentState);
2630 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2633 - (BOOL) halfConfigured {
2634 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2637 - (BOOL) halfInstalled {
2638 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2642 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2643 return state.Mode != pkgDepCache::ModeKeep;
2646 - (NSString *) mode {
2647 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2649 switch (state.Mode) {
2650 case pkgDepCache::ModeDelete:
2651 if ((state.iFlags & pkgDepCache::Purge) != 0)
2655 case pkgDepCache::ModeKeep:
2656 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2657 return @"REINSTALL";
2658 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2662 case pkgDepCache::ModeInstall:
2663 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2664 return @"REINSTALL";
2665 else*/ switch (state.Status) {
2667 return @"DOWNGRADE";
2673 return @"NEW_INSTALL";
2684 - (NSString *) name {
2685 return name_.empty() ? id_ : name_;
2688 - (UIImage *) icon {
2689 NSString *section = [self simpleSection];
2692 if (parsed_ != NULL)
2693 if (NSString *href = parsed_->icon_)
2694 if ([href hasPrefix:@"file:///"])
2695 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2696 if (icon == nil) if (section != nil)
2697 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2698 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2699 if ([dicon hasPrefix:@"file:///"])
2700 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2702 icon = [UIImage applicationImageNamed:@"unknown.png"];
2706 - (NSString *) homepage {
2707 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2710 - (NSString *) depiction {
2711 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2714 - (MIMEAddress *) sponsor {
2715 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2718 - (MIMEAddress *) author {
2719 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2722 - (NSString *) support {
2723 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2726 - (NSArray *) files {
2727 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2728 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2731 fin.open([path UTF8String]);
2736 while (std::getline(fin, line))
2737 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2742 - (NSString *) state {
2743 @synchronized (database_) {
2744 if ([database_ era] != era_ || file_.end())
2747 switch (iterator_->CurrentState) {
2748 case pkgCache::State::NotInstalled:
2749 return @"NotInstalled";
2750 case pkgCache::State::UnPacked:
2752 case pkgCache::State::HalfConfigured:
2753 return @"HalfConfigured";
2754 case pkgCache::State::HalfInstalled:
2755 return @"HalfInstalled";
2756 case pkgCache::State::ConfigFiles:
2757 return @"ConfigFiles";
2758 case pkgCache::State::Installed:
2759 return @"Installed";
2760 case pkgCache::State::TriggersAwaited:
2761 return @"TriggersAwaited";
2762 case pkgCache::State::TriggersPending:
2763 return @"TriggersPending";
2766 return (NSString *) [NSNull null];
2769 - (NSString *) selection {
2770 @synchronized (database_) {
2771 if ([database_ era] != era_ || file_.end())
2774 switch (iterator_->SelectedState) {
2775 case pkgCache::State::Unknown:
2777 case pkgCache::State::Install:
2779 case pkgCache::State::Hold:
2781 case pkgCache::State::DeInstall:
2782 return @"DeInstall";
2783 case pkgCache::State::Purge:
2787 return (NSString *) [NSNull null];
2790 - (NSArray *) warnings {
2791 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2792 const char *name(iterator_.Name());
2794 size_t length(strlen(name));
2795 if (length < 2) invalid:
2796 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2797 else for (size_t i(0); i != length; ++i)
2799 /* XXX: technically this is not allowed */
2800 (name[i] < 'A' || name[i] > 'Z') &&
2801 (name[i] < 'a' || name[i] > 'z') &&
2802 (name[i] < '0' || name[i] > '9') &&
2803 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2806 if (strcmp(name, "cydia") != 0) {
2809 bool _private = false;
2812 bool repository = [[self section] isEqualToString:@"Repositories"];
2814 if (NSArray *files = [self files])
2815 for (NSString *file in files)
2816 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2818 else if (!user && [file isEqualToString:@"/User"])
2820 else if (!_private && [file isEqualToString:@"/private"])
2822 else if (!stash && [file isEqualToString:@"/var/stash"])
2825 /* XXX: this is not sensitive enough. only some folders are valid. */
2826 if (cydia && !repository)
2827 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2829 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2831 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2833 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2836 return [warnings count] == 0 ? nil : warnings;
2839 - (NSArray *) applications {
2840 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2842 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2844 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2845 if (NSArray *files = [self files])
2846 for (NSString *file in files)
2847 if (application_r(file)) {
2848 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2849 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2850 if ([id isEqualToString:me])
2853 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2855 display = application_r[1];
2857 NSString *bundle([file stringByDeletingLastPathComponent]);
2858 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2859 if (icon == nil || [icon length] == 0)
2861 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2863 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2864 [applications addObject:application];
2866 [application addObject:id];
2867 [application addObject:display];
2868 [application addObject:url];
2871 return [applications count] == 0 ? nil : applications;
2874 - (Source *) source {
2875 if (source_ == nil) {
2876 @synchronized (database_) {
2877 if ([database_ era] != era_ || file_.end())
2878 source_ = (Source *) [NSNull null];
2880 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2884 return source_ == (Source *) [NSNull null] ? nil : source_;
2891 - (BOOL) matches:(NSArray *)query {
2892 if (query == nil || [query count] == 0)
2901 string = [self name];
2902 length = [string length];
2904 for (NSString *term in query) {
2905 range = [string rangeOfString:term options:MatchCompareOptions_];
2906 if (range.location != NSNotFound)
2907 rank_ -= 6 * 1000000 / length;
2912 length = [string length];
2914 for (NSString *term in query) {
2915 range = [string rangeOfString:term options:MatchCompareOptions_];
2916 if (range.location != NSNotFound)
2917 rank_ -= 6 * 1000000 / length;
2921 string = [self shortDescription];
2922 length = [string length];
2923 NSUInteger stop(std::min<NSUInteger>(length, 200));
2925 for (NSString *term in query) {
2926 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2927 if (range.location != NSNotFound)
2928 rank_ -= 2 * 100000;
2934 - (bool) hasSupportingRole {
2939 if ([Role_ isEqualToString:@"User"])
2943 if ([Role_ isEqualToString:@"Hacker"])
2947 if ([Role_ isEqualToString:@"Developer"])
2952 - (NSArray *) tags {
2956 - (BOOL) hasTag:(NSString *)tag {
2957 return tags_ == nil ? NO : [tags_ containsObject:tag];
2960 - (NSString *) primaryPurpose {
2961 for (NSString *tag in (NSArray *) tags_)
2962 if ([tag hasPrefix:@"purpose::"])
2963 return [tag substringFromIndex:9];
2967 - (NSArray *) purposes {
2968 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2969 for (NSString *tag in (NSArray *) tags_)
2970 if ([tag hasPrefix:@"purpose::"])
2971 [purposes addObject:[tag substringFromIndex:9]];
2972 return [purposes count] == 0 ? nil : purposes;
2975 - (bool) isCommercial {
2976 return [self hasTag:@"cydia::commercial"];
2979 - (void) setIndex:(size_t)index {
2980 if (metadata_->index_ != index)
2981 metadata_->index_ = index;
2984 - (CYString &) cyname {
2985 return name_.empty() ? id_ : name_;
2988 - (uint32_t) compareBySection:(NSArray *)sections {
2989 NSString *section([self section]);
2990 for (size_t i(0), e([sections count]); i != e; ++i) {
2991 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2995 return _not(uint32_t);
2999 @synchronized (database_) {
3000 pkgProblemResolver *resolver = [database_ resolver];
3001 resolver->Clear(iterator_);
3003 pkgCacheFile &cache([database_ cache]);
3004 cache->SetReInstall(iterator_, false);
3005 cache->MarkKeep(iterator_, false);
3009 @synchronized (database_) {
3010 pkgProblemResolver *resolver = [database_ resolver];
3011 resolver->Clear(iterator_);
3012 resolver->Protect(iterator_);
3014 pkgCacheFile &cache([database_ cache]);
3015 cache->SetReInstall(iterator_, false);
3016 cache->MarkInstall(iterator_, false);
3018 pkgDepCache::StateCache &state((*cache)[iterator_]);
3019 if (!state.Install())
3020 cache->SetReInstall(iterator_, true);
3024 @synchronized (database_) {
3025 pkgProblemResolver *resolver = [database_ resolver];
3026 resolver->Clear(iterator_);
3027 resolver->Remove(iterator_);
3028 resolver->Protect(iterator_);
3030 pkgCacheFile &cache([database_ cache]);
3031 cache->SetReInstall(iterator_, false);
3032 cache->MarkDelete(iterator_, true);
3035 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3036 _profile(Package$isUnfilteredAndSearchedForBy)
3039 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3040 value &= [self unfiltered];
3043 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3044 value &= [self matches:query];
3051 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3052 if ([search length] == 0)
3055 _profile(Package$isUnfilteredAndSelectedForBy)
3058 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3059 value &= [self unfiltered];
3062 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3063 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3070 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3071 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3074 - (bool) isVisibleInSection:(NSString *)name {
3075 NSString *section([self section]);
3079 section == nil && [name length] == 0 ||
3080 [name isEqualToString:section]
3081 ) && [self visible];
3084 - (bool) isVisibleInSource:(Source *)source {
3085 return [self source] == source && [self visible];
3090 /* Section Class {{{ */
3091 @interface Section : NSObject {
3096 _H<NSString> localized_;
3099 - (NSComparisonResult) compareByLocalized:(Section *)section;
3100 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3101 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3102 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3103 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3104 - (NSString *) name;
3111 - (void) addToCount;
3113 - (void) setCount:(size_t)count;
3114 - (NSString *) localized;
3118 @implementation Section
3120 - (NSComparisonResult) compareByLocalized:(Section *)section {
3121 NSString *lhs(localized_);
3122 NSString *rhs([section localized]);
3124 /*if ([lhs length] != 0 && [rhs length] != 0) {
3125 unichar lhc = [lhs characterAtIndex:0];
3126 unichar rhc = [rhs characterAtIndex:0];
3128 if (isalpha(lhc) && !isalpha(rhc))
3129 return NSOrderedAscending;
3130 else if (!isalpha(lhc) && isalpha(rhc))
3131 return NSOrderedDescending;
3134 return [lhs compare:rhs options:LaxCompareOptions_];
3137 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3138 if ((self = [self initWithName:name localize:NO]) != nil) {
3139 if (localized != nil)
3140 localized_ = localized;
3144 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3145 return [self initWithName:name row:0 localize:localize];
3148 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3149 if ((self = [super init]) != nil) {
3154 localized_ = LocalizeSection(name_);
3158 /* XXX: localize the index thingees */
3159 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3160 if ((self = [super init]) != nil) {
3161 name_ = [NSString stringWithCharacters:&index length:1];
3167 - (NSString *) name {
3187 - (void) addToCount {
3191 - (void) setCount:(size_t)count {
3195 - (NSString *) localized {
3202 class CydiaLogCleaner :
3203 public pkgArchiveCleaner
3206 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3211 /* Database Implementation {{{ */
3212 @implementation Database
3214 + (Database *) sharedInstance {
3215 static _H<Database> instance;
3216 if (instance == nil)
3217 instance = [[[Database alloc] init] autorelease];
3225 - (void) releasePackages {
3226 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3227 CFArrayRemoveAllValues(packages_);
3231 // XXX: actually implement this thing
3233 [self releasePackages];
3234 apr_pool_destroy(pool_);
3235 NSRecycleZone(zone_);
3239 - (void) _readCydia:(NSNumber *)fd {
3240 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3241 std::istream is(&ib);
3244 static Pcre finish_r("^finish:([^:]*)$");
3246 while (std::getline(is, line)) {
3247 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3249 const char *data(line.c_str());
3250 size_t size = line.size();
3251 lprintf("C:%s\n", data);
3253 if (finish_r(data, size)) {
3254 NSString *finish = finish_r[1];
3255 int index = [Finishes_ indexOfObject:finish];
3256 if (index != INT_MAX && index > Finish_)
3266 - (void) _readStatus:(NSNumber *)fd {
3267 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3268 std::istream is(&ib);
3271 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3272 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3274 while (std::getline(is, line)) {
3275 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3277 const char *data(line.c_str());
3278 size_t size(line.size());
3279 lprintf("S:%s\n", data);
3281 if (conffile_r(data, size)) {
3282 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3283 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3284 } else if (strncmp(data, "status: ", 8) == 0) {
3285 // status: <package>: {unpacked,half-configured,installed}
3286 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3287 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3288 } else if (strncmp(data, "processing: ", 12) == 0) {
3289 // processing: configure: config-test
3290 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3291 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3292 } else if (pmstatus_r(data, size)) {
3293 std::string type([pmstatus_r[1] UTF8String]);
3295 NSString *package = pmstatus_r[2];
3296 if ([package isEqualToString:@"dpkg-exec"])
3299 float percent([pmstatus_r[3] floatValue]);
3300 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3302 NSString *string = pmstatus_r[4];
3304 if (type == "pmerror") {
3305 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3306 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3307 } else if (type == "pmstatus") {
3308 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3309 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3310 } else if (type == "pmconffile")
3311 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3313 lprintf("E:unknown pmstatus\n");
3315 lprintf("E:unknown status\n");
3323 - (void) _readOutput:(NSNumber *)fd {
3324 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3325 std::istream is(&ib);
3328 while (std::getline(is, line)) {
3329 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3331 lprintf("O:%s\n", line.c_str());
3333 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3334 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3346 - (Package *) packageWithName:(NSString *)name {
3349 @synchronized (self) {
3350 if (static_cast<pkgDepCache *>(cache_) == NULL)
3352 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3353 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3357 if ((self = [super init]) != nil) {
3364 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3365 apr_pool_create(&pool_, NULL);
3367 size_t capacity(MetaFile_->active_);
3373 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3374 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3378 _assert(pipe(fds) != -1);
3381 _config->Set("APT::Keep-Fds::", cydiafd_);
3382 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3385 detachNewThreadSelector:@selector(_readCydia:)
3387 withObject:[NSNumber numberWithInt:fds[0]]
3390 _assert(pipe(fds) != -1);
3394 detachNewThreadSelector:@selector(_readStatus:)
3396 withObject:[NSNumber numberWithInt:fds[0]]
3399 _assert(pipe(fds) != -1);
3400 _assert(dup2(fds[0], 0) != -1);
3401 _assert(close(fds[0]) != -1);
3403 input_ = fdopen(fds[1], "a");
3405 _assert(pipe(fds) != -1);
3406 _assert(dup2(fds[1], 1) != -1);
3407 _assert(close(fds[1]) != -1);
3410 detachNewThreadSelector:@selector(_readOutput:)
3412 withObject:[NSNumber numberWithInt:fds[0]]
3417 - (pkgCacheFile &) cache {
3421 - (pkgDepCache::Policy *) policy {
3425 - (pkgRecords *) records {
3429 - (pkgProblemResolver *) resolver {
3433 - (pkgAcquire &) fetcher {
3437 - (pkgSourceList &) list {
3441 - (NSArray *) packages {
3442 return (NSArray *) packages_;
3445 - (NSArray *) sources {
3449 - (Source *) sourceWithKey:(NSString *)key {
3450 for (Source *source in [self sources]) {
3451 if ([[source key] isEqualToString:key])
3456 - (bool) popErrorWithTitle:(NSString *)title {
3459 while (!_error->empty()) {
3461 bool warning(!_error->PopMessage(error));
3466 size_t size(error.size());
3467 if (size == 0 || error[size - 1] != '\n')
3469 error.resize(size - 1);
3472 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3474 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3480 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3481 return [self popErrorWithTitle:title] || !success;
3484 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3485 @synchronized (self) {
3488 [self releasePackages];
3491 [sourceList_ removeAllObjects];
3511 apr_pool_clear(pool_);
3513 NSRecycleZone(zone_);
3514 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3516 int chk(creat("/tmp/cydia.chk", 0644));
3520 if (invocation != nil)
3521 [invocation invoke];
3523 NSString *title(UCLocalize("DATABASE"));
3526 OpProgress progress;
3527 while (!cache_.Open(progress, true)) { pop:
3529 bool warning(!_error->PopMessage(error));
3530 lprintf("cache_.Open():[%s]\n", error.c_str());
3532 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3533 [delegate_ repairWithSelector:@selector(configure)];
3534 else if (error == "The package lists or status file could not be parsed or opened.")
3535 [delegate_ repairWithSelector:@selector(update)];
3536 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3537 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3538 // else if (error == "Malformed Status line")
3539 // else if (error == "The list of sources could not be read.")
3541 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3551 unlink("/tmp/cydia.chk");
3553 now_ = [[NSDate date] timeIntervalSince1970];
3555 policy_ = new pkgDepCache::Policy();
3556 records_ = new pkgRecords(cache_);
3557 resolver_ = new pkgProblemResolver(cache_);
3558 fetcher_ = new pkgAcquire(&status_);
3561 list_ = new pkgSourceList();
3562 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3565 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3566 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3570 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3573 if (cache_->BrokenCount() != 0) {
3574 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3577 if (cache_->BrokenCount() != 0) {
3578 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3582 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3586 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3587 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3588 [sourceList_ addObject:object];
3590 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3591 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3592 // XXX: this could be more intelligent
3593 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3594 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3596 sourceMap_[cached->ID] = object;
3601 /*std::vector<Package *> packages;
3602 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3607 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3608 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3609 //packages.push_back(package);
3610 CFArrayAppendValue(packages_, CFRetain(package));
3614 /*if (packages.empty())
3615 packages_ = [[NSArray alloc] init];
3617 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3620 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3621 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3622 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3630 /*if (!packages.empty())
3631 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3632 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3634 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3636 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3638 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3642 size_t count(CFArrayGetCount(packages_));
3643 MetaFile_->active_ = count;
3645 for (size_t index(0); index != count; ++index)
3646 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3653 @synchronized (self) {
3655 resolver_ = new pkgProblemResolver(cache_);
3657 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3658 if (!cache_[iterator].Keep())
3659 cache_->MarkKeep(iterator, false);
3660 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3661 cache_->SetReInstall(iterator, false);
3664 - (void) configure {
3665 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3667 system([dpkg UTF8String]);
3672 // XXX: I don't remember this condition
3677 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3679 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3681 if ([self popErrorWithTitle:title])
3685 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3687 CydiaLogCleaner cleaner;
3688 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3695 fetcher_->Shutdown();
3697 pkgRecords records(cache_);
3699 lock_ = new FileFd();
3700 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3702 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3704 if ([self popErrorWithTitle:title])
3708 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3711 manager_ = (_system->CreatePM(cache_));
3712 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3719 bool substrate(RestartSubstrate_);
3720 RestartSubstrate_ = false;
3722 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3724 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3726 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3728 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3729 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3732 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3734 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3736 [self popErrorWithTitle:title];
3740 bool failed = false;
3741 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3742 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3744 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3750 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3758 RestartSubstrate_ = true;
3761 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3763 if (_error->PendingError()) {
3768 if (result == pkgPackageManager::Failed) {
3773 if (result != pkgPackageManager::Completed) {
3778 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3780 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3782 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3783 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3786 if (![before isEqualToArray:after])
3791 NSString *title(UCLocalize("UPGRADE"));
3792 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3798 [self updateWithStatus:status_];
3801 - (void) updateWithStatus:(Status &)status {
3802 NSString *title(UCLocalize("REFRESHING_DATA"));
3805 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3809 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3810 if ([self popErrorWithTitle:title])
3813 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3815 bool success(ListUpdate(status, list, PulseInterval_));
3816 if (status.WasCancelled())
3819 [self popErrorWithTitle:title forOperation:success];
3820 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3824 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3827 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3828 delegate_ = delegate;
3831 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3832 progress_ = delegate;
3833 status_.setDelegate(delegate);
3836 - (NSObject<ProgressDelegate> *) progressDelegate {
3840 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3841 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3842 return i == sourceMap_.end() ? nil : i->second;
3845 - (NSString *) mappedSectionForPointer:(const char *)section {
3846 _H<NSString> *mapped;
3848 _profile(Database$mappedSectionForPointer$Cache)
3849 mapped = §ions_[section];
3852 if (*mapped == NULL) {
3853 size_t length(strlen(section));
3854 char spaced[length + 1];
3856 _profile(Database$mappedSectionForPointer$Replace)
3857 for (size_t index(0); index != length; ++index)
3858 spaced[index] = section[index] == '_' ? ' ' : section[index];
3859 spaced[length] = '\0';
3864 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3865 string = [NSString stringWithUTF8String:spaced];
3868 _profile(Database$mappedSectionForPointer$Map)
3869 string = [SectionMap_ objectForKey:string] ?: string;
3879 static _H<NSMutableSet> Diversions_;
3881 @interface Diversion : NSObject {
3884 _H<NSString> format_;
3889 @implementation Diversion
3891 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3892 if ((self = [super init]) != nil) {
3893 pattern_ = [from UTF8String];
3899 - (NSString *) divert:(NSString *)url {
3900 return !pattern_(url) ? nil : pattern_->*format_;
3903 + (NSURL *) divertURL:(NSURL *)url {
3905 NSString *href([url absoluteString]);
3907 for (Diversion *diversion in (id) Diversions_)
3908 if (NSString *diverted = [diversion divert:href]) {
3910 NSLog(@"div: %@", diverted);
3912 url = [NSURL URLWithString:diverted];
3919 - (NSString *) key {
3923 - (NSUInteger) hash {
3927 - (BOOL) isEqual:(Diversion *)object {
3928 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3933 @interface CydiaObject : NSObject {
3934 _H<IndirectDelegate> indirect_;
3935 _transient id delegate_;
3938 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3942 @interface CydiaWebViewController : CyteWebViewController {
3943 _H<CydiaObject> cydia_;
3946 + (void) addDiversion:(Diversion *)diversion;
3950 /* Web Scripting {{{ */
3951 @implementation CydiaObject
3953 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3954 if ((self = [super init]) != nil) {
3955 indirect_ = indirect;
3959 - (void) setDelegate:(id)delegate {
3960 delegate_ = delegate;
3963 + (NSArray *) _attributeKeys {
3964 return [NSArray arrayWithObjects:
3981 - (NSArray *) attributeKeys {
3982 return [[self class] _attributeKeys];
3985 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3986 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3989 - (NSString *) version {
3993 - (NSString *) device {
3994 return [[UIDevice currentDevice] uniqueIdentifier];
3997 - (NSString *) firmware {
3998 return [[UIDevice currentDevice] systemVersion];
4001 - (NSString *) hostname {
4002 return [[UIDevice currentDevice] name];
4005 - (NSString *) idiom {
4006 return (id) Idiom_ ?: [NSNull null];
4009 - (NSString *) plmn {
4010 return (id) PLMN_ ?: [NSNull null];
4013 - (NSString *) bbsnum {
4014 return (id) BBSNum_ ?: [NSNull null];
4017 - (NSString *) ecid {
4018 return (id) ChipID_ ?: [NSNull null];
4021 - (NSString *) serial {
4022 return SerialNumber_;
4025 - (NSString *) role {
4026 return (id) Role_ ?: [NSNull null];
4029 - (NSString *) model {
4030 return [NSString stringWithUTF8String:Machine_];
4033 - (NSString *) token {
4034 return (id) Token_ ?: [NSNull null];
4037 + (NSString *) webScriptNameForSelector:(SEL)selector {
4039 else if (selector == @selector(addBridgedHost:))
4040 return @"addBridgedHost";
4041 else if (selector == @selector(addInsecureHost:))
4042 return @"addInsecureHost";
4043 else if (selector == @selector(addInternalRedirect::))
4044 return @"addInternalRedirect";
4045 else if (selector == @selector(addPipelinedHost:scheme:))
4046 return @"addPipelinedHost";
4047 else if (selector == @selector(addSource:::))
4048 return @"addSource";
4049 else if (selector == @selector(addTokenHost:))
4050 return @"addTokenHost";
4051 else if (selector == @selector(addTrivialSource:))
4052 return @"addTrivialSource";
4053 else if (selector == @selector(close))
4055 else if (selector == @selector(du:))
4057 else if (selector == @selector(stringWithFormat:arguments:))
4059 else if (selector == @selector(getAllSources))
4060 return @"getAllSourcs";
4061 else if (selector == @selector(getKernelNumber:))
4062 return @"getKernelNumber";
4063 else if (selector == @selector(getKernelString:))
4064 return @"getKernelString";
4065 else if (selector == @selector(getInstalledPackages))
4066 return @"getInstalledPackages";
4067 else if (selector == @selector(getIORegistryEntry::))
4068 return @"getIORegistryEntry";
4069 else if (selector == @selector(getLocaleIdentifier))
4070 return @"getLocaleIdentifier";
4071 else if (selector == @selector(getPreferredLanguages))
4072 return @"getPreferredLanguages";
4073 else if (selector == @selector(getPackageById:))
4074 return @"getPackageById";
4075 else if (selector == @selector(getMetadataKeys))
4076 return @"getMetadataKeys";
4077 else if (selector == @selector(getMetadataValue:))
4078 return @"getMetadataValue";
4079 else if (selector == @selector(getSessionValue:))
4080 return @"getSessionValue";
4081 else if (selector == @selector(installPackages:))
4082 return @"installPackages";
4083 else if (selector == @selector(localizedStringForKey:value:table:))
4085 else if (selector == @selector(popViewController:))
4086 return @"popViewController";
4087 else if (selector == @selector(refreshSources))
4088 return @"refreshSources";
4089 else if (selector == @selector(removeButton))
4090 return @"removeButton";
4091 else if (selector == @selector(saveConfig))
4092 return @"saveConfig";
4093 else if (selector == @selector(setCydiaSource:))
4094 return @"setCydiaSource";
4095 else if (selector == @selector(setMetadataValue::))
4096 return @"setMetadataValue";
4097 else if (selector == @selector(setSessionValue::))
4098 return @"setSessionValue";
4099 else if (selector == @selector(substitutePackageNames:))
4100 return @"substitutePackageNames";
4101 else if (selector == @selector(scrollToBottom:))
4102 return @"scrollToBottom";
4103 else if (selector == @selector(setAllowsNavigationAction:))
4104 return @"setAllowsNavigationAction";
4105 else if (selector == @selector(setBadgeValue:))
4106 return @"setBadgeValue";
4107 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4108 return @"setButtonImage";
4109 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4110 return @"setButtonTitle";
4111 else if (selector == @selector(setHidesBackButton:))
4112 return @"setHidesBackButton";
4113 else if (selector == @selector(setHidesNavigationBar:))
4114 return @"setHidesNavigationBar";
4115 else if (selector == @selector(setNavigationBarStyle:))
4116 return @"setNavigationBarStyle";
4117 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4118 return @"setNavigationBarTintColor";
4119 else if (selector == @selector(setPasteboardString:))
4120 return @"setPasteboardString";
4121 else if (selector == @selector(setPasteboardURL:))
4122 return @"setPasteboardURL";
4123 else if (selector == @selector(setToken:))
4125 else if (selector == @selector(setViewportWidth:))
4126 return @"setViewportWidth";
4127 else if (selector == @selector(statfs:))
4129 else if (selector == @selector(supports:))
4131 else if (selector == @selector(unload))
4137 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4138 return [self webScriptNameForSelector:selector] == nil;
4141 - (BOOL) supports:(NSString *)feature {
4142 return [feature isEqualToString:@"window.open"];
4146 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4149 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4150 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4153 - (NSNumber *) getKernelNumber:(NSString *)name {
4154 const char *string([name UTF8String]);
4157 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4158 return (id) [NSNull null];
4160 if (size != sizeof(int))
4161 return (id) [NSNull null];
4164 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4165 return (id) [NSNull null];
4167 return [NSNumber numberWithInt:value];
4170 - (NSString *) getKernelString:(NSString *)name {
4171 const char *string([name UTF8String]);
4174 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4175 return (id) [NSNull null];
4177 char value[size + 1];
4178 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4179 return (id) [NSNull null];
4181 // XXX: just in case you request something ludicrous
4184 return [NSString stringWithCString:value];
4187 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4188 NSObject *value(CYIOGetValue([path UTF8String], entry));
4191 if ([value isKindOfClass:[NSData class]])
4192 value = CYHex((NSData *) value);
4197 - (void) _setCydiaSource:(NSString *)source {
4198 @synchronized (HostConfig_) {
4199 CydiaSource_ = source;
4200 [Metadata_ setObject:source forKey:@"CydiaSource"];
4206 - (void) setCydiaSource:(NSString *)source {
4207 [self performSelectorOnMainThread:@selector(_setCydiaSource:) withObject:source waitUntilDone:NO];
4210 - (NSString *) cydiaSource {
4211 @synchronized (HostConfig_) {
4212 return (id) CydiaSource_ ?: [NSNull null];
4216 - (NSArray *) getMetadataKeys {
4217 @synchronized (Values_) {
4218 return [Values_ allKeys];
4221 - (id) getMetadataValue:(NSString *)key {
4222 @synchronized (Values_) {
4223 return [Values_ objectForKey:key];
4226 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4227 @synchronized (Values_) {
4228 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4229 [Values_ removeObjectForKey:key];
4231 [Values_ setObject:value forKey:key];
4233 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4236 - (id) getSessionValue:(NSString *)key {
4237 @synchronized (SessionData_) {
4238 return [SessionData_ objectForKey:key];
4241 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4242 @synchronized (SessionData_) {
4243 if (value == (id) [WebUndefined undefined])
4244 [SessionData_ removeObjectForKey:key];
4246 [SessionData_ setObject:value forKey:key];
4249 - (void) addBridgedHost:(NSString *)host {
4250 @synchronized (HostConfig_) {
4251 [BridgedHosts_ addObject:host];
4254 - (void) addInsecureHost:(NSString *)host {
4255 @synchronized (HostConfig_) {
4256 [InsecureHosts_ addObject:host];
4259 - (void) addTokenHost:(NSString *)host {
4260 @synchronized (HostConfig_) {
4261 [TokenHosts_ addObject:host];
4264 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4265 @synchronized (HostConfig_) {
4266 if (scheme != (id) [WebUndefined undefined])
4267 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4269 [PipelinedHosts_ addObject:host];
4272 - (void) popViewController:(NSNumber *)value {
4273 if (value == (id) [WebUndefined undefined])
4274 value = [NSNumber numberWithBool:YES];
4275 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4278 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4279 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4281 for (NSString *section in sections)
4282 [array addObject:section];
4284 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4287 distribution, @"Distribution",
4289 nil] waitUntilDone:NO];
4292 - (void) addTrivialSource:(NSString *)href {
4293 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4296 - (void) refreshSources {
4297 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4300 - (void) saveConfig {
4301 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4304 - (NSArray *) getAllSources {
4305 return [[Database sharedInstance] sources];
4308 - (NSArray *) getInstalledPackages {
4309 Database *database([Database sharedInstance]);
4310 @synchronized (database) {
4311 NSArray *packages([database packages]);
4312 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4313 for (Package *package in packages)
4314 if (![package uninstalled])
4315 [installed addObject:package];
4319 - (Package *) getPackageById:(NSString *)id {
4320 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4324 return (Package *) [NSNull null];
4327 - (NSString *) getLocaleIdentifier {
4328 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4331 - (NSArray *) getPreferredLanguages {
4335 - (NSArray *) statfs:(NSString *)path {
4338 if (path == nil || statfs([path UTF8String], &stat) == -1)
4341 return [NSArray arrayWithObjects:
4342 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4343 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4344 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4348 - (NSNumber *) du:(NSString *)path {
4349 NSNumber *value(nil);
4352 _assert(pipe(fds) != -1);
4354 pid_t pid(ExecFork());
4356 _assert(dup2(fds[1], 1) != -1);
4357 _assert(close(fds[0]) != -1);
4358 _assert(close(fds[1]) != -1);
4359 /* XXX: this should probably not use du */
4360 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4365 _assert(close(fds[1]) != -1);
4367 if (FILE *du = fdopen(fds[0], "r")) {
4369 while (fgets(line, sizeof(line), du) != NULL) {
4370 size_t length(strlen(line));
4371 while (length != 0 && line[length - 1] == '\n')
4372 line[--length] = '\0';
4373 if (char *tab = strchr(line, '\t')) {
4375 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4380 } else _assert(close(fds[0]));
4384 if (waitpid(pid, &status, 0) == -1)
4387 else _assert(false);
4393 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4396 - (void) installPackages:(NSArray *)packages {
4397 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4400 - (NSString *) substitutePackageNames:(NSString *)message {
4401 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4402 for (size_t i(0), e([words count]); i != e; ++i) {
4403 NSString *word([words objectAtIndex:i]);
4404 if (Package *package = [[Database sharedInstance] packageWithName:word])
4405 [words replaceObjectAtIndex:i withObject:[package name]];
4408 return [words componentsJoinedByString:@" "];
4411 - (void) removeButton {
4412 [indirect_ removeButton];
4415 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4416 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4419 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4420 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4423 - (void) setBadgeValue:(id)value {
4424 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4427 - (void) setAllowsNavigationAction:(NSString *)value {
4428 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4431 - (void) setHidesBackButton:(NSString *)value {
4432 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4435 - (void) setHidesNavigationBar:(NSString *)value {
4436 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4439 - (void) setNavigationBarStyle:(NSString *)value {
4440 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4443 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4444 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4445 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4446 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4449 - (void) setPasteboardString:(NSString *)value {
4450 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4453 - (void) setPasteboardURL:(NSString *)value {
4454 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4457 - (void) _setToken:(NSString *)token {
4461 [Metadata_ removeObjectForKey:@"Token"];
4463 [Metadata_ setObject:Token_ forKey:@"Token"];
4468 - (void) setToken:(NSString *)token {
4469 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4472 - (void) scrollToBottom:(NSNumber *)animated {
4473 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4476 - (void) setViewportWidth:(float)width {
4477 [indirect_ setViewportWidthOnMainThread:width];
4480 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4481 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4482 unsigned count([arguments count]);
4484 for (unsigned i(0); i != count; ++i)
4485 values[i] = [arguments objectAtIndex:i];
4486 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4489 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4490 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4492 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4494 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4500 @interface NSURL (CydiaSecure)
4503 @implementation NSURL (CydiaSecure)
4505 - (bool) isCydiaSecure {
4506 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4509 @synchronized (HostConfig_) {
4510 if ([InsecureHosts_ containsObject:[self host]])
4519 /* Cydia Browser Controller {{{ */
4520 @implementation CydiaWebViewController
4522 - (NSURL *) navigationURL {
4523 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4526 + (void) initialize {
4527 Diversions_ = [NSMutableSet setWithCapacity:0];
4530 + (void) addDiversion:(Diversion *)diversion {
4531 [Diversions_ addObject:diversion];
4534 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4535 [super webView:view didClearWindowObject:window forFrame:frame];
4537 WebDataSource *source([frame dataSource]);
4538 NSURLResponse *response([source response]);
4539 NSURL *url([response URL]);
4540 NSString *scheme([[url scheme] lowercaseString]);
4542 bool bridged(false);
4544 @synchronized (HostConfig_) {
4545 if ([scheme isEqualToString:@"file"])
4547 else if ([scheme isEqualToString:@"https"])
4548 if ([BridgedHosts_ containsObject:[url host]])
4553 [window setValue:cydia_ forKey:@"cydia"];
4556 - (void) _setupMail:(MFMailComposeViewController *)controller {
4557 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4559 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4560 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4563 - (NSURL *) URLWithURL:(NSURL *)url {
4564 return [Diversion divertURL:url];
4567 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4568 NSURL *url([request URL]);
4569 NSString *host([url host]);
4571 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4573 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4574 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4575 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4576 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4579 @synchronized (HostConfig_) {
4580 token = [TokenHosts_ containsObject:host] || [BridgedHosts_ containsObject:host];
4583 if ([url isCydiaSecure] && token) {
4584 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4585 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4591 - (void) setDelegate:(id)delegate {
4592 [super setDelegate:delegate];
4593 [cydia_ setDelegate:delegate];
4596 - (NSString *) applicationNameForUserAgent {
4597 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4600 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4602 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4603 if (Product_ != nil)
4604 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4610 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4611 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4617 @interface AppCacheController : CydiaWebViewController {
4622 @implementation AppCacheController
4624 - (void) didReceiveMemoryWarning {
4631 @interface NSObject (CydiaScript)
4632 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4635 @implementation NSObject (CydiaScript)
4637 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4643 @implementation NSArray (CydiaScript)
4645 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4646 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4647 for (size_t i(0), e([self count]); i != e; ++i)
4648 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4654 @implementation NSDictionary (CydiaScript)
4656 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4657 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4659 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4666 /* Confirmation Controller {{{ */
4667 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4668 if (!iterator.end())
4669 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4670 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4672 pkgCache::PkgIterator package(dep.TargetPkg());
4675 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4682 @protocol ConfirmationControllerDelegate
4683 - (void) cancelAndClear:(bool)clear;
4684 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4688 @interface ConfirmationController : CydiaWebViewController {
4689 _transient Database *database_;
4691 _H<UIAlertView> essential_;
4693 _H<NSDictionary> changes_;
4694 _H<NSMutableArray> issues_;
4695 _H<NSDictionary> sizes_;
4700 - (id) initWithDatabase:(Database *)database;
4704 @implementation ConfirmationController
4708 RestartSubstrate_ = true;
4709 [delegate_ confirmWithNavigationController:[self navigationController]];
4712 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4713 NSString *context([alert context]);
4715 if ([context isEqualToString:@"remove"]) {
4716 if (button == [alert cancelButtonIndex])
4717 [self dismissModalViewControllerAnimated:YES];
4718 else if (button == [alert firstOtherButtonIndex]) {
4722 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4723 } else if ([context isEqualToString:@"unable"]) {
4724 [self dismissModalViewControllerAnimated:YES];
4725 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4727 [super alertView:alert clickedButtonAtIndex:button];
4731 - (void) _doContinue {
4732 [delegate_ cancelAndClear:NO];
4733 [self dismissModalViewControllerAnimated:YES];
4736 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4737 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4741 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4742 [super webView:view didClearWindowObject:window forFrame:frame];
4744 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4745 (id) changes_, @"changes",
4746 (id) issues_, @"issues",
4747 (id) sizes_, @"sizes",
4749 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4752 - (id) initWithDatabase:(Database *)database {
4753 if ((self = [super init]) != nil) {
4754 database_ = database;
4756 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4757 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4758 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4759 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4760 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4764 pkgCacheFile &cache([database_ cache]);
4765 NSArray *packages([database_ packages]);
4766 pkgDepCache::Policy *policy([database_ policy]);
4768 issues_ = [NSMutableArray arrayWithCapacity:4];
4770 for (Package *package in packages) {
4771 pkgCache::PkgIterator iterator([package iterator]);
4772 NSString *name([package id]);
4774 if ([package broken]) {
4775 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4777 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4779 reasons, @"reasons",
4782 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4786 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4787 pkgCache::DepIterator start;
4788 pkgCache::DepIterator end;
4789 dep.GlobOr(start, end); // ++dep
4791 if (!cache->IsImportantDep(end))
4793 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4796 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4798 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4799 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4800 clauses, @"clauses",
4804 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4806 pkgCache::PkgIterator target(start.TargetPkg());
4807 if (target->ProvidesList != 0)
4808 reason = @"missing";
4810 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4812 reason = @"installed";
4813 installed = [NSString stringWithUTF8String:ver.VerStr()];
4814 } else if (!cache[target].CandidateVerIter(cache).end())
4815 reason = @"uninstalled";
4816 else if (target->ProvidesList == 0)
4817 reason = @"uninstallable";
4819 reason = @"virtual";
4822 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4823 [NSString stringWithUTF8String:start.CompType()], @"operator",
4824 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4827 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4828 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4829 version, @"version",
4831 installed, @"installed",
4834 // yes, seriously. (wtf?)
4842 pkgDepCache::StateCache &state(cache[iterator]);
4844 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4846 if (state.NewInstall())
4847 [installs addObject:name];
4848 // XXX: else if (state.Install())
4849 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4850 [reinstalls addObject:name];
4851 // XXX: move before previous if
4852 else if (state.Upgrade())
4853 [upgrades addObject:name];
4854 else if (state.Downgrade())
4855 [downgrades addObject:name];
4856 else if (!state.Delete())
4857 // XXX: _assert(state.Keep());
4859 else if (special_r(name))
4860 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4861 [NSNull null], @"package",
4862 [NSArray arrayWithObjects:
4863 [NSDictionary dictionaryWithObjectsAndKeys:
4864 @"Conflicts", @"relationship",
4865 [NSArray arrayWithObjects:
4866 [NSDictionary dictionaryWithObjectsAndKeys:
4868 [NSNull null], @"version",
4869 @"installed", @"reason",
4876 if ([package essential])
4878 [removes addObject:name];
4881 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4882 substrate_ |= DepSubstrate(iterator.CurrentVer());
4887 else if (Advanced_) {
4888 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4890 essential_ = [[[UIAlertView alloc]
4891 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4892 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4894 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4896 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4900 [essential_ setContext:@"remove"];
4902 essential_ = [[[UIAlertView alloc]
4903 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4904 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4906 cancelButtonTitle:UCLocalize("OKAY")
4907 otherButtonTitles:nil
4910 [essential_ setContext:@"unable"];
4913 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4914 installs, @"installs",
4915 reinstalls, @"reinstalls",
4916 upgrades, @"upgrades",
4917 downgrades, @"downgrades",
4918 removes, @"removes",
4921 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4922 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4923 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4926 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4930 - (UIBarButtonItem *) leftButton {
4931 return [[[UIBarButtonItem alloc]
4932 initWithTitle:UCLocalize("CANCEL")
4933 style:UIBarButtonItemStylePlain
4935 action:@selector(cancelButtonClicked)
4940 - (void) applyRightButton {
4941 if ([issues_ count] == 0 && ![self isLoading])
4942 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4943 initWithTitle:UCLocalize("CONFIRM")
4944 style:UIBarButtonItemStyleDone
4946 action:@selector(confirmButtonClicked)
4949 [[self navigationItem] setRightBarButtonItem:nil];
4953 - (void) cancelButtonClicked {
4954 [self dismissModalViewControllerAnimated:YES];
4955 [delegate_ cancelAndClear:YES];
4959 - (void) confirmButtonClicked {
4960 if (essential_ != nil)
4970 /* Progress Data {{{ */
4971 @interface CydiaProgressData : NSObject {
4972 _transient id delegate_;
4981 _H<NSMutableArray> events_;
4982 _H<NSString> title_;
4984 _H<NSString> status_;
4985 _H<NSString> finish_;
4990 @implementation CydiaProgressData
4992 + (NSArray *) _attributeKeys {
4993 return [NSArray arrayWithObjects:
5005 - (NSArray *) attributeKeys {
5006 return [[self class] _attributeKeys];
5009 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5010 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5014 if ((self = [super init]) != nil) {
5015 events_ = [NSMutableArray arrayWithCapacity:32];
5019 - (void) setDelegate:(id)delegate {
5020 delegate_ = delegate;
5023 - (void) setPercent:(float)value {
5027 - (NSNumber *) percent {
5028 return [NSNumber numberWithFloat:percent_];
5031 - (void) setCurrent:(float)value {
5035 - (NSNumber *) current {
5036 return [NSNumber numberWithFloat:current_];
5039 - (void) setTotal:(float)value {
5043 - (NSNumber *) total {
5044 return [NSNumber numberWithFloat:total_];
5047 - (void) setSpeed:(float)value {
5051 - (NSNumber *) speed {
5052 return [NSNumber numberWithFloat:speed_];
5055 - (NSArray *) events {
5059 - (void) removeAllEvents {
5060 [events_ removeAllObjects];
5063 - (void) addEvent:(CydiaProgressEvent *)event {
5064 [events_ addObject:event];
5067 - (void) setTitle:(NSString *)text {
5071 - (NSString *) title {
5075 - (void) setFinish:(NSString *)text {
5079 - (NSString *) finish {
5080 return (id) finish_ ?: [NSNull null];
5083 - (void) setRunning:(bool)running {
5087 - (NSNumber *) running {
5088 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5093 /* Progress Controller {{{ */
5094 @interface ProgressController : CydiaWebViewController <
5097 _transient Database *database_;
5098 _H<CydiaProgressData, 1> progress_;
5102 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5104 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5106 - (void) setTitle:(NSString *)title;
5107 - (void) setCancellable:(bool)cancellable;
5111 @implementation ProgressController
5114 [database_ setProgressDelegate:nil];
5118 - (UIBarButtonItem *) leftButton {
5119 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5120 initWithTitle:UCLocalize("CANCEL")
5121 style:UIBarButtonItemStylePlain
5123 action:@selector(cancel)
5124 ] autorelease] : nil;
5127 - (void) updateCancel {
5128 [super applyLeftButton];
5131 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5132 if ((self = [super init]) != nil) {
5133 database_ = database;
5134 delegate_ = delegate;
5136 [database_ setProgressDelegate:self];
5138 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5139 [progress_ setDelegate:self];
5141 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5143 [scroller_ setBackgroundColor:[UIColor blackColor]];
5145 [[self navigationItem] setHidesBackButton:YES];
5147 [self updateCancel];
5151 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5152 [super webView:view didClearWindowObject:window forFrame:frame];
5153 [window setValue:progress_ forKey:@"cydiaProgress"];
5156 - (void) updateProgress {
5157 [self dispatchEvent:@"CydiaProgressUpdate"];
5160 - (void) viewWillAppear:(BOOL)animated {
5161 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5162 [super viewWillAppear:animated];
5166 UpdateExternalStatus(0);
5169 [delegate_ saveState];
5173 [delegate_ returnToCydia];
5177 [delegate_ terminateWithSuccess];
5178 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5179 [delegate_ suspendWithAnimation:YES];
5181 [delegate_ suspend];*/
5193 system("/usr/bin/sbreload");
5199 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5200 SBReboot(SBSSpringBoardServerPort());
5202 reboot2(RB_AUTOBOOT);
5209 - (void) setTitle:(NSString *)title {
5210 [progress_ setTitle:title];
5211 [self updateProgress];
5214 - (UIBarButtonItem *) rightButton {
5215 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5216 initWithTitle:UCLocalize("CLOSE")
5217 style:UIBarButtonItemStylePlain
5219 action:@selector(close)
5223 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5224 UpdateExternalStatus(1);
5226 [progress_ setRunning:true];
5227 [self setTitle:title];
5228 // implicit updateProgress
5230 SHA1SumValue notifyconf; {
5232 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5235 MMap mmap(file, MMap::ReadOnly);
5237 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5238 notifyconf = sha1.Result();
5242 SHA1SumValue springlist; {
5244 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5247 MMap mmap(file, MMap::ReadOnly);
5249 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5250 springlist = sha1.Result();
5254 if (invocation != nil) {
5255 [invocation yieldToSelector:@selector(invoke)];
5256 [self setTitle:@"COMPLETE"];
5261 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5264 MMap mmap(file, MMap::ReadOnly);
5266 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5267 if (!(notifyconf == sha1.Result()))
5274 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5277 MMap mmap(file, MMap::ReadOnly);
5279 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5280 if (!(springlist == sha1.Result()))
5286 if (RestartSubstrate_)
5290 RestartSubstrate_ = false;
5293 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5294 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5295 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5296 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5297 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5301 system("su -c /usr/bin/uicache mobile");
5304 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5306 [progress_ setRunning:false];
5307 [self updateProgress];
5309 [self applyRightButton];
5312 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5313 [progress_ addEvent:event];
5314 [self updateProgress];
5317 - (bool) isProgressCancelled {
5318 return cancel_ == 2;
5323 [self updateCancel];
5326 - (void) setCancellable:(bool)cancellable {
5327 unsigned cancel(cancel_);
5331 else if (cancel_ == 0)
5334 if (cancel != cancel_)
5335 [self updateCancel];
5338 - (void) setProgressCancellable:(NSNumber *)cancellable {
5339 [self setCancellable:[cancellable boolValue]];
5342 - (void) setProgressPercent:(NSNumber *)percent {
5343 [progress_ setPercent:[percent floatValue]];
5344 [self updateProgress];
5347 - (void) setProgressStatus:(NSDictionary *)status {
5348 if (status == nil) {
5349 [progress_ setCurrent:0];
5350 [progress_ setTotal:0];
5351 [progress_ setSpeed:0];
5353 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5355 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5356 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5357 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5360 [self updateProgress];
5366 /* Package Cell {{{ */
5367 @interface PackageCell : CyteTableViewCell <
5368 CyteTableViewCellDelegate
5372 _H<NSString> description_;
5374 _H<NSString> source_;
5376 _H<UIImage> placard_;
5380 - (PackageCell *) init;
5381 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5383 - (void) drawContentRect:(CGRect)rect;
5387 @implementation PackageCell
5389 - (PackageCell *) init {
5390 CGRect frame(CGRectMake(0, 0, 320, 74));
5391 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5392 UIView *content([self contentView]);
5393 CGRect bounds([content bounds]);
5395 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5396 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5397 [content addSubview:content_];
5399 [content_ setDelegate:self];
5400 [content_ setOpaque:YES];
5404 - (NSString *) accessibilityLabel {
5405 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5408 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5409 summarized_ = summary;
5419 [content_ setBackgroundColor:[UIColor whiteColor]];
5423 Source *source = [package source];
5425 icon_ = [package icon];
5427 if (NSString *name = [package name])
5428 name_ = [NSString stringWithString:name];
5430 NSString *description(nil);
5432 if (description == nil && IsWildcat_)
5433 description = [package longDescription];
5434 if (description == nil)
5435 description = [package shortDescription];
5437 if (description != nil)
5438 description_ = [NSString stringWithString:description];
5440 commercial_ = [package isCommercial];
5442 NSString *label = nil;
5443 bool trusted = false;
5445 if (source != nil) {
5446 label = [source label];
5447 trusted = [source trusted];
5448 } else if ([[package id] isEqualToString:@"firmware"])
5449 label = UCLocalize("APPLE");
5451 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5453 NSString *from(label);
5455 NSString *section = [package simpleSection];
5456 if (section != nil && ![section isEqualToString:label]) {
5457 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5458 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5461 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5463 if (NSString *purpose = [package primaryPurpose])
5464 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5469 if (NSString *mode = [package mode]) {
5470 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5471 color = RemovingColor_;
5472 //placard = @"removing";
5474 color = InstallingColor_;
5475 //placard = @"installing";
5478 // XXX: the removing/installing placards are not @2x
5481 color = [UIColor whiteColor];
5483 if ([package installed] != nil)
5484 placard = @"installed";
5489 [content_ setBackgroundColor:color];
5492 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5495 [self setNeedsDisplay];
5496 [content_ setNeedsDisplay];
5499 - (void) drawSummaryContentRect:(CGRect)rect {
5500 bool highlighted(highlighted_);
5501 float width([self bounds].size.width);
5505 rect.size = [(UIImage *) icon_ size];
5507 rect.size.width /= 4;
5508 rect.size.height /= 4;
5510 rect.origin.x = 14 - rect.size.width / 4;
5511 rect.origin.y = 14 - rect.size.height / 4;
5513 [icon_ drawInRect:rect];
5516 if (badge_ != nil) {
5518 rect.size = [(UIImage *) badge_ size];
5520 rect.size.width /= 4;
5521 rect.size.height /= 4;
5523 rect.origin.x = 20 - rect.size.width / 4;
5524 rect.origin.y = 20 - rect.size.height / 4;
5526 [badge_ drawInRect:rect];
5533 UISetColor(commercial_ ? Purple_ : Black_);
5534 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5536 if (placard_ != nil)
5537 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5540 - (void) drawNormalContentRect:(CGRect)rect {
5541 bool highlighted(highlighted_);
5542 float width([self bounds].size.width);
5546 rect.size = [(UIImage *) icon_ size];
5548 rect.size.width /= 2;
5549 rect.size.height /= 2;
5551 rect.origin.x = 25 - rect.size.width / 2;
5552 rect.origin.y = 25 - rect.size.height / 2;
5554 [icon_ drawInRect:rect];
5557 if (badge_ != nil) {
5559 rect.size = [(UIImage *) badge_ size];
5561 rect.size.width /= 2;
5562 rect.size.height /= 2;
5564 rect.origin.x = 36 - rect.size.width / 2;
5565 rect.origin.y = 36 - rect.size.height / 2;
5567 [badge_ drawInRect:rect];
5574 UISetColor(commercial_ ? Purple_ : Black_);
5575 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5576 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5579 UISetColor(commercial_ ? Purplish_ : Gray_);
5580 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5582 if (placard_ != nil)
5583 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5586 - (void) drawContentRect:(CGRect)rect {
5588 [self drawSummaryContentRect:rect];
5590 [self drawNormalContentRect:rect];
5595 /* Section Cell {{{ */
5596 @interface SectionCell : CyteTableViewCell <
5597 CyteTableViewCellDelegate
5599 _H<NSString> basic_;
5600 _H<NSString> section_;
5602 _H<NSString> count_;
5604 _H<UISwitch> switch_;
5608 - (void) setSection:(Section *)section editing:(BOOL)editing;
5612 @implementation SectionCell
5614 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5615 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5616 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5617 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5618 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5620 UIView *content([self contentView]);
5621 CGRect bounds([content bounds]);
5623 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5624 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5625 [content addSubview:content_];
5626 [content_ setBackgroundColor:[UIColor whiteColor]];
5628 [content_ setDelegate:self];
5632 - (void) onSwitch:(id)sender {
5633 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5634 if (metadata == nil) {
5635 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5636 [Sections_ setObject:metadata forKey:basic_];
5639 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5643 - (void) setSection:(Section *)section editing:(BOOL)editing {
5644 if (editing != editing_) {
5646 [switch_ removeFromSuperview];
5648 [self addSubview:switch_];
5657 if (section == nil) {
5658 name_ = UCLocalize("ALL_PACKAGES");
5661 basic_ = [section name];
5662 section_ = [section localized];
5664 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5665 count_ = [NSString stringWithFormat:@"%d", [section count]];
5668 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5671 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5672 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5674 [content_ setNeedsDisplay];
5677 - (void) setFrame:(CGRect)frame {
5678 [super setFrame:frame];
5680 CGRect rect([switch_ frame]);
5681 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5684 - (NSString *) accessibilityLabel {
5688 - (void) drawContentRect:(CGRect)rect {
5689 bool highlighted(highlighted_ && !editing_);
5691 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5696 float width(rect.size.width);
5702 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5704 CGSize size = [count_ sizeWithFont:Font14_];
5708 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5714 /* File Table {{{ */
5715 @interface FileTable : CyteViewController <
5716 UITableViewDataSource,
5719 _transient Database *database_;
5720 _H<Package> package_;
5722 _H<NSMutableArray> files_;
5723 _H<UITableView, 2> list_;
5726 - (id) initWithDatabase:(Database *)database;
5727 - (void) setPackage:(Package *)package;
5731 @implementation FileTable
5733 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5734 return files_ == nil ? 0 : [files_ count];
5737 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5741 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5742 static NSString *reuseIdentifier = @"Cell";
5744 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5746 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5747 [cell setFont:[UIFont systemFontOfSize:16]];
5749 [cell setText:[files_ objectAtIndex:indexPath.row]];
5750 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5755 - (NSURL *) navigationURL {
5756 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5760 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5762 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5763 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5764 [list_ setRowHeight:24.0f];
5765 [(UITableView *) list_ setDataSource:self];
5766 [list_ setDelegate:self];
5767 [[self view] addSubview:list_];
5770 - (void) viewDidLoad {
5771 [super viewDidLoad];
5773 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5776 - (void) releaseSubviews {
5782 [super releaseSubviews];
5785 - (id) initWithDatabase:(Database *)database {
5786 if ((self = [super init]) != nil) {
5787 database_ = database;
5791 - (void) setPackage:(Package *)package {
5795 files_ = [NSMutableArray arrayWithCapacity:32];
5797 if (package != nil) {
5799 name_ = [package id];
5801 if (NSArray *files = [package files])
5802 [files_ addObjectsFromArray:files];
5804 if ([files_ count] != 0) {
5805 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5806 [files_ removeObjectAtIndex:0];
5807 [files_ sortUsingSelector:@selector(compareByPath:)];
5809 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5810 [stack addObject:@"/"];
5812 for (int i(0), e([files_ count]); i != e; ++i) {
5813 NSString *file = [files_ objectAtIndex:i];
5814 while (![file hasPrefix:[stack lastObject]])
5815 [stack removeLastObject];
5816 NSString *directory = [stack lastObject];
5817 [stack addObject:[file stringByAppendingString:@"/"]];
5818 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5819 ([stack count] - 2) * 3, "",
5820 [file substringFromIndex:[directory length]]
5829 - (void) reloadData {
5832 [self setPackage:[database_ packageWithName:name_]];
5837 /* Package Controller {{{ */
5838 @interface CYPackageController : CydiaWebViewController <
5839 UIActionSheetDelegate
5841 _transient Database *database_;
5842 _H<Package> package_;
5845 _H<NSMutableArray> buttons_;
5846 _H<UIBarButtonItem> button_;
5849 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5853 @implementation CYPackageController
5855 - (NSURL *) navigationURL {
5856 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5859 /* XXX: this is not safe at all... localization of /fail/ */
5860 - (void) _clickButtonWithName:(NSString *)name {
5861 if ([name isEqualToString:UCLocalize("CLEAR")])
5862 [delegate_ clearPackage:package_];
5863 else if ([name isEqualToString:UCLocalize("INSTALL")])
5864 [delegate_ installPackage:package_];
5865 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5866 [delegate_ installPackage:package_];
5867 else if ([name isEqualToString:UCLocalize("REMOVE")])
5868 [delegate_ removePackage:package_];
5869 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5870 [delegate_ installPackage:package_];
5871 else _assert(false);
5874 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5875 NSString *context([sheet context]);
5877 if ([context isEqualToString:@"modify"]) {
5878 if (button != [sheet cancelButtonIndex]) {
5879 NSString *buttonName = [buttons_ objectAtIndex:button];
5880 [self _clickButtonWithName:buttonName];
5883 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5887 - (bool) _allowJavaScriptPanel {
5892 - (void) _customButtonClicked {
5893 int count([buttons_ count]);
5898 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5900 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5901 [buttons addObjectsFromArray:buttons_];
5903 UIActionSheet *sheet = [[[UIActionSheet alloc]
5906 cancelButtonTitle:nil
5907 destructiveButtonTitle:nil
5908 otherButtonTitles:nil
5911 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5913 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5914 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5916 [sheet setContext:@"modify"];
5918 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5922 // We don't want to allow non-commercial packages to do custom things to the install button,
5923 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5924 - (void) customButtonClicked {
5926 [super customButtonClicked];
5928 [self _customButtonClicked];
5931 - (void) reloadButtonClicked {
5932 // Don't reload a commerical package by tapping the loading button,
5933 // but if it's not an Install button, we should forward it on.
5934 if (![package_ uninstalled])
5935 [self _customButtonClicked];
5938 - (void) applyLoadingTitle {
5939 // Don't show "Loading" as the title. Ever.
5942 - (UIBarButtonItem *) rightButton {
5947 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5948 if ((self = [super init]) != nil) {
5949 database_ = database;
5950 buttons_ = [NSMutableArray arrayWithCapacity:4];
5951 name_ = name == nil ? @"" : [NSString stringWithString:name];
5952 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5956 - (void) reloadData {
5959 package_ = [database_ packageWithName:name_];
5961 [buttons_ removeAllObjects];
5963 if (package_ != nil) {
5964 [(Package *) package_ parse];
5966 commercial_ = [package_ isCommercial];
5968 if ([package_ mode] != nil)
5969 [buttons_ addObject:UCLocalize("CLEAR")];
5970 if ([package_ source] == nil);
5971 else if ([package_ upgradableAndEssential:NO])
5972 [buttons_ addObject:UCLocalize("UPGRADE")];
5973 else if ([package_ uninstalled])
5974 [buttons_ addObject:UCLocalize("INSTALL")];
5976 [buttons_ addObject:UCLocalize("REINSTALL")];
5977 if (![package_ uninstalled])
5978 [buttons_ addObject:UCLocalize("REMOVE")];
5982 switch ([buttons_ count]) {
5983 case 0: title = nil; break;
5984 case 1: title = [buttons_ objectAtIndex:0]; break;
5985 default: title = UCLocalize("MODIFY"); break;
5988 button_ = [[[UIBarButtonItem alloc]
5990 style:UIBarButtonItemStylePlain
5992 action:@selector(customButtonClicked)
5996 - (bool) isLoading {
5997 return commercial_ ? [super isLoading] : false;
6003 /* Package List Controller {{{ */
6004 @interface PackageListController : CyteViewController <
6005 UITableViewDataSource,
6008 _transient Database *database_;
6010 _H<NSArray> packages_;
6011 _H<NSMutableArray> sections_;
6012 _H<UITableView, 2> list_;
6013 _H<NSMutableArray> index_;
6014 _H<NSMutableDictionary> indices_;
6015 _H<NSString> title_;
6016 unsigned reloading_;
6019 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6020 - (void) setDelegate:(id)delegate;
6021 - (void) resetCursor;
6026 @implementation PackageListController
6028 - (bool) isSummarized {
6032 - (bool) showsSections {
6036 - (void) deselectWithAnimation:(BOOL)animated {
6037 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6040 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6041 CGRect base = [[self view] bounds];
6042 base.size.height -= bounds.size.height;
6043 base.origin = [list_ frame].origin;
6045 [UIView beginAnimations:nil context:NULL];
6046 [UIView setAnimationBeginsFromCurrentState:YES];
6047 [UIView setAnimationCurve:curve];
6048 [UIView setAnimationDuration:duration];
6049 [list_ setFrame:base];
6050 [UIView commitAnimations];
6053 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6054 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6057 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6058 [self resizeForKeyboardBounds:bounds duration:0];
6061 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6062 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6063 *curve = UIViewAnimationCurveEaseInOut;
6065 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6067 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6070 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6073 - (void) keyboardWillShow:(NSNotification *)notification {
6076 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6077 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6079 NSTimeInterval duration;
6080 UIViewAnimationCurve curve;
6081 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6083 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);
6084 UIViewController *base = self;
6085 while ([base parentViewController] != nil)
6086 base = [base parentViewController];
6087 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6088 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6090 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6091 intersection.size.height += CYStatusBarHeight([self interfaceOrientation]);
6093 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6096 - (void) keyboardWillHide:(NSNotification *)notification {
6097 NSTimeInterval duration;
6098 UIViewAnimationCurve curve;
6099 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6101 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6104 - (void) viewWillAppear:(BOOL)animated {
6105 [super viewWillAppear:animated];
6107 [self resizeForKeyboardBounds:CGRectZero];
6108 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6109 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6112 - (void) viewWillDisappear:(BOOL)animated {
6113 [super viewWillDisappear:animated];
6115 [self resizeForKeyboardBounds:CGRectZero];
6116 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6117 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6120 - (void) viewDidAppear:(BOOL)animated {
6121 [super viewDidAppear:animated];
6122 [self deselectWithAnimation:animated];
6125 - (void) didSelectPackage:(Package *)package {
6126 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6127 [view setDelegate:delegate_];
6128 [[self navigationController] pushViewController:view animated:YES];
6131 #if TryIndexedCollation
6132 + (BOOL) hasIndexedCollation {
6133 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6137 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6138 NSInteger count([sections_ count]);
6139 return count == 0 ? 1 : count;
6142 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6143 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6145 return [[sections_ objectAtIndex:section] name];
6148 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6149 if ([sections_ count] == 0)
6151 return [[sections_ objectAtIndex:section] count];
6154 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6155 @synchronized (database_) {
6156 if ([database_ era] != era_)
6159 Section *section([sections_ objectAtIndex:[path section]]);
6160 NSInteger row([path row]);
6161 Package *package([packages_ objectAtIndex:([section row] + row)]);
6162 return [[package retain] autorelease];
6165 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6166 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6168 cell = [[[PackageCell alloc] init] autorelease];
6170 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6171 [cell setPackage:package asSummary:[self isSummarized]];
6175 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6176 Package *package([self packageAtIndexPath:path]);
6177 package = [database_ packageWithName:[package id]];
6178 [self didSelectPackage:package];
6181 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6182 if (![self showsSections])
6188 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6189 #if TryIndexedCollation
6190 if ([[self class] hasIndexedCollation]) {
6191 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6198 - (void) updateHeight {
6199 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6202 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6203 if ((self = [super init]) != nil) {
6204 database_ = database;
6205 title_ = [title copy];
6206 [[self navigationItem] setTitle:title_];
6211 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6213 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6214 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6215 [[self view] addSubview:list_];
6217 // XXX: is 20 the most optimal number here?
6218 [list_ setSectionIndexMinimumDisplayRowCount:20];
6220 [(UITableView *) list_ setDataSource:self];
6221 [list_ setDelegate:self];
6223 [self updateHeight];
6226 - (void) releaseSubviews {
6234 [super releaseSubviews];
6237 - (void) setDelegate:(id)delegate {
6238 delegate_ = delegate;
6241 - (bool) shouldYield {
6245 - (bool) shouldBlock {
6249 - (NSMutableArray *) _reloadPackages {
6250 @synchronized (database_) {
6251 era_ = [database_ era];
6252 NSArray *packages([database_ packages]);
6254 return [NSMutableArray arrayWithArray:packages];
6257 - (void) _reloadData {
6258 if (reloading_ != 0) {
6265 if ([self shouldYield]) {
6269 if (![self shouldBlock])
6272 hud = [delegate_ addProgressHUD];
6273 [hud setText:UCLocalize("LOADING")];
6277 packages = [self yieldToSelector:@selector(_reloadPackages)];
6280 [delegate_ removeProgressHUD:hud];
6281 } while (reloading_ == 2);
6285 packages = [self _reloadPackages];
6288 packages_ = packages;
6290 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6291 sections_ = [NSMutableArray arrayWithCapacity:16];
6293 Section *section = nil;
6295 #if TryIndexedCollation
6296 if ([[self class] hasIndexedCollation]) {
6297 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6299 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6300 NSArray *titles = [collation sectionIndexTitles];
6303 _profile(PackageTable$reloadData$Section)
6304 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6308 _profile(PackageTable$reloadData$Section$Package)
6309 package = [packages_ objectAtIndex:offset];
6310 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6313 while (secidx < index) {
6316 _profile(PackageTable$reloadData$Section$Allocate)
6317 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6320 _profile(PackageTable$reloadData$Section$Add)
6321 [sections_ addObject:section];
6325 [section addToCount];
6331 index_ = [NSMutableArray arrayWithCapacity:32];
6333 bool sectioned([self showsSections]);
6335 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6336 [sections_ addObject:section];
6339 _profile(PackageTable$reloadData$Section)
6340 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6344 _profile(PackageTable$reloadData$Section$Package)
6345 package = [packages_ objectAtIndex:offset];
6346 index = [package index];
6349 if (sectioned && (section == nil || [section index] != index)) {
6350 _profile(PackageTable$reloadData$Section$Allocate)
6351 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6354 [index_ addObject:[section name]];
6355 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6357 _profile(PackageTable$reloadData$Section$Add)
6358 [sections_ addObject:section];
6362 [section addToCount];
6367 [self updateHeight];
6369 _profile(PackageTable$reloadData$List)
6370 [(UITableView *) list_ setDataSource:self];
6375 - (void) reloadData {
6378 if ([self shouldYield])
6379 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6384 - (void) resetCursor {
6385 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6388 - (void) clearData {
6389 [self updateHeight];
6391 [list_ setDataSource:nil];
6399 /* Filtered Package List Controller {{{ */
6400 @interface FilteredPackageListController : PackageListController {
6403 _H<NSObject> object_;
6406 - (void) setObject:(id)object;
6407 - (void) setObject:(id)object forFilter:(SEL)filter;
6410 - (void) setFilter:(SEL)filter;
6412 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6416 @implementation FilteredPackageListController
6422 - (void) setFilter:(SEL)filter {
6423 @synchronized (self) {
6426 /* XXX: this is an unsafe optimization of doomy hell */
6427 Method method(class_getInstanceMethod([Package class], filter));
6428 _assert(method != NULL);
6429 imp_ = method_getImplementation(method);
6430 _assert(imp_ != NULL);
6433 - (void) setObject:(id)object {
6434 @synchronized (self) {
6438 - (void) setObject:(id)object forFilter:(SEL)filter {
6439 @synchronized (self) {
6440 [self setFilter:filter];
6441 [self setObject:object];
6444 - (NSMutableArray *) _reloadPackages {
6445 @synchronized (database_) {
6446 era_ = [database_ era];
6447 NSArray *packages([database_ packages]);
6449 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6453 _H<NSObject> object;
6455 @synchronized (self) {
6461 _profile(PackageTable$reloadData$Filter)
6462 for (Package *package in packages)
6463 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6464 [filtered addObject:package];
6470 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6471 if ((self = [super initWithDatabase:database title:title]) != nil) {
6472 [self setFilter:filter];
6473 [self setObject:object];
6480 /* Home Controller {{{ */
6481 @interface HomeController : CydiaWebViewController {
6486 @implementation HomeController
6489 if ((self = [super init]) != nil) {
6490 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6495 - (NSURL *) navigationURL {
6496 return [NSURL URLWithString:@"cydia://home"];
6499 - (void) didReceiveMemoryWarning {
6502 - (void) aboutButtonClicked {
6503 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6505 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6506 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6507 [alert setCancelButtonIndex:0];
6510 @"Copyright \u00a9 2008-2011\n"
6513 "Jay Freeman (saurik)\n"
6514 "saurik@saurik.com\n"
6515 "http://www.saurik.com/"
6521 - (UIBarButtonItem *) leftButton {
6522 return [[[UIBarButtonItem alloc]
6523 initWithTitle:UCLocalize("ABOUT")
6524 style:UIBarButtonItemStylePlain
6526 action:@selector(aboutButtonClicked)
6532 /* Manage Controller {{{ */
6533 @interface ManageController : CydiaWebViewController {
6536 - (void) queueStatusDidChange;
6540 @implementation ManageController
6543 if ((self = [super init]) != nil) {
6544 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6548 - (NSURL *) navigationURL {
6549 return [NSURL URLWithString:@"cydia://manage"];
6552 - (UIBarButtonItem *) leftButton {
6553 return [[[UIBarButtonItem alloc]
6554 initWithTitle:UCLocalize("SETTINGS")
6555 style:UIBarButtonItemStylePlain
6557 action:@selector(settingsButtonClicked)
6561 - (void) settingsButtonClicked {
6562 [delegate_ showSettings];
6565 - (void) queueButtonClicked {
6569 - (UIBarButtonItem *) customButton {
6570 return Queuing_ ? [[[UIBarButtonItem alloc]
6571 initWithTitle:UCLocalize("QUEUE")
6572 style:UIBarButtonItemStyleDone
6574 action:@selector(queueButtonClicked)
6575 ] autorelease] : [super customButton];
6578 - (void) queueStatusDidChange {
6579 [self applyRightButton];
6582 - (bool) isLoading {
6583 return !Queuing_ && [super isLoading];
6589 /* Refresh Bar {{{ */
6590 @interface RefreshBar : UINavigationBar {
6591 _H<UIProgressIndicator> indicator_;
6592 _H<UITextLabel> prompt_;
6593 _H<UIProgressBar> progress_;
6594 _H<UINavigationButton> cancel_;
6599 @implementation RefreshBar
6601 - (void) positionViews {
6602 CGRect frame = [cancel_ frame];
6603 frame.size = [cancel_ sizeThatFits:frame.size];
6604 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6605 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6606 [cancel_ setFrame:frame];
6608 CGSize prgsize = {75, 100};
6610 [self frame].size.width - prgsize.width - 10,
6611 ([self frame].size.height - prgsize.height) / 2
6613 [progress_ setFrame:prgrect];
6615 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6616 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6617 CGRect indrect = {{indoffset, indoffset}, indsize};
6618 [indicator_ setFrame:indrect];
6620 CGSize prmsize = {215, indsize.height + 4};
6622 indoffset * 2 + indsize.width,
6623 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6625 [prompt_ setFrame:prmrect];
6628 - (void) setFrame:(CGRect)frame {
6629 [super setFrame:frame];
6630 [self positionViews];
6633 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6634 if ((self = [super initWithFrame:frame]) != nil) {
6635 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6637 [self setBarStyle:UIBarStyleBlack];
6639 UIBarStyle barstyle([self _barStyle:NO]);
6640 bool ugly(barstyle == UIBarStyleDefault);
6642 UIProgressIndicatorStyle style = ugly ?
6643 UIProgressIndicatorStyleMediumBrown :
6644 UIProgressIndicatorStyleMediumWhite;
6646 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6647 [(UIProgressIndicator *) indicator_ setStyle:style];
6648 [indicator_ startAnimation];
6649 [self addSubview:indicator_];
6651 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6652 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6653 [prompt_ setBackgroundColor:[UIColor clearColor]];
6654 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6655 [self addSubview:prompt_];
6657 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6658 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6659 [(UIProgressBar *) progress_ setStyle:0];
6660 [self addSubview:progress_];
6662 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6663 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6664 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6665 [cancel_ setBarStyle:barstyle];
6667 [self positionViews];
6671 - (void) setCancellable:(bool)cancellable {
6673 [self addSubview:cancel_];
6675 [cancel_ removeFromSuperview];
6679 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6680 [progress_ setProgress:0];
6684 [self setCancellable:NO];
6687 - (void) setPrompt:(NSString *)prompt {
6688 [prompt_ setText:prompt];
6691 - (void) setProgress:(float)progress {
6692 [progress_ setProgress:progress];
6698 /* Cydia Navigation Controller Interface {{{ */
6699 @interface UINavigationController (Cydia)
6701 - (NSArray *) navigationURLCollection;
6702 - (void) unloadData;
6707 /* Cydia Tab Bar Controller {{{ */
6708 @interface CYTabBarController : UITabBarController <
6709 UITabBarControllerDelegate,
6712 _transient Database *database_;
6713 _H<RefreshBar, 1> refreshbar_;
6717 // XXX: ok, "updatedelegate_"?...
6718 _transient NSObject<CydiaDelegate> *updatedelegate_;
6720 _H<UIViewController> remembered_;
6721 _transient UIViewController *transient_;
6724 - (NSArray *) navigationURLCollection;
6725 - (void) dropBar:(BOOL)animated;
6726 - (void) beginUpdate;
6727 - (void) raiseBar:(BOOL)animated;
6729 - (void) unloadData;
6733 @implementation CYTabBarController
6735 - (void) setUnselectedViewController:(UIViewController *)transient {
6736 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6737 if (transient != nil) {
6738 if (transient_ == nil)
6739 remembered_ = [controllers objectAtIndex:0];
6740 transient_ = transient;
6741 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6742 [controllers replaceObjectAtIndex:0 withObject:transient_];
6743 [self setSelectedIndex:0];
6744 [self setViewControllers:controllers];
6745 [self concealTabBarSelection];
6746 } else if (remembered_ != nil) {
6747 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6748 transient_ = transient;
6749 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6751 [self setViewControllers:controllers];
6752 [self revealTabBarSelection];
6756 - (UIViewController *) unselectedViewController {
6760 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6761 if ([self unselectedViewController])
6762 [self setUnselectedViewController:nil];
6765 - (NSArray *) navigationURLCollection {
6766 NSMutableArray *items([NSMutableArray array]);
6768 // XXX: Should this deal with transient view controllers?
6769 for (id navigation in [self viewControllers]) {
6770 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6772 [items addObject:stack];
6778 - (void) unloadData {
6781 for (UINavigationController *controller in [self viewControllers])
6782 [controller unloadData];
6784 if (UIViewController *selected = [self selectedViewController])
6785 [selected reloadData];
6787 if (UIViewController *unselected = [self unselectedViewController]) {
6788 [unselected unloadData];
6789 [unselected reloadData];
6794 [[NSNotificationCenter defaultCenter] removeObserver:self];
6799 - (id) initWithDatabase:(Database *)database {
6800 if ((self = [super init]) != nil) {
6801 database_ = database;
6802 [self setDelegate:self];
6804 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6805 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6807 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6811 - (void) setUpdate:(NSDate *)date {
6815 - (void) beginUpdate {
6816 [(RefreshBar *) refreshbar_ start];
6819 [updatedelegate_ retainNetworkActivityIndicator];
6823 detachNewThreadSelector:@selector(performUpdate)
6829 - (void) performUpdate {
6830 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6833 status.setDelegate(self);
6834 [database_ updateWithStatus:status];
6837 performSelectorOnMainThread:@selector(completeUpdate)
6845 - (void) stopUpdateWithSelector:(SEL)selector {
6847 [updatedelegate_ releaseNetworkActivityIndicator];
6849 [self raiseBar:YES];
6852 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6855 - (void) completeUpdate {
6858 [self stopUpdateWithSelector:@selector(reloadData)];
6861 - (void) cancelUpdate {
6862 [self stopUpdateWithSelector:@selector(updateData)];
6865 - (void) cancelPressed {
6866 [self cancelUpdate];
6873 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6874 [refreshbar_ setPrompt:[event compoundMessage]];
6877 - (bool) isProgressCancelled {
6881 - (void) setProgressCancellable:(NSNumber *)cancellable {
6882 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6885 - (void) setProgressPercent:(NSNumber *)percent {
6886 [refreshbar_ setProgress:[percent floatValue]];
6889 - (void) setProgressStatus:(NSDictionary *)status {
6891 [self setProgressPercent:[status objectForKey:@"Percent"]];
6894 - (void) setUpdateDelegate:(id)delegate {
6895 updatedelegate_ = delegate;
6898 - (UIView *) transitionView {
6899 if ([self respondsToSelector:@selector(_transitionView)])
6900 return [self _transitionView];
6902 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6905 - (void) dropBar:(BOOL)animated {
6910 UIView *transition([self transitionView]);
6911 [[self view] addSubview:refreshbar_];
6913 CGRect barframe([refreshbar_ frame]);
6915 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6916 barframe.origin.y = CYStatusBarHeight([self interfaceOrientation]);
6918 barframe.origin.y = 0;
6920 [refreshbar_ setFrame:barframe];
6923 [UIView beginAnimations:nil context:NULL];
6925 CGRect viewframe = [transition frame];
6926 viewframe.origin.y += barframe.size.height;
6927 viewframe.size.height -= barframe.size.height;
6928 [transition setFrame:viewframe];
6931 [UIView commitAnimations];
6933 // Ensure bar has the proper width for our view, it might have changed
6934 barframe.size.width = viewframe.size.width;
6935 [refreshbar_ setFrame:barframe];
6938 - (void) raiseBar:(BOOL)animated {
6943 UIView *transition([self transitionView]);
6944 [refreshbar_ removeFromSuperview];
6946 CGRect barframe([refreshbar_ frame]);
6949 [UIView beginAnimations:nil context:NULL];
6951 CGRect viewframe = [transition frame];
6952 viewframe.origin.y -= barframe.size.height;
6953 viewframe.size.height += barframe.size.height;
6954 [transition setFrame:viewframe];
6957 [UIView commitAnimations];
6960 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6961 bool dropped(dropped_);
6966 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6972 - (void) statusBarFrameChanged:(NSNotification *)notification {
6982 /* Cydia Navigation Controller Implementation {{{ */
6983 @implementation UINavigationController (Cydia)
6985 - (NSArray *) navigationURLCollection {
6986 NSMutableArray *stack([NSMutableArray array]);
6988 for (CyteViewController *controller in [self viewControllers]) {
6989 NSString *url = [[controller navigationURL] absoluteString];
6991 [stack addObject:url];
6997 - (void) reloadData {
7000 UIViewController *visible([self visibleViewController]);
7002 [visible reloadData];
7004 // on the iPad, this view controller is ALSO visible. :(
7006 if (UIViewController *top = [self topViewController])
7011 - (void) unloadData {
7012 for (CyteViewController *page in [self viewControllers])
7021 /* Cydia:// Protocol {{{ */
7022 @interface CydiaURLProtocol : NSURLProtocol {
7027 @implementation CydiaURLProtocol
7029 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7030 NSURL *url([request URL]);
7034 NSString *scheme([[url scheme] lowercaseString]);
7035 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7037 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7043 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7047 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7048 id<NSURLProtocolClient> client([self client]);
7050 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7052 NSData *data(UIImagePNGRepresentation(icon));
7054 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7055 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7056 [client URLProtocol:self didLoadData:data];
7057 [client URLProtocolDidFinishLoading:self];
7061 - (void) startLoading {
7062 id<NSURLProtocolClient> client([self client]);
7063 NSURLRequest *request([self request]);
7065 NSURL *url([request URL]);
7066 NSString *href([url absoluteString]);
7067 NSString *scheme([[url scheme] lowercaseString]);
7071 if ([scheme isEqualToString:@"cydia"])
7072 path = [href substringFromIndex:8];
7073 else if ([scheme isEqualToString:@"about"])
7074 path = [href substringFromIndex:12];
7075 else _assert(false);
7077 NSRange slash([path rangeOfString:@"/"]);
7080 if (slash.location == NSNotFound) {
7084 command = [path substringToIndex:slash.location];
7085 path = [path substringFromIndex:(slash.location + 1)];
7088 Database *database([Database sharedInstance]);
7090 if ([command isEqualToString:@"package-icon"]) {
7093 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7094 Package *package([database packageWithName:path]);
7098 UIImage *icon([package icon]);
7099 [self _returnPNGWithImage:icon forRequest:request];
7100 } else if ([command isEqualToString:@"source-icon"]) {
7103 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7104 NSString *source(Simplify(path));
7105 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7107 icon = [UIImage applicationImageNamed:@"unknown.png"];
7108 [self _returnPNGWithImage:icon forRequest:request];
7109 } else if ([command isEqualToString:@"uikit-image"]) {
7112 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7113 UIImage *icon(_UIImageWithName(path));
7114 [self _returnPNGWithImage:icon forRequest:request];
7115 } else if ([command isEqualToString:@"section-icon"]) {
7118 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7119 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7121 icon = [UIImage applicationImageNamed:@"unknown.png"];
7122 [self _returnPNGWithImage:icon forRequest:request];
7124 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7128 - (void) stopLoading {
7134 /* Section Controller {{{ */
7135 @interface SectionController : FilteredPackageListController {
7136 _H<NSString> section_;
7139 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7143 @implementation SectionController
7145 - (NSURL *) navigationURL {
7146 NSString *name = section_;
7150 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7153 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7156 title = UCLocalize("ALL_PACKAGES");
7157 else if (![name isEqual:@""])
7158 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7160 title = UCLocalize("NO_SECTION");
7162 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7169 /* Sections Controller {{{ */
7170 @interface SectionsController : CyteViewController <
7171 UITableViewDataSource,
7174 _transient Database *database_;
7175 _H<NSMutableArray> sections_;
7176 _H<NSMutableArray> filtered_;
7177 _H<UITableView, 2> list_;
7180 - (id) initWithDatabase:(Database *)database;
7181 - (void) editButtonClicked;
7185 @implementation SectionsController
7187 - (NSURL *) navigationURL {
7188 return [NSURL URLWithString:@"cydia://sections"];
7191 - (void) updateNavigationItem {
7192 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7193 if ([sections_ count] == 0) {
7194 [[self navigationItem] setRightBarButtonItem:nil];
7196 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7197 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7199 action:@selector(editButtonClicked)
7200 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7204 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7205 [super setEditing:editing animated:animated];
7210 [delegate_ updateData];
7212 [self updateNavigationItem];
7215 - (void) viewDidAppear:(BOOL)animated {
7216 [super viewDidAppear:animated];
7217 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7220 - (void) viewWillDisappear:(BOOL)animated {
7221 [super viewWillDisappear:animated];
7222 if ([self isEditing]) [self setEditing:NO];
7225 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7226 Section *section = nil;
7227 int index = [indexPath row];
7228 if (![self isEditing]) {
7231 section = [filtered_ objectAtIndex:index];
7233 section = [sections_ objectAtIndex:index];
7238 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7239 if ([self isEditing])
7240 return [sections_ count];
7242 return [filtered_ count] + 1;
7245 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7249 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7250 static NSString *reuseIdentifier = @"SectionCell";
7252 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7254 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7256 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7261 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7262 if ([self isEditing])
7265 Section *section = [self sectionAtIndexPath:indexPath];
7267 SectionController *controller = [[[SectionController alloc]
7268 initWithDatabase:database_
7269 section:[section name]
7271 [controller setDelegate:delegate_];
7273 [[self navigationController] pushViewController:controller animated:YES];
7277 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7279 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7280 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7281 [list_ setRowHeight:45.0f];
7282 [(UITableView *) list_ setDataSource:self];
7283 [list_ setDelegate:self];
7284 [[self view] addSubview:list_];
7287 - (void) viewDidLoad {
7288 [super viewDidLoad];
7290 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7293 - (void) releaseSubviews {
7299 [super releaseSubviews];
7302 - (id) initWithDatabase:(Database *)database {
7303 if ((self = [super init]) != nil) {
7304 database_ = database;
7308 - (void) reloadData {
7311 NSArray *packages = [database_ packages];
7313 sections_ = [NSMutableArray arrayWithCapacity:16];
7314 filtered_ = [NSMutableArray arrayWithCapacity:16];
7316 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7319 for (Package *package in packages) {
7320 NSString *name([package section]);
7321 NSString *key(name == nil ? @"" : name);
7325 _profile(SectionsView$reloadData$Section)
7326 section = [sections objectForKey:key];
7327 if (section == nil) {
7328 _profile(SectionsView$reloadData$Section$Allocate)
7329 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7330 [sections setObject:section forKey:key];
7335 [section addToCount];
7337 _profile(SectionsView$reloadData$Filter)
7338 if (![package valid] || ![package visible])
7346 [sections_ addObjectsFromArray:[sections allValues]];
7348 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7350 for (Section *section in (id) sections_) {
7351 size_t count([section row]);
7355 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7356 [section setCount:count];
7357 [filtered_ addObject:section];
7360 [self updateNavigationItem];
7365 - (void) editButtonClicked {
7366 [self setEditing:![self isEditing] animated:YES];
7372 /* Changes Controller {{{ */
7373 @interface ChangesController : CyteViewController <
7374 UITableViewDataSource,
7377 _transient Database *database_;
7379 _H<NSArray> packages_;
7380 _H<NSMutableArray> sections_;
7381 _H<UITableView, 2> list_;
7385 - (id) initWithDatabase:(Database *)database;
7389 @implementation ChangesController
7391 - (NSURL *) navigationURL {
7392 return [NSURL URLWithString:@"cydia://changes"];
7395 - (void) viewDidAppear:(BOOL)animated {
7396 [super viewDidAppear:animated];
7397 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7400 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7401 NSInteger count([sections_ count]);
7402 return count == 0 ? 1 : count;
7405 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7406 if ([sections_ count] == 0)
7408 return [[sections_ objectAtIndex:section] name];
7411 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7412 if ([sections_ count] == 0)
7414 return [[sections_ objectAtIndex:section] count];
7417 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7418 @synchronized (database_) {
7419 if ([database_ era] != era_)
7422 NSUInteger sectionIndex([path section]);
7423 if (sectionIndex >= [sections_ count])
7425 Section *section([sections_ objectAtIndex:sectionIndex]);
7426 NSInteger row([path row]);
7427 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7430 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7431 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7433 cell = [[[PackageCell alloc] init] autorelease];
7435 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7436 [cell setPackage:package asSummary:false];
7440 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7441 Package *package([self packageAtIndexPath:path]);
7442 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7443 [view setDelegate:delegate_];
7444 [[self navigationController] pushViewController:view animated:YES];
7448 - (void) refreshButtonClicked {
7449 [delegate_ beginUpdate];
7450 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7453 - (void) upgradeButtonClicked {
7454 [delegate_ distUpgrade];
7455 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7459 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7461 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7462 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7463 [list_ setRowHeight:73];
7464 [(UITableView *) list_ setDataSource:self];
7465 [list_ setDelegate:self];
7466 [[self view] addSubview:list_];
7469 - (void) viewDidLoad {
7470 [super viewDidLoad];
7472 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7475 - (void) releaseSubviews {
7481 [super releaseSubviews];
7484 - (id) initWithDatabase:(Database *)database {
7485 if ((self = [super init]) != nil) {
7486 database_ = database;
7490 - (NSMutableArray *) _reloadPackages {
7491 @synchronized (database_) {
7492 era_ = [database_ era];
7493 NSArray *packages([database_ packages]);
7495 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7498 _profile(ChangesController$_reloadPackages$Filter)
7499 for (Package *package in packages)
7500 if ([package upgradableAndEssential:YES] || [package visible])
7501 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7504 _profile(ChangesController$_reloadPackages$radixSort)
7505 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7512 - (void) _reloadData {
7517 UIProgressHUD *hud([delegate_ addProgressHUD]);
7518 [hud setText:UCLocalize("LOADING")];
7519 //NSLog(@"HUD:%@::%@", delegate_, hud);
7520 packages = [self yieldToSelector:@selector(_reloadPackages)];
7521 [delegate_ removeProgressHUD:hud];
7523 packages = [self _reloadPackages];
7526 @synchronized (database_) {
7527 if (era_ != [database_ era])
7530 packages_ = packages;
7531 sections_ = [NSMutableArray arrayWithCapacity:16];
7533 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7534 Section *ignored = nil;
7535 Section *section = nil;
7539 bool unseens = false;
7541 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7543 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7544 Package *package = [packages_ objectAtIndex:offset];
7546 BOOL uae = [package upgradableAndEssential:YES];
7550 time_t seen([package seen]);
7552 if (section == nil || last != seen) {
7556 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7559 _profile(ChangesController$reloadData$Allocate)
7560 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7561 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7562 [sections_ addObject:section];
7566 [section addToCount];
7567 } else if ([package ignored]) {
7568 if (ignored == nil) {
7569 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7571 [ignored addToCount];
7574 [upgradable addToCount];
7579 CFRelease(formatter);
7582 Section *last = [sections_ lastObject];
7583 size_t count = [last count];
7584 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7585 [sections_ removeLastObject];
7588 if ([ignored count] != 0)
7589 [sections_ insertObject:ignored atIndex:0];
7591 [sections_ insertObject:upgradable atIndex:0];
7595 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7596 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7597 style:UIBarButtonItemStylePlain
7599 action:@selector(upgradeButtonClicked)
7600 ] autorelease]) animated:YES];
7602 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7603 initWithTitle:UCLocalize("REFRESH")
7604 style:UIBarButtonItemStylePlain
7606 action:@selector(refreshButtonClicked)
7607 ] autorelease]) animated:YES];
7612 - (void) reloadData {
7614 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7619 /* Search Controller {{{ */
7620 @interface SearchController : FilteredPackageListController <
7623 _H<UISearchBar, 1> search_;
7627 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7628 - (void) reloadData;
7632 @implementation SearchController
7634 - (NSURL *) navigationURL {
7635 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7636 return [NSURL URLWithString:@"cydia://search"];
7638 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7641 - (void) useSearch {
7642 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7647 - (void) viewWillAppear:(BOOL)animated {
7648 [super viewWillAppear:animated];
7650 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7654 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7655 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7660 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7661 [search_ resignFirstResponder];
7665 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7666 [search_ setText:@""];
7667 [self searchBarButtonClicked:searchBar];
7670 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7671 [self searchBarButtonClicked:searchBar];
7674 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7675 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7679 - (bool) shouldYield {
7683 - (bool) shouldBlock {
7684 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7687 - (bool) isSummarized {
7688 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7691 - (bool) showsSections {
7695 - (NSMutableArray *) _reloadPackages {
7696 NSMutableArray *packages([super _reloadPackages]);
7697 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7698 [packages radixSortUsingSelector:@selector(rank)];
7702 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7703 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7704 search_ = [[[UISearchBar alloc] init] autorelease];
7705 [search_ setDelegate:self];
7708 [search_ setText:query];
7712 - (void) viewDidAppear:(BOOL)animated {
7713 [super viewDidAppear:animated];
7715 if (!searchloaded_) {
7716 searchloaded_ = YES;
7717 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7718 [search_ layoutSubviews];
7719 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7721 UITextField *textField;
7722 if ([search_ respondsToSelector:@selector(searchField)])
7723 textField = [search_ searchField];
7725 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7727 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7728 [textField setEnablesReturnKeyAutomatically:NO];
7729 [[self navigationItem] setTitleView:textField];
7733 - (void) reloadData {
7734 id object([search_ text]);
7735 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7736 object = [object componentsSeparatedByString:@" "];
7738 [self setObject:object];
7744 - (void) didSelectPackage:(Package *)package {
7745 [search_ resignFirstResponder];
7746 [super didSelectPackage:package];
7751 /* Package Settings Controller {{{ */
7752 @interface PackageSettingsController : CyteViewController <
7753 UITableViewDataSource,
7756 _transient Database *database_;
7758 _H<Package> package_;
7759 _H<UITableView, 2> table_;
7760 _H<UISwitch> subscribedSwitch_;
7761 _H<UISwitch> ignoredSwitch_;
7762 _H<UITableViewCell> subscribedCell_;
7763 _H<UITableViewCell> ignoredCell_;
7766 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7770 @implementation PackageSettingsController
7772 - (NSURL *) navigationURL {
7773 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7776 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7777 if (package_ == nil)
7780 if ([package_ installed] == nil)
7786 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7787 if (package_ == nil)
7790 // both sections contain just one item right now.
7794 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7798 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7800 return UCLocalize("SHOW_ALL_CHANGES_EX");
7802 return UCLocalize("IGNORE_UPGRADES_EX");
7805 - (void) onSubscribed:(id)control {
7806 bool value([control isOn]);
7807 if (package_ == nil)
7809 if ([package_ setSubscribed:value])
7810 [delegate_ updateData];
7813 - (void) _updateIgnored {
7814 const char *package([name_ UTF8String]);
7815 bool on([ignoredSwitch_ isOn]);
7817 pid_t pid(ExecFork());
7819 FILE *dpkg(popen("dpkg --set-selections", "w"));
7820 fwrite(package, strlen(package), 1, dpkg);
7823 fwrite(" hold\n", 6, 1, dpkg);
7825 fwrite(" install\n", 9, 1, dpkg);
7835 int result(waitpid(pid, &status, 0));
7838 _assert(result == pid);
7844 - (void) onIgnored:(id)control {
7845 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7846 [invocation setTarget:self];
7847 [invocation setSelector:@selector(_updateIgnored)];
7849 [delegate_ reloadDataWithInvocation:invocation];
7852 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7853 if (package_ == nil)
7856 switch ([indexPath section]) {
7857 case 0: return subscribedCell_;
7858 case 1: return ignoredCell_;
7867 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7869 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7870 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7871 [(UITableView *) table_ setDataSource:self];
7872 [table_ setDelegate:self];
7873 [[self view] addSubview:table_];
7875 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7876 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7877 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7879 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7880 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7881 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7883 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7884 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7885 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7886 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7888 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7889 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7890 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7891 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7894 - (void) viewDidLoad {
7895 [super viewDidLoad];
7897 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7900 - (void) releaseSubviews {
7902 subscribedCell_ = nil;
7904 ignoredSwitch_ = nil;
7905 subscribedSwitch_ = nil;
7907 [super releaseSubviews];
7910 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7911 if ((self = [super init]) != nil) {
7912 database_ = database;
7917 - (void) reloadData {
7920 package_ = [database_ packageWithName:name_];
7922 if (package_ != nil) {
7923 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7924 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7925 } // XXX: what now, G?
7927 [table_ reloadData];
7933 /* Installed Controller {{{ */
7934 @interface InstalledController : FilteredPackageListController {
7938 - (id) initWithDatabase:(Database *)database;
7940 - (void) updateRoleButton;
7941 - (void) queueStatusDidChange;
7945 @implementation InstalledController
7947 - (NSURL *) navigationURL {
7948 return [NSURL URLWithString:@"cydia://installed"];
7951 - (id) initWithDatabase:(Database *)database {
7952 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7953 [self updateRoleButton];
7954 [self queueStatusDidChange];
7959 - (void) queueButtonClicked {
7964 - (void) queueStatusDidChange {
7968 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7969 initWithTitle:UCLocalize("QUEUE")
7970 style:UIBarButtonItemStyleDone
7972 action:@selector(queueButtonClicked)
7975 [[self navigationItem] setLeftBarButtonItem:nil];
7981 - (void) updateRoleButton {
7982 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7983 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7984 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7985 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7987 action:@selector(roleButtonClicked)
7991 - (void) roleButtonClicked {
7992 [self setObject:[NSNumber numberWithBool:expert_]];
7996 [self updateRoleButton];
8002 /* Source Cell {{{ */
8003 @interface SourceCell : CyteTableViewCell <
8004 CyteTableViewCellDelegate
8007 _H<NSString> origin_;
8008 _H<NSString> label_;
8011 - (void) setSource:(Source *)source;
8015 @implementation SourceCell
8017 - (void) _setImage:(UIImage *)image {
8019 [content_ setNeedsDisplay];
8022 - (void) _setSource:(Source *)source {
8023 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8025 if (NSString *base = [source base])
8026 if ([base length] != 0) {
8027 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
8029 if (NSData *data = [NSURLConnection
8030 sendSynchronousRequest:[NSURLRequest
8032 //cachePolicy:NSURLRequestUseProtocolCachePolicy
8036 returningResponse:NULL
8039 if (UIImage *image = [UIImage imageWithData:data])
8040 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
8046 - (void) setSource:(Source *)source {
8047 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8049 origin_ = [source name];
8050 label_ = [source uri];
8052 [content_ setNeedsDisplay];
8054 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
8057 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8058 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8059 UIView *content([self contentView]);
8060 CGRect bounds([content bounds]);
8062 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8063 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8064 [content_ setBackgroundColor:[UIColor whiteColor]];
8065 [content addSubview:content_];
8067 [content_ setDelegate:self];
8068 [content_ setOpaque:YES];
8070 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8074 - (NSString *) accessibilityLabel {
8078 - (void) drawContentRect:(CGRect)rect {
8079 bool highlighted(highlighted_);
8080 float width(rect.size.width);
8083 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8090 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 60) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8094 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 75) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8099 /* Source Controller {{{ */
8100 @interface SourceController : FilteredPackageListController {
8101 _transient Source *source_;
8105 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8109 @implementation SourceController
8111 - (NSURL *) navigationURL {
8112 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8115 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8116 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8118 key_ = [source key];
8122 - (void) reloadData {
8123 source_ = [database_ sourceWithKey:key_];
8124 key_ = [source_ key];
8125 [self setObject:source_];
8127 [[self navigationItem] setTitle:[source_ label]];
8134 /* Sources Controller {{{ */
8135 @interface SourcesController : CyteViewController <
8136 UITableViewDataSource,
8139 _transient Database *database_;
8140 _H<UITableView, 2> list_;
8141 _H<NSMutableArray> sources_;
8145 _H<UIProgressHUD> hud_;
8148 //NSURLConnection *installer_;
8149 NSURLConnection *trivial_;
8150 NSURLConnection *trivial_bz2_;
8151 NSURLConnection *trivial_gz_;
8152 //NSURLConnection *automatic_;
8157 - (id) initWithDatabase:(Database *)database;
8158 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8162 @implementation SourcesController
8164 - (void) _releaseConnection:(NSURLConnection *)connection {
8165 if (connection != nil) {
8166 [connection cancel];
8167 //[connection setDelegate:nil];
8168 [connection release];
8173 //[self _releaseConnection:installer_];
8174 [self _releaseConnection:trivial_];
8175 [self _releaseConnection:trivial_gz_];
8176 [self _releaseConnection:trivial_bz2_];
8177 //[self _releaseConnection:automatic_];
8182 - (NSURL *) navigationURL {
8183 return [NSURL URLWithString:@"cydia://sources"];
8186 - (void) viewDidAppear:(BOOL)animated {
8187 [super viewDidAppear:animated];
8188 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8191 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8192 return offset_ == 0 ? 1 : 2;
8195 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8196 switch (section + (offset_ == 0 ? 1 : 0)) {
8197 case 0: return UCLocalize("ENTERED_BY_USER");
8198 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8204 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8205 int count = [sources_ count];
8207 case 0: return (offset_ == 0 ? count : offset_);
8208 case 1: return count - offset_;
8214 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8216 switch (indexPath.section) {
8217 case 0: idx = indexPath.row; break;
8218 case 1: idx = indexPath.row + offset_; break;
8222 return [sources_ objectAtIndex:idx];
8225 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8226 static NSString *cellIdentifier = @"SourceCell";
8228 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8229 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8230 [cell setSource:[self sourceAtIndexPath:indexPath]];
8231 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8236 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8237 Source *source = [self sourceAtIndexPath:indexPath];
8239 SourceController *controller = [[[SourceController alloc]
8240 initWithDatabase:database_
8244 [controller setDelegate:delegate_];
8246 [[self navigationController] pushViewController:controller animated:YES];
8249 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8250 Source *source = [self sourceAtIndexPath:indexPath];
8251 return [source record] != nil;
8254 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8255 if (editingStyle == UITableViewCellEditingStyleDelete) {
8256 Source *source = [self sourceAtIndexPath:indexPath];
8257 [Sources_ removeObjectForKey:[source key]];
8258 [delegate_ syncData];
8263 [delegate_ addTrivialSource:href_];
8264 [delegate_ syncData];
8267 - (NSString *) getWarning {
8268 NSString *href(href_);
8269 NSRange colon([href rangeOfString:@"://"]);
8270 if (colon.location != NSNotFound)
8271 href = [href substringFromIndex:(colon.location + 3)];
8272 href = [href stringByAddingPercentEscapes];
8273 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8274 href = [href stringByCachingURLWithCurrentCDN];
8276 NSURL *url([NSURL URLWithString:href]);
8278 NSStringEncoding encoding;
8279 NSError *error(nil);
8281 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8282 return [warning length] == 0 ? nil : warning;
8286 - (void) _endConnection:(NSURLConnection *)connection {
8287 // XXX: the memory management in this method is horribly awkward
8289 NSURLConnection **field = NULL;
8290 if (connection == trivial_)
8292 else if (connection == trivial_bz2_)
8293 field = &trivial_bz2_;
8294 else if (connection == trivial_gz_)
8295 field = &trivial_gz_;
8296 _assert(field != NULL);
8297 [connection release];
8302 trivial_bz2_ == nil &&
8305 [delegate_ releaseNetworkActivityIndicator];
8307 [delegate_ removeProgressHUD:hud_];
8313 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8316 UIAlertView *alert = [[[UIAlertView alloc]
8317 initWithTitle:UCLocalize("SOURCE_WARNING")
8320 cancelButtonTitle:UCLocalize("CANCEL")
8322 UCLocalize("ADD_ANYWAY"),
8326 [alert setContext:@"warning"];
8327 [alert setNumberOfRows:1];
8331 } else if (error_ != nil) {
8332 UIAlertView *alert = [[[UIAlertView alloc]
8333 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8334 message:[error_ localizedDescription]
8336 cancelButtonTitle:UCLocalize("OK")
8337 otherButtonTitles:nil
8340 [alert setContext:@"urlerror"];
8343 UIAlertView *alert = [[[UIAlertView alloc]
8344 initWithTitle:UCLocalize("NOT_REPOSITORY")
8345 message:UCLocalize("NOT_REPOSITORY_EX")
8347 cancelButtonTitle:UCLocalize("OK")
8348 otherButtonTitles:nil
8351 [alert setContext:@"trivial"];
8360 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8361 switch ([response statusCode]) {
8367 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8368 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8370 [self _endConnection:connection];
8373 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8374 [self _endConnection:connection];
8377 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8378 NSURL *url([NSURL URLWithString:href]);
8380 NSMutableURLRequest *request = [NSMutableURLRequest
8382 cachePolicy:NSURLRequestUseProtocolCachePolicy
8383 timeoutInterval:120.0
8386 [request setHTTPMethod:method];
8388 if (Machine_ != NULL)
8389 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8391 if ([url isCydiaSecure]) {
8392 if (UniqueID_ != nil)
8393 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8396 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8399 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8400 NSString *context([alert context]);
8402 if ([context isEqualToString:@"source"]) {
8405 NSString *href = [[alert textField] text];
8407 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8409 if (![href hasSuffix:@"/"])
8410 href_ = [href stringByAppendingString:@"/"];
8414 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8415 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8416 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8417 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8421 // XXX: this is stupid
8422 hud_ = [delegate_ addProgressHUD];
8423 [hud_ setText:UCLocalize("VERIFYING_URL")];
8424 [delegate_ retainNetworkActivityIndicator];
8433 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8434 } else if ([context isEqualToString:@"trivial"])
8435 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8436 else if ([context isEqualToString:@"urlerror"])
8437 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8438 else if ([context isEqualToString:@"warning"]) {
8452 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8457 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8459 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8460 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8461 [list_ setRowHeight:53];
8462 [(UITableView *) list_ setDataSource:self];
8463 [list_ setDelegate:self];
8464 [[self view] addSubview:list_];
8467 - (void) viewDidLoad {
8468 [super viewDidLoad];
8470 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8471 [self updateButtonsForEditingStatus:NO animated:NO];
8474 - (void) releaseSubviews {
8479 [super releaseSubviews];
8482 - (id) initWithDatabase:(Database *)database {
8483 if ((self = [super init]) != nil) {
8484 database_ = database;
8488 - (void) reloadData {
8492 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8495 sources_ = [NSMutableArray arrayWithCapacity:16];
8496 [sources_ addObjectsFromArray:[database_ sources]];
8498 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8501 int count([sources_ count]);
8503 for (int i = 0; i != count; i++) {
8504 if ([[sources_ objectAtIndex:i] record] == nil)
8509 [list_ setEditing:NO];
8510 [self updateButtonsForEditingStatus:NO animated:NO];
8514 - (void) showAddSourcePrompt {
8515 UIAlertView *alert = [[[UIAlertView alloc]
8516 initWithTitle:UCLocalize("ENTER_APT_URL")
8519 cancelButtonTitle:UCLocalize("CANCEL")
8521 UCLocalize("ADD_SOURCE"),
8525 [alert setContext:@"source"];
8527 [alert setNumberOfRows:1];
8528 [alert addTextFieldWithValue:@"http://" label:@""];
8530 UITextInputTraits *traits = [[alert textField] textInputTraits];
8531 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8532 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8533 [traits setKeyboardType:UIKeyboardTypeURL];
8534 // XXX: UIReturnKeyDone
8535 [traits setReturnKeyType:UIReturnKeyNext];
8540 - (void) addButtonClicked {
8541 [self showAddSourcePrompt];
8544 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8545 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8546 initWithTitle:UCLocalize("ADD")
8547 style:UIBarButtonItemStylePlain
8549 action:@selector(addButtonClicked)
8550 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8552 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8553 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8554 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8556 action:@selector(editButtonClicked)
8557 ] autorelease] animated:animated];
8559 if (IsWildcat_ && !editing)
8560 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8561 initWithTitle:UCLocalize("SETTINGS")
8562 style:UIBarButtonItemStylePlain
8564 action:@selector(settingsButtonClicked)
8568 - (void) settingsButtonClicked {
8569 [delegate_ showSettings];
8572 - (void) editButtonClicked {
8573 [list_ setEditing:![list_ isEditing] animated:YES];
8575 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8581 /* Settings Controller {{{ */
8582 @interface SettingsController : CyteViewController <
8583 UITableViewDataSource,
8586 _transient Database *database_;
8587 // XXX: ok, "roledelegate_"?...
8588 _transient id roledelegate_;
8589 _H<UITableView, 2> table_;
8590 _H<UISegmentedControl> segment_;
8591 _H<UIView> container_;
8594 - (void) showDoneButton;
8595 - (void) resizeSegmentedControl;
8599 @implementation SettingsController
8602 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8604 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8605 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8606 [table_ setDelegate:self];
8607 [(UITableView *) table_ setDataSource:self];
8608 [[self view] addSubview:table_];
8610 NSArray *items = [NSArray arrayWithObjects:
8612 UCLocalize("HACKER"),
8613 UCLocalize("DEVELOPER"),
8615 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8616 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8617 [container_ addSubview:segment_];
8620 - (void) viewDidLoad {
8621 [super viewDidLoad];
8623 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8626 if ([Role_ isEqualToString:@"User"]) index = 0;
8627 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8628 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8630 [segment_ setSelectedSegmentIndex:index];
8631 [self showDoneButton];
8634 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8635 [self resizeSegmentedControl];
8638 - (void) releaseSubviews {
8643 [super releaseSubviews];
8646 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8647 if ((self = [super init]) != nil) {
8648 database_ = database;
8649 roledelegate_ = delegate;
8653 - (void) resizeSegmentedControl {
8654 CGFloat width = [[self view] frame].size.width;
8655 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8658 - (void) viewWillAppear:(BOOL)animated {
8659 [super viewWillAppear:animated];
8661 [self resizeSegmentedControl];
8664 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8665 [self resizeSegmentedControl];
8668 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8669 [self resizeSegmentedControl];
8673 NSString *role(nil);
8675 switch ([segment_ selectedSegmentIndex]) {
8676 case 0: role = @"User"; break;
8677 case 1: role = @"Hacker"; break;
8678 case 2: role = @"Developer"; break;
8683 if (![role isEqualToString:Role_]) {
8684 bool rolling(Role_ == nil);
8687 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8691 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8695 [roledelegate_ loadData];
8697 [roledelegate_ updateData];
8701 - (void) segmentChanged:(UISegmentedControl *)control {
8702 [self showDoneButton];
8705 - (void) saveAndClose {
8708 [[self navigationItem] setRightBarButtonItem:nil];
8709 [[self navigationController] dismissModalViewControllerAnimated:YES];
8712 - (void) doneButtonClicked {
8713 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8714 [spinner startAnimating];
8715 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8716 [[self navigationItem] setRightBarButtonItem:spinItem];
8718 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8721 - (void) showDoneButton {
8722 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8723 initWithTitle:UCLocalize("DONE")
8724 style:UIBarButtonItemStyleDone
8726 action:@selector(doneButtonClicked)
8727 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8730 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8731 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8735 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8739 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8740 return nil; // This method is required by the protocol.
8743 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8745 return UCLocalize("ROLE_EX");
8747 return [NSString stringWithFormat:
8748 @"%@: %@\n%@: %@\n%@: %@",
8749 UCLocalize("USER"), UCLocalize("USER_EX"),
8750 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8751 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8756 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8757 return section == 3 ? 44.0f : 0;
8760 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8761 return section == 3 ? container_ : nil;
8764 - (void) reloadData {
8767 [table_ reloadData];
8772 /* Stash Controller {{{ */
8773 @interface StashController : CyteViewController {
8774 _H<UIActivityIndicatorView> spinner_;
8775 _H<UILabel> status_;
8776 _H<UILabel> caption_;
8781 @implementation StashController
8784 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8785 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8787 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8788 CGRect spinrect = [spinner_ frame];
8789 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8790 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8791 [spinner_ setFrame:spinrect];
8792 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8793 [[self view] addSubview:spinner_];
8794 [spinner_ startAnimating];
8797 captrect.size.width = [[self view] frame].size.width;
8798 captrect.size.height = 40.0f;
8799 captrect.origin.x = 0;
8800 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8801 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8802 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8803 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8804 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8805 [caption_ setTextColor:[UIColor whiteColor]];
8806 [caption_ setBackgroundColor:[UIColor clearColor]];
8807 [caption_ setShadowColor:[UIColor blackColor]];
8808 [caption_ setTextAlignment:UITextAlignmentCenter];
8809 [[self view] addSubview:caption_];
8812 statusrect.size.width = [[self view] frame].size.width;
8813 statusrect.size.height = 30.0f;
8814 statusrect.origin.x = 0;
8815 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8816 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8817 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8818 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8819 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8820 [status_ setTextColor:[UIColor whiteColor]];
8821 [status_ setBackgroundColor:[UIColor clearColor]];
8822 [status_ setShadowColor:[UIColor blackColor]];
8823 [status_ setTextAlignment:UITextAlignmentCenter];
8824 [[self view] addSubview:status_];
8827 - (void) releaseSubviews {
8832 [super releaseSubviews];
8838 @interface CYURLCache : SDURLCache {
8843 @implementation CYURLCache
8845 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8848 else if ([event isEqualToString:@"no-cache"])
8850 else if ([event isEqualToString:@"store"])
8852 else if ([event isEqualToString:@"invalid"])
8854 else if ([event isEqualToString:@"memory"])
8856 else if ([event isEqualToString:@"disk"])
8858 else if ([event isEqualToString:@"miss"])
8861 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8865 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8866 if (NSURLResponse *response = [cached response])
8867 if (NSString *mime = [response MIMEType])
8868 if ([mime isEqualToString:@"text/cache-manifest"]) {
8869 NSURL *url([response URL]);
8872 NSLog(@"###: %@", [url absoluteString]);
8875 @synchronized (HostConfig_) {
8876 [CachedURLs_ addObject:url];
8880 [super storeCachedResponse:cached forRequest:request];
8885 @interface Cydia : UIApplication <
8886 ConfirmationControllerDelegate,
8889 UINavigationControllerDelegate,
8890 UITabBarControllerDelegate
8892 _H<UIWindow> window_;
8893 _H<CYTabBarController> tabbar_;
8894 _H<CydiaLoadingViewController> emulated_;
8896 _H<NSMutableArray> essential_;
8897 _H<NSMutableArray> broken_;
8899 Database *database_;
8901 _H<NSURL> starturl_;
8906 _H<StashController> stash_;
8915 @implementation Cydia
8917 - (void) beginUpdate {
8918 [tabbar_ beginUpdate];
8922 return [tabbar_ updating];
8926 if ([broken_ count] != 0) {
8927 int count = [broken_ count];
8929 UIAlertView *alert = [[[UIAlertView alloc]
8930 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8931 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8933 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8935 UCLocalize("TEMPORARY_IGNORE"),
8939 [alert setContext:@"fixhalf"];
8940 [alert setNumberOfRows:2];
8942 } else if (!Ignored_ && [essential_ count] != 0) {
8943 int count = [essential_ count];
8945 UIAlertView *alert = [[[UIAlertView alloc]
8946 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8947 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8949 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8951 UCLocalize("UPGRADE_ESSENTIAL"),
8952 UCLocalize("COMPLETE_UPGRADE"),
8956 [alert setContext:@"upgrade"];
8961 - (void) returnToCydia {
8965 - (void) _saveConfig {
8971 NSString *error(nil);
8973 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8975 NSError *error(nil);
8976 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8977 NSLog(@"failure to save metadata data: %@", error);
8982 NSLog(@"failure to serialize metadata: %@", error);
8989 // Navigation controller for the queuing badge.
8990 - (UINavigationController *) queueNavigationController {
8991 NSArray *controllers = [tabbar_ viewControllers];
8992 return [controllers objectAtIndex:3];
8995 - (void) unloadData {
8996 [tabbar_ unloadData];
8999 - (void) _updateData {
9003 UINavigationController *navigation = [self queueNavigationController];
9005 id queuedelegate = nil;
9006 if ([[navigation viewControllers] count] > 0)
9007 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9009 [queuedelegate queueStatusDidChange];
9010 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9013 - (void) _refreshIfPossible:(NSDate *)update {
9014 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9016 bool recently = false;
9017 if (update != nil) {
9018 NSTimeInterval interval([update timeIntervalSinceNow]);
9019 if (interval <= 0 && interval > -(15*60))
9023 // Don't automatic refresh if:
9024 // - We already refreshed recently.
9025 // - We already auto-refreshed this launch.
9026 // - Auto-refresh is disabled.
9027 if (recently || loaded_ || ManualRefresh) {
9028 // If we are cancelling, we need to make sure it knows it's already loaded.
9031 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9033 // We are going to load, so remember that.
9036 SCNetworkReachabilityFlags flags; {
9037 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9038 SCNetworkReachabilityGetFlags(reachability, &flags);
9039 CFRelease(reachability);
9042 // XXX: this elaborate mess is what Apple is using to determine this? :(
9043 // XXX: do we care if the user has to intervene? maybe that's ok?
9045 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9046 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9047 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9048 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9049 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9050 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9054 // If we can reach the server, auto-refresh!
9056 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9062 - (void) refreshIfPossible {
9063 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9066 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9067 @synchronized (self) {
9068 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9069 [hud setText:UCLocalize("RELOADING_DATA")];
9071 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9074 [self removeProgressHUD:hud];
9078 [essential_ removeAllObjects];
9079 [broken_ removeAllObjects];
9081 NSArray *packages([database_ packages]);
9082 for (Package *package in packages) {
9084 [broken_ addObject:package];
9085 if ([package upgradableAndEssential:NO]) {
9086 if ([package essential])
9087 [essential_ addObject:package];
9092 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9095 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9096 [changesItem setBadgeValue:badge];
9097 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9098 [self setApplicationIconBadgeNumber:changes];
9101 [changesItem setBadgeValue:nil];
9102 [changesItem setAnimatedBadge:NO];
9103 [self setApplicationIconBadgeNumber:0];
9109 - (void) updateData {
9115 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9118 - (void) disemulate {
9119 if (emulated_ == nil)
9122 [window_ addSubview:[tabbar_ view]];
9123 [[emulated_ view] removeFromSuperview];
9125 [window_ setUserInteractionEnabled:YES];
9128 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9129 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9131 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9133 UIViewController *parent;
9134 if (emulated_ == nil)
9143 [parent presentModalViewController:navigation animated:YES];
9146 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9147 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9149 if (navigation != nil)
9150 [navigation pushViewController:progress animated:YES];
9152 [self presentModalViewController:progress force:YES];
9154 [progress invoke:invocation withTitle:title];
9158 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9159 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9162 - (void) repairWithInvocation:(NSInvocation *)invocation {
9164 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9168 - (void) repairWithSelector:(SEL)selector {
9169 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9172 - (void) reloadData {
9173 [self reloadDataWithInvocation:nil];
9174 if ([database_ progressDelegate] == nil)
9180 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9183 - (void) addSource:(NSDictionary *) source {
9187 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9188 AddSource(href, distribution, sections);
9191 - (void) addTrivialSource:(NSString *)href {
9192 AddSource(href, @"./");
9195 - (void) updateValues {
9200 pkgProblemResolver *resolver = [database_ resolver];
9202 resolver->InstallProtect();
9203 if (!resolver->Resolve(true))
9208 // XXX: this is a really crappy way of doing this.
9209 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9210 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9211 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9212 if ([tabbar_ updating])
9213 [tabbar_ cancelUpdate];
9215 if (![database_ prepare])
9218 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9219 [page setDelegate:self];
9220 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9223 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9224 [tabbar_ presentModalViewController:confirm_ animated:YES];
9230 @synchronized (self) {
9235 - (void) clearPackage:(Package *)package {
9236 @synchronized (self) {
9243 - (void) installPackages:(NSArray *)packages {
9244 @synchronized (self) {
9245 for (Package *package in packages)
9252 - (void) installPackage:(Package *)package {
9253 @synchronized (self) {
9260 - (void) removePackage:(Package *)package {
9261 @synchronized (self) {
9268 - (void) distUpgrade {
9269 @synchronized (self) {
9270 if (![database_ upgrade])
9277 [database_ perform];
9278 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9281 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9284 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9286 [self refreshIfPossible];
9289 - (void) showSettings {
9290 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9293 - (void) retainNetworkActivityIndicator {
9294 if (activity_++ == 0)
9295 [self setNetworkActivityIndicatorVisible:YES];
9298 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9302 - (void) releaseNetworkActivityIndicator {
9303 if (--activity_ == 0)
9304 [self setNetworkActivityIndicatorVisible:NO];
9307 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9312 - (void) cancelAndClear:(bool)clear {
9313 @synchronized (self) {
9325 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9326 NSString *context([alert context]);
9328 if ([context isEqualToString:@"conffile"]) {
9329 FILE *input = [database_ input];
9330 if (button == [alert cancelButtonIndex])
9331 fprintf(input, "N\n");
9332 else if (button == [alert firstOtherButtonIndex])
9333 fprintf(input, "Y\n");
9336 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9337 } else if ([context isEqualToString:@"fixhalf"]) {
9338 if (button == [alert cancelButtonIndex]) {
9339 @synchronized (self) {
9340 for (Package *broken in (id) broken_) {
9343 NSString *id = [broken id];
9344 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9345 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9346 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9347 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9353 } else if (button == [alert firstOtherButtonIndex]) {
9354 [broken_ removeAllObjects];
9358 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9359 } else if ([context isEqualToString:@"upgrade"]) {
9360 if (button == [alert firstOtherButtonIndex]) {
9361 @synchronized (self) {
9362 for (Package *essential in (id) essential_)
9363 [essential install];
9368 } else if (button == [alert firstOtherButtonIndex] + 1) {
9370 } else if (button == [alert cancelButtonIndex]) {
9374 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9378 - (void) system:(NSString *)command {
9379 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9382 system([command UTF8String]);
9388 - (void) applicationWillSuspend {
9390 [super applicationWillSuspend];
9393 - (BOOL) isSafeToSuspend {
9396 NSLog(@"isSafeToSuspend: locked_ != 0");
9401 // Use external process status API internally.
9402 // This is probably a really bad idea.
9403 // XXX: what is the point of this? does this solve anything at all?
9404 uint64_t status = 0;
9406 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9407 notify_get_state(notify_token, &status);
9408 notify_cancel(notify_token);
9413 NSLog(@"isSafeToSuspend: status != 0");
9419 NSLog(@"isSafeToSuspend: -> true");
9424 - (void) applicationSuspend:(__GSEvent *)event {
9425 if ([self isSafeToSuspend])
9426 [super applicationSuspend:event];
9429 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9430 if ([self isSafeToSuspend])
9431 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9434 - (void) _setSuspended:(BOOL)value {
9435 if ([self isSafeToSuspend])
9436 [super _setSuspended:value];
9439 - (UIProgressHUD *) addProgressHUD {
9440 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9441 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9443 [window_ setUserInteractionEnabled:NO];
9445 UIViewController *target(tabbar_);
9446 if (UIViewController *modal = [target modalViewController])
9449 UIView *view([target view]);
9450 [view addSubview:hud];
9452 [hud showInView:[tabbar_ view]];
9458 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9461 [hud removeFromSuperview];
9462 [window_ setUserInteractionEnabled:YES];
9465 - (CyteViewController *) pageForPackage:(NSString *)name {
9466 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9469 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9470 NSString *scheme([[url scheme] lowercaseString]);
9471 if ([[url absoluteString] length] <= [scheme length] + 3)
9473 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9474 NSArray *components([path pathComponents]);
9476 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9477 return [self pageForPackage:[components objectAtIndex:1]];
9479 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9482 NSString *base([components objectAtIndex:0]);
9484 CyteViewController *controller = nil;
9486 if ([base isEqualToString:@"url"]) {
9487 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9488 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9489 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9490 } else if (!external && [components count] == 1) {
9491 if ([base isEqualToString:@"manage"]) {
9492 controller = [[[ManageController alloc] init] autorelease];
9495 if ([base isEqualToString:@"sources"]) {
9496 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9499 if ([base isEqualToString:@"home"]) {
9500 controller = [[[HomeController alloc] init] autorelease];
9503 if ([base isEqualToString:@"sections"]) {
9504 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9507 if ([base isEqualToString:@"search"]) {
9508 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9511 if ([base isEqualToString:@"changes"]) {
9512 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9515 if ([base isEqualToString:@"installed"]) {
9516 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9518 } else if ([components count] == 2) {
9519 NSString *argument = [components objectAtIndex:1];
9521 if ([base isEqualToString:@"package"]) {
9522 controller = [self pageForPackage:argument];
9525 if (!external && [base isEqualToString:@"search"]) {
9526 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9529 if (!external && [base isEqualToString:@"sections"]) {
9530 if ([argument isEqualToString:@"all"])
9532 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9535 if (!external && [base isEqualToString:@"sources"]) {
9536 if ([argument isEqualToString:@"add"]) {
9537 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9538 [(SourcesController *)controller showAddSourcePrompt];
9540 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9541 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9545 if (!external && [base isEqualToString:@"launch"]) {
9546 [self launchApplicationWithIdentifier:argument suspended:NO];
9549 } else if (!external && [components count] == 3) {
9550 NSString *arg1 = [components objectAtIndex:1];
9551 NSString *arg2 = [components objectAtIndex:2];
9553 if ([base isEqualToString:@"package"]) {
9554 if ([arg2 isEqualToString:@"settings"]) {
9555 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9556 } else if ([arg2 isEqualToString:@"files"]) {
9557 if (Package *package = [database_ packageWithName:arg1]) {
9558 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9559 [(FileTable *)controller setPackage:package];
9565 [controller setDelegate:self];
9569 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9570 CyteViewController *page([self pageForURL:url forExternal:external]);
9573 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9574 [nav setViewControllers:[NSArray arrayWithObject:page]];
9575 [tabbar_ setUnselectedViewController:nav];
9581 - (void) applicationOpenURL:(NSURL *)url {
9582 [super applicationOpenURL:url];
9587 [self openCydiaURL:url forExternal:YES];
9590 - (void) applicationWillResignActive:(UIApplication *)application {
9591 // Stop refreshing if you get a phone call or lock the device.
9592 if ([tabbar_ updating])
9593 [tabbar_ cancelUpdate];
9595 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9596 [super applicationWillResignActive:application];
9599 - (void) saveState {
9600 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9601 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9602 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9608 - (void) applicationWillTerminate:(UIApplication *)application {
9612 - (void) setConfigurationData:(NSString *)data {
9613 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9615 if (!conffile_r(data)) {
9616 lprintf("E:invalid conffile\n");
9620 NSString *ofile = conffile_r[1];
9621 //NSString *nfile = conffile_r[2];
9623 UIAlertView *alert = [[[UIAlertView alloc]
9624 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9625 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9627 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9629 UCLocalize("ACCEPT_NEW_COPY"),
9630 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9634 [alert setContext:@"conffile"];
9635 [alert setNumberOfRows:2];
9639 - (void) addStashController {
9641 stash_ = [[[StashController alloc] init] autorelease];
9642 [window_ addSubview:[stash_ view]];
9645 - (void) removeStashController {
9646 [[stash_ view] removeFromSuperview];
9652 [self setIdleTimerDisabled:YES];
9654 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9655 UpdateExternalStatus(1);
9656 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9657 UpdateExternalStatus(0);
9659 [self removeStashController];
9661 if (ExecFork() == 0) {
9662 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9663 perror("launchctl stop");
9667 - (void) setupViewControllers {
9668 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9670 NSMutableArray *items([NSMutableArray arrayWithObjects:
9671 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9672 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9673 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9674 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9678 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9679 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9681 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9684 NSMutableArray *controllers([NSMutableArray array]);
9685 for (UITabBarItem *item in items) {
9686 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9687 [controller setTabBarItem:item];
9688 [controllers addObject:controller];
9690 [tabbar_ setViewControllers:controllers];
9692 [tabbar_ setUpdateDelegate:self];
9695 - (void) _sendMemoryWarningNotification {
9696 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9699 - (void) _sendMemoryWarningNotifications {
9701 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9706 - (void) applicationDidFinishLaunching:(id)unused {
9707 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9710 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9711 [self setApplicationSupportsShakeToEdit:NO];
9713 @synchronized (HostConfig_) {
9714 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9717 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9718 initWithMemoryCapacity:524288
9719 diskCapacity:10485760
9720 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9723 [CydiaWebViewController _initialize];
9725 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9727 // this would disallow http{,s} URLs from accessing this data
9728 //[WebView registerURLSchemeAsLocal:@"cydia"];
9730 Font12_ = [UIFont systemFontOfSize:12];
9731 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9732 Font14_ = [UIFont systemFontOfSize:14];
9733 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9734 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9736 essential_ = [NSMutableArray arrayWithCapacity:4];
9737 broken_ = [NSMutableArray arrayWithCapacity:4];
9739 // XXX: I really need this thing... like, seriously... I'm sorry
9740 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9742 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9743 [window_ orderFront:self];
9744 [window_ makeKey:self];
9745 [window_ setHidden:NO];
9748 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9749 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9750 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9751 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9752 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9753 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9754 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9755 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9756 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9759 [self addStashController];
9760 // XXX: this would be much cleaner as a yieldToSelector:
9761 // that way the removeStashController could happen right here inline
9762 // we also could no longer require the useless stash_ field anymore
9763 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9767 database_ = [Database sharedInstance];
9768 [database_ setDelegate:self];
9770 [window_ setUserInteractionEnabled:NO];
9771 [self setupViewControllers];
9773 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9774 [window_ addSubview:[emulated_ view]];
9776 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9780 - (NSArray *) defaultStartPages {
9781 NSMutableArray *standard = [NSMutableArray array];
9782 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9783 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9784 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9786 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9788 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9789 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9791 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9798 [window_ setUserInteractionEnabled:YES];
9799 [self showSettings];
9802 if ([emulated_ modalViewController] != nil)
9803 [emulated_ dismissModalViewControllerAnimated:YES];
9804 [window_ setUserInteractionEnabled:NO];
9807 [self reloadDataWithInvocation:nil];
9808 [self refreshIfPossible];
9813 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9814 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9815 int standardIndex = 0;
9816 NSArray *standard = [self defaultStartPages];
9823 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9824 if (valid && closed != nil) {
9825 NSTimeInterval interval([closed timeIntervalSinceNow]);
9826 // XXX: Is 15 minutes the optimal time here?
9827 if (interval > 0 && interval <= -(15*60))
9831 if (valid && [saved count] != [standard count])
9835 for (unsigned int i = 0; i < [standard count]; i++) {
9836 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9837 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9838 // but it's good enough for now.
9839 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9846 NSArray *items = nil;
9848 [tabbar_ setSelectedIndex:savedIndex];
9851 [tabbar_ setSelectedIndex:standardIndex];
9855 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9856 NSArray *stack = [items objectAtIndex:tab];
9857 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9858 NSMutableArray *current = [NSMutableArray array];
9860 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9861 NSString *addr = [stack objectAtIndex:nav];
9862 NSURL *url = [NSURL URLWithString:addr];
9863 CyteViewController *page = [self pageForURL:url forExternal:NO];
9865 [current addObject:page];
9868 [navigation setViewControllers:current];
9871 // (Try to) show the startup URL.
9872 if (starturl_ != nil) {
9873 [self openCydiaURL:starturl_ forExternal:NO];
9878 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9879 if (item != nil && IsWildcat_) {
9880 [sheet showFromBarButtonItem:item animated:YES];
9882 [sheet showInView:window_];
9886 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9887 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9888 [progress setTitle:task];
9889 [progress addProgressEvent:event];
9892 - (void) addProgressEventForTask:(NSArray *)data {
9893 CydiaProgressEvent *event([data objectAtIndex:0]);
9894 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9895 [self addProgressEvent:event forTask:task];
9898 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9899 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9905 id Alloc_(id self, SEL selector) {
9906 id object = alloc_(self, selector);
9907 lprintf("[%s]A-%p\n", self->isa->name, object);
9912 id Dealloc_(id self, SEL selector) {
9913 id object = dealloc_(self, selector);
9914 lprintf("[%s]D-%p\n", self->isa->name, object);
9918 Class $WebDefaultUIKitDelegate;
9920 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9921 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9922 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9923 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9926 static NSSet *MobilizedFiles_;
9928 static NSURL *MobilizeURL(NSURL *url) {
9929 NSString *path([url path]);
9930 if ([path hasPrefix:@"/var/root/"]) {
9931 NSString *file([path substringFromIndex:10]);
9932 if ([MobilizedFiles_ containsObject:file])
9933 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9939 Class $CFXPreferencesPropertyListSource;
9940 @class CFXPreferencesPropertyListSource;
9942 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9943 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9944 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9945 url = MobilizeURL(url);
9946 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9947 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9953 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9954 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9955 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9956 url = MobilizeURL(url);
9957 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9958 //NSLog(@"%@ %@", [url absoluteString], value);
9964 Class $NSURLConnection;
9966 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9967 NSMutableURLRequest *copy([request mutableCopy]);
9969 NSURL *url([copy URL]);
9971 NSString *href([url absoluteString]);
9972 NSString *host([url host]);
9973 NSString *scheme([[url scheme] lowercaseString]);
9975 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9977 @synchronized (HostConfig_) {
9978 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9979 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9980 [copy setHTTPShouldUsePipelining:YES];
9982 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9983 if ([control isEqualToString:@"max-age=0"])
9984 if ([CachedURLs_ containsObject:href]) {
9986 NSLog(@"~~~: %@", href);
9989 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9991 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9992 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9993 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9997 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10001 int main(int argc, char *argv[]) {
10002 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10006 UpdateExternalStatus(0);
10008 if (Class $UIDevice = objc_getClass("UIDevice")) {
10009 UIDevice *device([$UIDevice currentDevice]);
10010 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10012 IsWildcat_ = false;
10014 UIScreen *screen([UIScreen mainScreen]);
10015 if ([screen respondsToSelector:@selector(scale)])
10016 ScreenScale_ = [screen scale];
10020 UIDevice *device([UIDevice currentDevice]);
10021 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10022 Idiom_ = @"iphone";
10024 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10025 if (idiom == UIUserInterfaceIdiomPhone)
10026 Idiom_ = @"iphone";
10027 else if (idiom == UIUserInterfaceIdiomPad)
10030 NSLog(@"unknown UIUserInterfaceIdiom!");
10033 Pcre pattern("^([0-9]+\\.[0-9]+)");
10034 if (pattern([device systemVersion]))
10035 Firmware_ = pattern[1];
10037 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10039 HostConfig_ = [[[NSObject alloc] init] autorelease];
10040 @synchronized (HostConfig_) {
10041 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10042 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10043 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10044 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10045 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10048 NSString *ui(@"ui/ios");
10050 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10051 UI_ = CydiaURL(ui);
10053 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10055 MobilizedFiles_ = [NSMutableSet setWithObjects:
10056 @"Library/Preferences/com.apple.Accessibility.plist",
10057 @"Library/Preferences/com.apple.preferences.sounds.plist",
10060 /* Library Hacks {{{ */
10061 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10063 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10065 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10066 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10067 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10068 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10071 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10072 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10073 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10074 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10077 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10078 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10079 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10080 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10081 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10084 $NSURLConnection = objc_getClass("NSURLConnection");
10085 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10086 if (NSURLConnection$init$ != NULL) {
10087 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10088 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10091 /* Set Locale {{{ */
10092 Locale_ = CFLocaleCopyCurrent();
10093 Languages_ = [NSLocale preferredLanguages];
10095 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10096 //NSLog(@"%@", [Languages_ description]);
10099 if (Locale_ != NULL)
10100 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10101 else if (Languages_ != nil && [Languages_ count] != 0)
10102 lang = [[Languages_ objectAtIndex:0] UTF8String];
10104 // XXX: consider just setting to C and then falling through?
10107 if (lang != NULL) {
10108 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10109 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10112 NSLog(@"Setting Language: %s", lang);
10114 if (lang != NULL) {
10115 setenv("LANG", lang, true);
10116 std::setlocale(LC_ALL, lang);
10120 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10122 /* Parse Arguments {{{ */
10123 bool substrate(false);
10129 for (int argi(1); argi != argc; ++argi)
10130 if (strcmp(argv[argi], "--") == 0) {
10132 argv[argi] = argv[0];
10138 for (int argi(1); argi != arge; ++argi)
10139 if (strcmp(args[argi], "--substrate") == 0)
10142 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10146 App_ = [[NSBundle mainBundle] bundlePath];
10152 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10153 alloc_ = alloc->method_imp;
10154 alloc->method_imp = (IMP) &Alloc_;*/
10156 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10157 dealloc_ = dealloc->method_imp;
10158 dealloc->method_imp = (IMP) &Dealloc_;*/
10160 /* System Information {{{ */
10164 size = sizeof(maxproc);
10165 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10166 perror("sysctlbyname(\"kern.maxproc\", ?)");
10167 else if (maxproc < 64) {
10169 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10170 perror("sysctlbyname(\"kern.maxproc\", #)");
10173 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10174 char *osversion = new char[size];
10175 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10176 perror("sysctlbyname(\"kern.osversion\", ?)");
10178 System_ = [NSString stringWithUTF8String:osversion];
10180 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10181 char *machine = new char[size];
10182 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10183 perror("sysctlbyname(\"hw.machine\", ?)");
10185 Machine_ = machine;
10187 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10188 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10189 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10191 UniqueID_ = [device uniqueIdentifier];
10193 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10194 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10195 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10197 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10198 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10199 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10201 if (mcc != NULL && mnc != NULL)
10202 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10209 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10210 Build_ = [system objectForKey:@"ProductBuildVersion"];
10211 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10212 Product_ = [info objectForKey:@"SafariProductVersion"];
10213 Safari_ = [info objectForKey:@"CFBundleVersion"];
10216 /* Load Database {{{ */
10218 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10220 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10222 if (Metadata_ == NULL)
10223 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10225 Settings_ = [Metadata_ objectForKey:@"Settings"];
10227 Packages_ = [Metadata_ objectForKey:@"Packages"];
10229 Values_ = [Metadata_ objectForKey:@"Values"];
10230 Sections_ = [Metadata_ objectForKey:@"Sections"];
10231 Sources_ = [Metadata_ objectForKey:@"Sources"];
10233 Token_ = [Metadata_ objectForKey:@"Token"];
10235 Version_ = [Metadata_ objectForKey:@"Version"];
10237 @synchronized (HostConfig_) {
10238 CydiaSource_ = [Metadata_ objectForKey:@"CydiaSource"];
10242 if (Settings_ != nil)
10243 Role_ = [Settings_ objectForKey:@"Role"];
10245 if (Values_ == nil) {
10246 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10247 [Metadata_ setObject:Values_ forKey:@"Values"];
10250 if (Sections_ == nil) {
10251 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10252 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10255 if (Sources_ == nil) {
10256 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10257 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10260 if (Version_ == nil) {
10261 Version_ = [NSNumber numberWithUnsignedInt:0];
10262 [Metadata_ setObject:Version_ forKey:@"Version"];
10265 @synchronized (HostConfig_) {
10266 if (CydiaSource_ == nil) {
10267 CydiaSource_ = @"apt.saurik.com";
10268 [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
10272 if ([Version_ unsignedIntValue] == 0) {
10273 AddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10274 AddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10275 AddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10276 AddSource(@"http://repo666.ultrasn0w.com/", @"./");
10278 Version_ = [NSNumber numberWithUnsignedInt:1];
10279 [Metadata_ setObject:Version_ forKey:@"Version"];
10281 [Metadata_ removeObjectForKey:@"LastUpdate"];
10290 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10293 if (Packages_ != nil) {
10295 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10299 [Metadata_ removeObjectForKey:@"Packages"];
10305 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10307 #define MobileSubstrate_(name) \
10308 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10309 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10310 if (handle == NULL) \
10311 NSLog(@"%s", dlerror()); \
10314 MobileSubstrate_(Activator)
10315 MobileSubstrate_(libstatusbar)
10316 MobileSubstrate_(SimulatedKeyEvents)
10317 MobileSubstrate_(WinterBoard)
10319 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10320 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10322 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10324 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10325 unlink("/tmp/.cydia.fw");
10327 } else if (access("/User", F_OK) != 0 || version < 4) {
10330 system("/usr/libexec/cydia/firmware.sh");
10334 _assert([[NSFileManager defaultManager]
10335 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10336 withIntermediateDirectories:YES
10341 if (access("/tmp/cydia.chk", F_OK) == 0) {
10342 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10343 _assert(errno == ENOENT);
10344 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10345 _assert(errno == ENOENT);
10348 /* APT Initialization {{{ */
10349 _assert(pkgInitConfig(*_config));
10350 _assert(pkgInitSystem(*_config, _system));
10353 _config->Set("APT::Acquire::Translation", lang);
10355 // XXX: this timeout might be important :(
10356 //_config->Set("Acquire::http::Timeout", 15);
10358 _config->Set("Acquire::http::MaxParallel", 3);
10360 /* Color Choices {{{ */
10361 space_ = CGColorSpaceCreateDeviceRGB();
10363 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10364 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10365 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10366 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10367 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10368 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10369 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10370 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10371 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10373 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10374 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10376 /* UIKit Configuration {{{ */
10377 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10378 if ($GSFontSetUseLegacyFontMetrics != NULL)
10379 $GSFontSetUseLegacyFontMetrics(YES);
10381 // XXX: I have a feeling this was important
10382 //UIKeyboardDisableAutomaticAppearance();
10385 Colon_ = UCLocalize("COLON_DELIMITED");
10386 Elision_ = UCLocalize("ELISION");
10387 Error_ = UCLocalize("ERROR");
10388 Warning_ = UCLocalize("WARNING");
10391 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10393 CGColorSpaceRelease(space_);
10394 CFRelease(Locale_);